add pragma cipher_default_use_hmac to toggle global HMAC setting
[sqlcipher.git] / src / trigger.c
blob22c4877b6a3ea3fd340aee9819b16106949849ca
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
13 #include "sqliteInt.h"
15 #ifndef SQLITE_OMIT_TRIGGER
17 ** Delete a linked list of TriggerStep structures.
19 void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
20 while( pTriggerStep ){
21 TriggerStep * pTmp = pTriggerStep;
22 pTriggerStep = pTriggerStep->pNext;
24 sqlite3ExprDelete(db, pTmp->pWhere);
25 sqlite3ExprListDelete(db, pTmp->pExprList);
26 sqlite3SelectDelete(db, pTmp->pSelect);
27 sqlite3IdListDelete(db, pTmp->pIdList);
29 sqlite3DbFree(db, pTmp);
34 ** Given table pTab, return a list of all the triggers attached to
35 ** the table. The list is connected by Trigger.pNext pointers.
37 ** All of the triggers on pTab that are in the same database as pTab
38 ** are already attached to pTab->pTrigger. But there might be additional
39 ** triggers on pTab in the TEMP schema. This routine prepends all
40 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
41 ** and returns the combined list.
43 ** To state it another way: This routine returns a list of all triggers
44 ** that fire off of pTab. The list will include any TEMP triggers on
45 ** pTab as well as the triggers lised in pTab->pTrigger.
47 Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
48 Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
49 Trigger *pList = 0; /* List of triggers to return */
51 if( pParse->disableTriggers ){
52 return 0;
55 if( pTmpSchema!=pTab->pSchema ){
56 HashElem *p;
57 assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
58 for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
59 Trigger *pTrig = (Trigger *)sqliteHashData(p);
60 if( pTrig->pTabSchema==pTab->pSchema
61 && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
63 pTrig->pNext = (pList ? pList : pTab->pTrigger);
64 pList = pTrig;
69 return (pList ? pList : pTab->pTrigger);
73 ** This is called by the parser when it sees a CREATE TRIGGER statement
74 ** up to the point of the BEGIN before the trigger actions. A Trigger
75 ** structure is generated based on the information available and stored
76 ** in pParse->pNewTrigger. After the trigger actions have been parsed, the
77 ** sqlite3FinishTrigger() function is called to complete the trigger
78 ** construction process.
80 void sqlite3BeginTrigger(
81 Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
82 Token *pName1, /* The name of the trigger */
83 Token *pName2, /* The name of the trigger */
84 int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
85 int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
86 IdList *pColumns, /* column list if this is an UPDATE OF trigger */
87 SrcList *pTableName,/* The name of the table/view the trigger applies to */
88 Expr *pWhen, /* WHEN clause */
89 int isTemp, /* True if the TEMPORARY keyword is present */
90 int noErr /* Suppress errors if the trigger already exists */
92 Trigger *pTrigger = 0; /* The new trigger */
93 Table *pTab; /* Table that the trigger fires off of */
94 char *zName = 0; /* Name of the trigger */
95 sqlite3 *db = pParse->db; /* The database connection */
96 int iDb; /* The database to store the trigger in */
97 Token *pName; /* The unqualified db name */
98 DbFixer sFix; /* State vector for the DB fixer */
99 int iTabDb; /* Index of the database holding pTab */
101 assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
102 assert( pName2!=0 );
103 assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
104 assert( op>0 && op<0xff );
105 if( isTemp ){
106 /* If TEMP was specified, then the trigger name may not be qualified. */
107 if( pName2->n>0 ){
108 sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
109 goto trigger_cleanup;
111 iDb = 1;
112 pName = pName1;
113 }else{
114 /* Figure out the db that the the trigger will be created in */
115 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
116 if( iDb<0 ){
117 goto trigger_cleanup;
120 if( !pTableName || db->mallocFailed ){
121 goto trigger_cleanup;
124 /* A long-standing parser bug is that this syntax was allowed:
126 ** CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
127 ** ^^^^^^^^
129 ** To maintain backwards compatibility, ignore the database
130 ** name on pTableName if we are reparsing our of SQLITE_MASTER.
132 if( db->init.busy && iDb!=1 ){
133 sqlite3DbFree(db, pTableName->a[0].zDatabase);
134 pTableName->a[0].zDatabase = 0;
137 /* If the trigger name was unqualified, and the table is a temp table,
138 ** then set iDb to 1 to create the trigger in the temporary database.
139 ** If sqlite3SrcListLookup() returns 0, indicating the table does not
140 ** exist, the error is caught by the block below.
142 pTab = sqlite3SrcListLookup(pParse, pTableName);
143 if( db->init.busy==0 && pName2->n==0 && pTab
144 && pTab->pSchema==db->aDb[1].pSchema ){
145 iDb = 1;
148 /* Ensure the table name matches database name and that the table exists */
149 if( db->mallocFailed ) goto trigger_cleanup;
150 assert( pTableName->nSrc==1 );
151 if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) &&
152 sqlite3FixSrcList(&sFix, pTableName) ){
153 goto trigger_cleanup;
155 pTab = sqlite3SrcListLookup(pParse, pTableName);
156 if( !pTab ){
157 /* The table does not exist. */
158 if( db->init.iDb==1 ){
159 /* Ticket #3810.
160 ** Normally, whenever a table is dropped, all associated triggers are
161 ** dropped too. But if a TEMP trigger is created on a non-TEMP table
162 ** and the table is dropped by a different database connection, the
163 ** trigger is not visible to the database connection that does the
164 ** drop so the trigger cannot be dropped. This results in an
165 ** "orphaned trigger" - a trigger whose associated table is missing.
167 db->init.orphanTrigger = 1;
169 goto trigger_cleanup;
171 if( IsVirtual(pTab) ){
172 sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
173 goto trigger_cleanup;
176 /* Check that the trigger name is not reserved and that no trigger of the
177 ** specified name exists */
178 zName = sqlite3NameFromToken(db, pName);
179 if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
180 goto trigger_cleanup;
182 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
183 if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
184 zName, sqlite3Strlen30(zName)) ){
185 if( !noErr ){
186 sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
187 }else{
188 assert( !db->init.busy );
189 sqlite3CodeVerifySchema(pParse, iDb);
191 goto trigger_cleanup;
194 /* Do not create a trigger on a system table */
195 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
196 sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
197 pParse->nErr++;
198 goto trigger_cleanup;
201 /* INSTEAD of triggers are only for views and views only support INSTEAD
202 ** of triggers.
204 if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
205 sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
206 (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
207 goto trigger_cleanup;
209 if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
210 sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
211 " trigger on table: %S", pTableName, 0);
212 goto trigger_cleanup;
214 iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
216 #ifndef SQLITE_OMIT_AUTHORIZATION
218 int code = SQLITE_CREATE_TRIGGER;
219 const char *zDb = db->aDb[iTabDb].zName;
220 const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
221 if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
222 if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
223 goto trigger_cleanup;
225 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
226 goto trigger_cleanup;
229 #endif
231 /* INSTEAD OF triggers can only appear on views and BEFORE triggers
232 ** cannot appear on views. So we might as well translate every
233 ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
234 ** elsewhere.
236 if (tr_tm == TK_INSTEAD){
237 tr_tm = TK_BEFORE;
240 /* Build the Trigger object */
241 pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
242 if( pTrigger==0 ) goto trigger_cleanup;
243 pTrigger->zName = zName;
244 zName = 0;
245 pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
246 pTrigger->pSchema = db->aDb[iDb].pSchema;
247 pTrigger->pTabSchema = pTab->pSchema;
248 pTrigger->op = (u8)op;
249 pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
250 pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
251 pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
252 assert( pParse->pNewTrigger==0 );
253 pParse->pNewTrigger = pTrigger;
255 trigger_cleanup:
256 sqlite3DbFree(db, zName);
257 sqlite3SrcListDelete(db, pTableName);
258 sqlite3IdListDelete(db, pColumns);
259 sqlite3ExprDelete(db, pWhen);
260 if( !pParse->pNewTrigger ){
261 sqlite3DeleteTrigger(db, pTrigger);
262 }else{
263 assert( pParse->pNewTrigger==pTrigger );
268 ** This routine is called after all of the trigger actions have been parsed
269 ** in order to complete the process of building the trigger.
271 void sqlite3FinishTrigger(
272 Parse *pParse, /* Parser context */
273 TriggerStep *pStepList, /* The triggered program */
274 Token *pAll /* Token that describes the complete CREATE TRIGGER */
276 Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */
277 char *zName; /* Name of trigger */
278 sqlite3 *db = pParse->db; /* The database */
279 DbFixer sFix; /* Fixer object */
280 int iDb; /* Database containing the trigger */
281 Token nameToken; /* Trigger name for error reporting */
283 pParse->pNewTrigger = 0;
284 if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
285 zName = pTrig->zName;
286 iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
287 pTrig->step_list = pStepList;
288 while( pStepList ){
289 pStepList->pTrig = pTrig;
290 pStepList = pStepList->pNext;
292 nameToken.z = pTrig->zName;
293 nameToken.n = sqlite3Strlen30(nameToken.z);
294 if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken)
295 && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
296 goto triggerfinish_cleanup;
299 /* if we are not initializing,
300 ** build the sqlite_master entry
302 if( !db->init.busy ){
303 Vdbe *v;
304 char *z;
306 /* Make an entry in the sqlite_master table */
307 v = sqlite3GetVdbe(pParse);
308 if( v==0 ) goto triggerfinish_cleanup;
309 sqlite3BeginWriteOperation(pParse, 0, iDb);
310 z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
311 sqlite3NestedParse(pParse,
312 "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
313 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
314 pTrig->table, z);
315 sqlite3DbFree(db, z);
316 sqlite3ChangeCookie(pParse, iDb);
317 sqlite3VdbeAddParseSchemaOp(v, iDb,
318 sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
321 if( db->init.busy ){
322 Trigger *pLink = pTrig;
323 Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
324 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
325 pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
326 if( pTrig ){
327 db->mallocFailed = 1;
328 }else if( pLink->pSchema==pLink->pTabSchema ){
329 Table *pTab;
330 int n = sqlite3Strlen30(pLink->table);
331 pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
332 assert( pTab!=0 );
333 pLink->pNext = pTab->pTrigger;
334 pTab->pTrigger = pLink;
338 triggerfinish_cleanup:
339 sqlite3DeleteTrigger(db, pTrig);
340 assert( !pParse->pNewTrigger );
341 sqlite3DeleteTriggerStep(db, pStepList);
345 ** Turn a SELECT statement (that the pSelect parameter points to) into
346 ** a trigger step. Return a pointer to a TriggerStep structure.
348 ** The parser calls this routine when it finds a SELECT statement in
349 ** body of a TRIGGER.
351 TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
352 TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
353 if( pTriggerStep==0 ) {
354 sqlite3SelectDelete(db, pSelect);
355 return 0;
357 pTriggerStep->op = TK_SELECT;
358 pTriggerStep->pSelect = pSelect;
359 pTriggerStep->orconf = OE_Default;
360 return pTriggerStep;
364 ** Allocate space to hold a new trigger step. The allocated space
365 ** holds both the TriggerStep object and the TriggerStep.target.z string.
367 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
369 static TriggerStep *triggerStepAllocate(
370 sqlite3 *db, /* Database connection */
371 u8 op, /* Trigger opcode */
372 Token *pName /* The target name */
374 TriggerStep *pTriggerStep;
376 pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
377 if( pTriggerStep ){
378 char *z = (char*)&pTriggerStep[1];
379 memcpy(z, pName->z, pName->n);
380 pTriggerStep->target.z = z;
381 pTriggerStep->target.n = pName->n;
382 pTriggerStep->op = op;
384 return pTriggerStep;
388 ** Build a trigger step out of an INSERT statement. Return a pointer
389 ** to the new trigger step.
391 ** The parser calls this routine when it sees an INSERT inside the
392 ** body of a trigger.
394 TriggerStep *sqlite3TriggerInsertStep(
395 sqlite3 *db, /* The database connection */
396 Token *pTableName, /* Name of the table into which we insert */
397 IdList *pColumn, /* List of columns in pTableName to insert into */
398 ExprList *pEList, /* The VALUE clause: a list of values to be inserted */
399 Select *pSelect, /* A SELECT statement that supplies values */
400 u8 orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
402 TriggerStep *pTriggerStep;
404 assert(pEList == 0 || pSelect == 0);
405 assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
407 pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
408 if( pTriggerStep ){
409 pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
410 pTriggerStep->pIdList = pColumn;
411 pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
412 pTriggerStep->orconf = orconf;
413 }else{
414 sqlite3IdListDelete(db, pColumn);
416 sqlite3ExprListDelete(db, pEList);
417 sqlite3SelectDelete(db, pSelect);
419 return pTriggerStep;
423 ** Construct a trigger step that implements an UPDATE statement and return
424 ** a pointer to that trigger step. The parser calls this routine when it
425 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
427 TriggerStep *sqlite3TriggerUpdateStep(
428 sqlite3 *db, /* The database connection */
429 Token *pTableName, /* Name of the table to be updated */
430 ExprList *pEList, /* The SET clause: list of column and new values */
431 Expr *pWhere, /* The WHERE clause */
432 u8 orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
434 TriggerStep *pTriggerStep;
436 pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
437 if( pTriggerStep ){
438 pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
439 pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
440 pTriggerStep->orconf = orconf;
442 sqlite3ExprListDelete(db, pEList);
443 sqlite3ExprDelete(db, pWhere);
444 return pTriggerStep;
448 ** Construct a trigger step that implements a DELETE statement and return
449 ** a pointer to that trigger step. The parser calls this routine when it
450 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
452 TriggerStep *sqlite3TriggerDeleteStep(
453 sqlite3 *db, /* Database connection */
454 Token *pTableName, /* The table from which rows are deleted */
455 Expr *pWhere /* The WHERE clause */
457 TriggerStep *pTriggerStep;
459 pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
460 if( pTriggerStep ){
461 pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
462 pTriggerStep->orconf = OE_Default;
464 sqlite3ExprDelete(db, pWhere);
465 return pTriggerStep;
469 ** Recursively delete a Trigger structure
471 void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
472 if( pTrigger==0 ) return;
473 sqlite3DeleteTriggerStep(db, pTrigger->step_list);
474 sqlite3DbFree(db, pTrigger->zName);
475 sqlite3DbFree(db, pTrigger->table);
476 sqlite3ExprDelete(db, pTrigger->pWhen);
477 sqlite3IdListDelete(db, pTrigger->pColumns);
478 sqlite3DbFree(db, pTrigger);
482 ** This function is called to drop a trigger from the database schema.
484 ** This may be called directly from the parser and therefore identifies
485 ** the trigger by name. The sqlite3DropTriggerPtr() routine does the
486 ** same job as this routine except it takes a pointer to the trigger
487 ** instead of the trigger name.
489 void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
490 Trigger *pTrigger = 0;
491 int i;
492 const char *zDb;
493 const char *zName;
494 int nName;
495 sqlite3 *db = pParse->db;
497 if( db->mallocFailed ) goto drop_trigger_cleanup;
498 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
499 goto drop_trigger_cleanup;
502 assert( pName->nSrc==1 );
503 zDb = pName->a[0].zDatabase;
504 zName = pName->a[0].zName;
505 nName = sqlite3Strlen30(zName);
506 assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
507 for(i=OMIT_TEMPDB; i<db->nDb; i++){
508 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
509 if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
510 assert( sqlite3SchemaMutexHeld(db, j, 0) );
511 pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
512 if( pTrigger ) break;
514 if( !pTrigger ){
515 if( !noErr ){
516 sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
517 }else{
518 sqlite3CodeVerifyNamedSchema(pParse, zDb);
520 pParse->checkSchema = 1;
521 goto drop_trigger_cleanup;
523 sqlite3DropTriggerPtr(pParse, pTrigger);
525 drop_trigger_cleanup:
526 sqlite3SrcListDelete(db, pName);
530 ** Return a pointer to the Table structure for the table that a trigger
531 ** is set on.
533 static Table *tableOfTrigger(Trigger *pTrigger){
534 int n = sqlite3Strlen30(pTrigger->table);
535 return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
540 ** Drop a trigger given a pointer to that trigger.
542 void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
543 Table *pTable;
544 Vdbe *v;
545 sqlite3 *db = pParse->db;
546 int iDb;
548 iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
549 assert( iDb>=0 && iDb<db->nDb );
550 pTable = tableOfTrigger(pTrigger);
551 assert( pTable );
552 assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
553 #ifndef SQLITE_OMIT_AUTHORIZATION
555 int code = SQLITE_DROP_TRIGGER;
556 const char *zDb = db->aDb[iDb].zName;
557 const char *zTab = SCHEMA_TABLE(iDb);
558 if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
559 if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
560 sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
561 return;
564 #endif
566 /* Generate code to destroy the database record of the trigger.
568 assert( pTable!=0 );
569 if( (v = sqlite3GetVdbe(pParse))!=0 ){
570 int base;
571 static const VdbeOpList dropTrigger[] = {
572 { OP_Rewind, 0, ADDR(9), 0},
573 { OP_String8, 0, 1, 0}, /* 1 */
574 { OP_Column, 0, 1, 2},
575 { OP_Ne, 2, ADDR(8), 1},
576 { OP_String8, 0, 1, 0}, /* 4: "trigger" */
577 { OP_Column, 0, 0, 2},
578 { OP_Ne, 2, ADDR(8), 1},
579 { OP_Delete, 0, 0, 0},
580 { OP_Next, 0, ADDR(1), 0}, /* 8 */
583 sqlite3BeginWriteOperation(pParse, 0, iDb);
584 sqlite3OpenMasterTable(pParse, iDb);
585 base = sqlite3VdbeAddOpList(v, ArraySize(dropTrigger), dropTrigger);
586 sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
587 sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
588 sqlite3ChangeCookie(pParse, iDb);
589 sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
590 sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
591 if( pParse->nMem<3 ){
592 pParse->nMem = 3;
598 ** Remove a trigger from the hash tables of the sqlite* pointer.
600 void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
601 Trigger *pTrigger;
602 Hash *pHash;
604 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
605 pHash = &(db->aDb[iDb].pSchema->trigHash);
606 pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
607 if( ALWAYS(pTrigger) ){
608 if( pTrigger->pSchema==pTrigger->pTabSchema ){
609 Table *pTab = tableOfTrigger(pTrigger);
610 Trigger **pp;
611 for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
612 *pp = (*pp)->pNext;
614 sqlite3DeleteTrigger(db, pTrigger);
615 db->flags |= SQLITE_InternChanges;
620 ** pEList is the SET clause of an UPDATE statement. Each entry
621 ** in pEList is of the format <id>=<expr>. If any of the entries
622 ** in pEList have an <id> which matches an identifier in pIdList,
623 ** then return TRUE. If pIdList==NULL, then it is considered a
624 ** wildcard that matches anything. Likewise if pEList==NULL then
625 ** it matches anything so always return true. Return false only
626 ** if there is no match.
628 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
629 int e;
630 if( pIdList==0 || NEVER(pEList==0) ) return 1;
631 for(e=0; e<pEList->nExpr; e++){
632 if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
634 return 0;
638 ** Return a list of all triggers on table pTab if there exists at least
639 ** one trigger that must be fired when an operation of type 'op' is
640 ** performed on the table, and, if that operation is an UPDATE, if at
641 ** least one of the columns in pChanges is being modified.
643 Trigger *sqlite3TriggersExist(
644 Parse *pParse, /* Parse context */
645 Table *pTab, /* The table the contains the triggers */
646 int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
647 ExprList *pChanges, /* Columns that change in an UPDATE statement */
648 int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
650 int mask = 0;
651 Trigger *pList = 0;
652 Trigger *p;
654 if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
655 pList = sqlite3TriggerList(pParse, pTab);
657 assert( pList==0 || IsVirtual(pTab)==0 );
658 for(p=pList; p; p=p->pNext){
659 if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
660 mask |= p->tr_tm;
663 if( pMask ){
664 *pMask = mask;
666 return (mask ? pList : 0);
670 ** Convert the pStep->target token into a SrcList and return a pointer
671 ** to that SrcList.
673 ** This routine adds a specific database name, if needed, to the target when
674 ** forming the SrcList. This prevents a trigger in one database from
675 ** referring to a target in another database. An exception is when the
676 ** trigger is in TEMP in which case it can refer to any other database it
677 ** wants.
679 static SrcList *targetSrcList(
680 Parse *pParse, /* The parsing context */
681 TriggerStep *pStep /* The trigger containing the target token */
683 int iDb; /* Index of the database to use */
684 SrcList *pSrc; /* SrcList to be returned */
686 pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
687 if( pSrc ){
688 assert( pSrc->nSrc>0 );
689 assert( pSrc->a!=0 );
690 iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
691 if( iDb==0 || iDb>=2 ){
692 sqlite3 *db = pParse->db;
693 assert( iDb<pParse->db->nDb );
694 pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
697 return pSrc;
701 ** Generate VDBE code for the statements inside the body of a single
702 ** trigger.
704 static int codeTriggerProgram(
705 Parse *pParse, /* The parser context */
706 TriggerStep *pStepList, /* List of statements inside the trigger body */
707 int orconf /* Conflict algorithm. (OE_Abort, etc) */
709 TriggerStep *pStep;
710 Vdbe *v = pParse->pVdbe;
711 sqlite3 *db = pParse->db;
713 assert( pParse->pTriggerTab && pParse->pToplevel );
714 assert( pStepList );
715 assert( v!=0 );
716 for(pStep=pStepList; pStep; pStep=pStep->pNext){
717 /* Figure out the ON CONFLICT policy that will be used for this step
718 ** of the trigger program. If the statement that caused this trigger
719 ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
720 ** the ON CONFLICT policy that was specified as part of the trigger
721 ** step statement. Example:
723 ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
724 ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
725 ** END;
727 ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy
728 ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy
730 pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
732 switch( pStep->op ){
733 case TK_UPDATE: {
734 sqlite3Update(pParse,
735 targetSrcList(pParse, pStep),
736 sqlite3ExprListDup(db, pStep->pExprList, 0),
737 sqlite3ExprDup(db, pStep->pWhere, 0),
738 pParse->eOrconf
740 break;
742 case TK_INSERT: {
743 sqlite3Insert(pParse,
744 targetSrcList(pParse, pStep),
745 sqlite3ExprListDup(db, pStep->pExprList, 0),
746 sqlite3SelectDup(db, pStep->pSelect, 0),
747 sqlite3IdListDup(db, pStep->pIdList),
748 pParse->eOrconf
750 break;
752 case TK_DELETE: {
753 sqlite3DeleteFrom(pParse,
754 targetSrcList(pParse, pStep),
755 sqlite3ExprDup(db, pStep->pWhere, 0)
757 break;
759 default: assert( pStep->op==TK_SELECT ); {
760 SelectDest sDest;
761 Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
762 sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
763 sqlite3Select(pParse, pSelect, &sDest);
764 sqlite3SelectDelete(db, pSelect);
765 break;
768 if( pStep->op!=TK_SELECT ){
769 sqlite3VdbeAddOp0(v, OP_ResetCount);
773 return 0;
776 #ifdef SQLITE_DEBUG
778 ** This function is used to add VdbeComment() annotations to a VDBE
779 ** program. It is not used in production code, only for debugging.
781 static const char *onErrorText(int onError){
782 switch( onError ){
783 case OE_Abort: return "abort";
784 case OE_Rollback: return "rollback";
785 case OE_Fail: return "fail";
786 case OE_Replace: return "replace";
787 case OE_Ignore: return "ignore";
788 case OE_Default: return "default";
790 return "n/a";
792 #endif
795 ** Parse context structure pFrom has just been used to create a sub-vdbe
796 ** (trigger program). If an error has occurred, transfer error information
797 ** from pFrom to pTo.
799 static void transferParseError(Parse *pTo, Parse *pFrom){
800 assert( pFrom->zErrMsg==0 || pFrom->nErr );
801 assert( pTo->zErrMsg==0 || pTo->nErr );
802 if( pTo->nErr==0 ){
803 pTo->zErrMsg = pFrom->zErrMsg;
804 pTo->nErr = pFrom->nErr;
805 }else{
806 sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
811 ** Create and populate a new TriggerPrg object with a sub-program
812 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
814 static TriggerPrg *codeRowTrigger(
815 Parse *pParse, /* Current parse context */
816 Trigger *pTrigger, /* Trigger to code */
817 Table *pTab, /* The table pTrigger is attached to */
818 int orconf /* ON CONFLICT policy to code trigger program with */
820 Parse *pTop = sqlite3ParseToplevel(pParse);
821 sqlite3 *db = pParse->db; /* Database handle */
822 TriggerPrg *pPrg; /* Value to return */
823 Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */
824 Vdbe *v; /* Temporary VM */
825 NameContext sNC; /* Name context for sub-vdbe */
826 SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */
827 Parse *pSubParse; /* Parse context for sub-vdbe */
828 int iEndTrigger = 0; /* Label to jump to if WHEN is false */
830 assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
831 assert( pTop->pVdbe );
833 /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
834 ** are freed if an error occurs, link them into the Parse.pTriggerPrg
835 ** list of the top-level Parse object sooner rather than later. */
836 pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
837 if( !pPrg ) return 0;
838 pPrg->pNext = pTop->pTriggerPrg;
839 pTop->pTriggerPrg = pPrg;
840 pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
841 if( !pProgram ) return 0;
842 sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
843 pPrg->pTrigger = pTrigger;
844 pPrg->orconf = orconf;
845 pPrg->aColmask[0] = 0xffffffff;
846 pPrg->aColmask[1] = 0xffffffff;
848 /* Allocate and populate a new Parse context to use for coding the
849 ** trigger sub-program. */
850 pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
851 if( !pSubParse ) return 0;
852 memset(&sNC, 0, sizeof(sNC));
853 sNC.pParse = pSubParse;
854 pSubParse->db = db;
855 pSubParse->pTriggerTab = pTab;
856 pSubParse->pToplevel = pTop;
857 pSubParse->zAuthContext = pTrigger->zName;
858 pSubParse->eTriggerOp = pTrigger->op;
859 pSubParse->nQueryLoop = pParse->nQueryLoop;
861 v = sqlite3GetVdbe(pSubParse);
862 if( v ){
863 VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
864 pTrigger->zName, onErrorText(orconf),
865 (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
866 (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
867 (pTrigger->op==TK_INSERT ? "INSERT" : ""),
868 (pTrigger->op==TK_DELETE ? "DELETE" : ""),
869 pTab->zName
871 #ifndef SQLITE_OMIT_TRACE
872 sqlite3VdbeChangeP4(v, -1,
873 sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
875 #endif
877 /* If one was specified, code the WHEN clause. If it evaluates to false
878 ** (or NULL) the sub-vdbe is immediately halted by jumping to the
879 ** OP_Halt inserted at the end of the program. */
880 if( pTrigger->pWhen ){
881 pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
882 if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
883 && db->mallocFailed==0
885 iEndTrigger = sqlite3VdbeMakeLabel(v);
886 sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
888 sqlite3ExprDelete(db, pWhen);
891 /* Code the trigger program into the sub-vdbe. */
892 codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
894 /* Insert an OP_Halt at the end of the sub-program. */
895 if( iEndTrigger ){
896 sqlite3VdbeResolveLabel(v, iEndTrigger);
898 sqlite3VdbeAddOp0(v, OP_Halt);
899 VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
901 transferParseError(pParse, pSubParse);
902 if( db->mallocFailed==0 ){
903 pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
905 pProgram->nMem = pSubParse->nMem;
906 pProgram->nCsr = pSubParse->nTab;
907 pProgram->token = (void *)pTrigger;
908 pPrg->aColmask[0] = pSubParse->oldmask;
909 pPrg->aColmask[1] = pSubParse->newmask;
910 sqlite3VdbeDelete(v);
913 assert( !pSubParse->pAinc && !pSubParse->pZombieTab );
914 assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
915 sqlite3StackFree(db, pSubParse);
917 return pPrg;
921 ** Return a pointer to a TriggerPrg object containing the sub-program for
922 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
923 ** TriggerPrg object exists, a new object is allocated and populated before
924 ** being returned.
926 static TriggerPrg *getRowTrigger(
927 Parse *pParse, /* Current parse context */
928 Trigger *pTrigger, /* Trigger to code */
929 Table *pTab, /* The table trigger pTrigger is attached to */
930 int orconf /* ON CONFLICT algorithm. */
932 Parse *pRoot = sqlite3ParseToplevel(pParse);
933 TriggerPrg *pPrg;
935 assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
937 /* It may be that this trigger has already been coded (or is in the
938 ** process of being coded). If this is the case, then an entry with
939 ** a matching TriggerPrg.pTrigger field will be present somewhere
940 ** in the Parse.pTriggerPrg list. Search for such an entry. */
941 for(pPrg=pRoot->pTriggerPrg;
942 pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
943 pPrg=pPrg->pNext
946 /* If an existing TriggerPrg could not be located, create a new one. */
947 if( !pPrg ){
948 pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
951 return pPrg;
955 ** Generate code for the trigger program associated with trigger p on
956 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
957 ** function are the same as those described in the header function for
958 ** sqlite3CodeRowTrigger()
960 void sqlite3CodeRowTriggerDirect(
961 Parse *pParse, /* Parse context */
962 Trigger *p, /* Trigger to code */
963 Table *pTab, /* The table to code triggers from */
964 int reg, /* Reg array containing OLD.* and NEW.* values */
965 int orconf, /* ON CONFLICT policy */
966 int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
968 Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
969 TriggerPrg *pPrg;
970 pPrg = getRowTrigger(pParse, p, pTab, orconf);
971 assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
973 /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
974 ** is a pointer to the sub-vdbe containing the trigger program. */
975 if( pPrg ){
976 int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
978 sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
979 sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
980 VdbeComment(
981 (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
983 /* Set the P5 operand of the OP_Program instruction to non-zero if
984 ** recursive invocation of this trigger program is disallowed. Recursive
985 ** invocation is disallowed if (a) the sub-program is really a trigger,
986 ** not a foreign key action, and (b) the flag to enable recursive triggers
987 ** is clear. */
988 sqlite3VdbeChangeP5(v, (u8)bRecursive);
993 ** This is called to code the required FOR EACH ROW triggers for an operation
994 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
995 ** is given by the op paramater. The tr_tm parameter determines whether the
996 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
997 ** parameter pChanges is passed the list of columns being modified.
999 ** If there are no triggers that fire at the specified time for the specified
1000 ** operation on pTab, this function is a no-op.
1002 ** The reg argument is the address of the first in an array of registers
1003 ** that contain the values substituted for the new.* and old.* references
1004 ** in the trigger program. If N is the number of columns in table pTab
1005 ** (a copy of pTab->nCol), then registers are populated as follows:
1007 ** Register Contains
1008 ** ------------------------------------------------------
1009 ** reg+0 OLD.rowid
1010 ** reg+1 OLD.* value of left-most column of pTab
1011 ** ... ...
1012 ** reg+N OLD.* value of right-most column of pTab
1013 ** reg+N+1 NEW.rowid
1014 ** reg+N+2 OLD.* value of left-most column of pTab
1015 ** ... ...
1016 ** reg+N+N+1 NEW.* value of right-most column of pTab
1018 ** For ON DELETE triggers, the registers containing the NEW.* values will
1019 ** never be accessed by the trigger program, so they are not allocated or
1020 ** populated by the caller (there is no data to populate them with anyway).
1021 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
1022 ** are never accessed, and so are not allocated by the caller. So, for an
1023 ** ON INSERT trigger, the value passed to this function as parameter reg
1024 ** is not a readable register, although registers (reg+N) through
1025 ** (reg+N+N+1) are.
1027 ** Parameter orconf is the default conflict resolution algorithm for the
1028 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
1029 ** is the instruction that control should jump to if a trigger program
1030 ** raises an IGNORE exception.
1032 void sqlite3CodeRowTrigger(
1033 Parse *pParse, /* Parse context */
1034 Trigger *pTrigger, /* List of triggers on table pTab */
1035 int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
1036 ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
1037 int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
1038 Table *pTab, /* The table to code triggers from */
1039 int reg, /* The first in an array of registers (see above) */
1040 int orconf, /* ON CONFLICT policy */
1041 int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
1043 Trigger *p; /* Used to iterate through pTrigger list */
1045 assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
1046 assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
1047 assert( (op==TK_UPDATE)==(pChanges!=0) );
1049 for(p=pTrigger; p; p=p->pNext){
1051 /* Sanity checking: The schema for the trigger and for the table are
1052 ** always defined. The trigger must be in the same schema as the table
1053 ** or else it must be a TEMP trigger. */
1054 assert( p->pSchema!=0 );
1055 assert( p->pTabSchema!=0 );
1056 assert( p->pSchema==p->pTabSchema
1057 || p->pSchema==pParse->db->aDb[1].pSchema );
1059 /* Determine whether we should code this trigger */
1060 if( p->op==op
1061 && p->tr_tm==tr_tm
1062 && checkColumnOverlap(p->pColumns, pChanges)
1064 sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
1070 ** Triggers may access values stored in the old.* or new.* pseudo-table.
1071 ** This function returns a 32-bit bitmask indicating which columns of the
1072 ** old.* or new.* tables actually are used by triggers. This information
1073 ** may be used by the caller, for example, to avoid having to load the entire
1074 ** old.* record into memory when executing an UPDATE or DELETE command.
1076 ** Bit 0 of the returned mask is set if the left-most column of the
1077 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
1078 ** the second leftmost column value is required, and so on. If there
1079 ** are more than 32 columns in the table, and at least one of the columns
1080 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
1082 ** It is not possible to determine if the old.rowid or new.rowid column is
1083 ** accessed by triggers. The caller must always assume that it is.
1085 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
1086 ** applies to the old.* table. If 1, the new.* table.
1088 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
1089 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
1090 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
1091 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
1092 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
1094 u32 sqlite3TriggerColmask(
1095 Parse *pParse, /* Parse context */
1096 Trigger *pTrigger, /* List of triggers on table pTab */
1097 ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
1098 int isNew, /* 1 for new.* ref mask, 0 for old.* ref mask */
1099 int tr_tm, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
1100 Table *pTab, /* The table to code triggers from */
1101 int orconf /* Default ON CONFLICT policy for trigger steps */
1103 const int op = pChanges ? TK_UPDATE : TK_DELETE;
1104 u32 mask = 0;
1105 Trigger *p;
1107 assert( isNew==1 || isNew==0 );
1108 for(p=pTrigger; p; p=p->pNext){
1109 if( p->op==op && (tr_tm&p->tr_tm)
1110 && checkColumnOverlap(p->pColumns,pChanges)
1112 TriggerPrg *pPrg;
1113 pPrg = getRowTrigger(pParse, p, pTab, orconf);
1114 if( pPrg ){
1115 mask |= pPrg->aColmask[isNew];
1120 return mask;
1123 #endif /* !defined(SQLITE_OMIT_TRIGGER) */