Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / third_party / sqlite / sqlite-src-3080704 / src / trigger.c
blobd2e7b5a1e6580b0b1be26ac5278dfad763b10fd0
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 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 out 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 sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
152 if( 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),zName) ){
184 if( !noErr ){
185 sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
186 }else{
187 assert( !db->init.busy );
188 sqlite3CodeVerifySchema(pParse, iDb);
190 goto trigger_cleanup;
193 /* Do not create a trigger on a system table */
194 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
195 sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
196 pParse->nErr++;
197 goto trigger_cleanup;
200 /* INSTEAD of triggers are only for views and views only support INSTEAD
201 ** of triggers.
203 if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
204 sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
205 (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
206 goto trigger_cleanup;
208 if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
209 sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
210 " trigger on table: %S", pTableName, 0);
211 goto trigger_cleanup;
213 iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
215 #ifndef SQLITE_OMIT_AUTHORIZATION
217 int code = SQLITE_CREATE_TRIGGER;
218 const char *zDb = db->aDb[iTabDb].zName;
219 const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
220 if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
221 if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
222 goto trigger_cleanup;
224 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
225 goto trigger_cleanup;
228 #endif
230 /* INSTEAD OF triggers can only appear on views and BEFORE triggers
231 ** cannot appear on views. So we might as well translate every
232 ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
233 ** elsewhere.
235 if (tr_tm == TK_INSTEAD){
236 tr_tm = TK_BEFORE;
239 /* Build the Trigger object */
240 pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
241 if( pTrigger==0 ) goto trigger_cleanup;
242 pTrigger->zName = zName;
243 zName = 0;
244 pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
245 pTrigger->pSchema = db->aDb[iDb].pSchema;
246 pTrigger->pTabSchema = pTab->pSchema;
247 pTrigger->op = (u8)op;
248 pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
249 pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
250 pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
251 assert( pParse->pNewTrigger==0 );
252 pParse->pNewTrigger = pTrigger;
254 trigger_cleanup:
255 sqlite3DbFree(db, zName);
256 sqlite3SrcListDelete(db, pTableName);
257 sqlite3IdListDelete(db, pColumns);
258 sqlite3ExprDelete(db, pWhen);
259 if( !pParse->pNewTrigger ){
260 sqlite3DeleteTrigger(db, pTrigger);
261 }else{
262 assert( pParse->pNewTrigger==pTrigger );
267 ** This routine is called after all of the trigger actions have been parsed
268 ** in order to complete the process of building the trigger.
270 void sqlite3FinishTrigger(
271 Parse *pParse, /* Parser context */
272 TriggerStep *pStepList, /* The triggered program */
273 Token *pAll /* Token that describes the complete CREATE TRIGGER */
275 Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */
276 char *zName; /* Name of trigger */
277 sqlite3 *db = pParse->db; /* The database */
278 DbFixer sFix; /* Fixer object */
279 int iDb; /* Database containing the trigger */
280 Token nameToken; /* Trigger name for error reporting */
282 pParse->pNewTrigger = 0;
283 if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
284 zName = pTrig->zName;
285 iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
286 pTrig->step_list = pStepList;
287 while( pStepList ){
288 pStepList->pTrig = pTrig;
289 pStepList = pStepList->pNext;
291 nameToken.z = pTrig->zName;
292 nameToken.n = sqlite3Strlen30(nameToken.z);
293 sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
294 if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
295 || sqlite3FixExpr(&sFix, pTrig->pWhen)
297 goto triggerfinish_cleanup;
300 /* if we are not initializing,
301 ** build the sqlite_master entry
303 if( !db->init.busy ){
304 Vdbe *v;
305 char *z;
307 /* Make an entry in the sqlite_master table */
308 v = sqlite3GetVdbe(pParse);
309 if( v==0 ) goto triggerfinish_cleanup;
310 sqlite3BeginWriteOperation(pParse, 0, iDb);
311 z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
312 sqlite3NestedParse(pParse,
313 "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
314 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
315 pTrig->table, z);
316 sqlite3DbFree(db, z);
317 sqlite3ChangeCookie(pParse, iDb);
318 sqlite3VdbeAddParseSchemaOp(v, iDb,
319 sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
322 if( db->init.busy ){
323 Trigger *pLink = pTrig;
324 Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
325 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
326 pTrig = sqlite3HashInsert(pHash, zName, pTrig);
327 if( pTrig ){
328 db->mallocFailed = 1;
329 }else if( pLink->pSchema==pLink->pTabSchema ){
330 Table *pTab;
331 pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table);
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 Select *pSelect, /* A SELECT statement that supplies values */
399 u8 orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
401 TriggerStep *pTriggerStep;
403 assert(pSelect != 0 || db->mallocFailed);
405 pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
406 if( pTriggerStep ){
407 pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
408 pTriggerStep->pIdList = pColumn;
409 pTriggerStep->orconf = orconf;
410 }else{
411 sqlite3IdListDelete(db, pColumn);
413 sqlite3SelectDelete(db, pSelect);
415 return pTriggerStep;
419 ** Construct a trigger step that implements an UPDATE statement and return
420 ** a pointer to that trigger step. The parser calls this routine when it
421 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
423 TriggerStep *sqlite3TriggerUpdateStep(
424 sqlite3 *db, /* The database connection */
425 Token *pTableName, /* Name of the table to be updated */
426 ExprList *pEList, /* The SET clause: list of column and new values */
427 Expr *pWhere, /* The WHERE clause */
428 u8 orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
430 TriggerStep *pTriggerStep;
432 pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
433 if( pTriggerStep ){
434 pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
435 pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
436 pTriggerStep->orconf = orconf;
438 sqlite3ExprListDelete(db, pEList);
439 sqlite3ExprDelete(db, pWhere);
440 return pTriggerStep;
444 ** Construct a trigger step that implements a DELETE statement and return
445 ** a pointer to that trigger step. The parser calls this routine when it
446 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
448 TriggerStep *sqlite3TriggerDeleteStep(
449 sqlite3 *db, /* Database connection */
450 Token *pTableName, /* The table from which rows are deleted */
451 Expr *pWhere /* The WHERE clause */
453 TriggerStep *pTriggerStep;
455 pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
456 if( pTriggerStep ){
457 pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
458 pTriggerStep->orconf = OE_Default;
460 sqlite3ExprDelete(db, pWhere);
461 return pTriggerStep;
465 ** Recursively delete a Trigger structure
467 void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
468 if( pTrigger==0 ) return;
469 sqlite3DeleteTriggerStep(db, pTrigger->step_list);
470 sqlite3DbFree(db, pTrigger->zName);
471 sqlite3DbFree(db, pTrigger->table);
472 sqlite3ExprDelete(db, pTrigger->pWhen);
473 sqlite3IdListDelete(db, pTrigger->pColumns);
474 sqlite3DbFree(db, pTrigger);
478 ** This function is called to drop a trigger from the database schema.
480 ** This may be called directly from the parser and therefore identifies
481 ** the trigger by name. The sqlite3DropTriggerPtr() routine does the
482 ** same job as this routine except it takes a pointer to the trigger
483 ** instead of the trigger name.
485 void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
486 Trigger *pTrigger = 0;
487 int i;
488 const char *zDb;
489 const char *zName;
490 sqlite3 *db = pParse->db;
492 if( db->mallocFailed ) goto drop_trigger_cleanup;
493 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
494 goto drop_trigger_cleanup;
497 assert( pName->nSrc==1 );
498 zDb = pName->a[0].zDatabase;
499 zName = pName->a[0].zName;
500 assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
501 for(i=OMIT_TEMPDB; i<db->nDb; i++){
502 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
503 if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
504 assert( sqlite3SchemaMutexHeld(db, j, 0) );
505 pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName);
506 if( pTrigger ) break;
508 if( !pTrigger ){
509 if( !noErr ){
510 sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
511 }else{
512 sqlite3CodeVerifyNamedSchema(pParse, zDb);
514 pParse->checkSchema = 1;
515 goto drop_trigger_cleanup;
517 sqlite3DropTriggerPtr(pParse, pTrigger);
519 drop_trigger_cleanup:
520 sqlite3SrcListDelete(db, pName);
524 ** Return a pointer to the Table structure for the table that a trigger
525 ** is set on.
527 static Table *tableOfTrigger(Trigger *pTrigger){
528 return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table);
533 ** Drop a trigger given a pointer to that trigger.
535 void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
536 Table *pTable;
537 Vdbe *v;
538 sqlite3 *db = pParse->db;
539 int iDb;
541 iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
542 assert( iDb>=0 && iDb<db->nDb );
543 pTable = tableOfTrigger(pTrigger);
544 assert( pTable );
545 assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
546 #ifndef SQLITE_OMIT_AUTHORIZATION
548 int code = SQLITE_DROP_TRIGGER;
549 const char *zDb = db->aDb[iDb].zName;
550 const char *zTab = SCHEMA_TABLE(iDb);
551 if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
552 if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
553 sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
554 return;
557 #endif
559 /* Generate code to destroy the database record of the trigger.
561 assert( pTable!=0 );
562 if( (v = sqlite3GetVdbe(pParse))!=0 ){
563 int base;
564 static const int iLn = VDBE_OFFSET_LINENO(2);
565 static const VdbeOpList dropTrigger[] = {
566 { OP_Rewind, 0, ADDR(9), 0},
567 { OP_String8, 0, 1, 0}, /* 1 */
568 { OP_Column, 0, 1, 2},
569 { OP_Ne, 2, ADDR(8), 1},
570 { OP_String8, 0, 1, 0}, /* 4: "trigger" */
571 { OP_Column, 0, 0, 2},
572 { OP_Ne, 2, ADDR(8), 1},
573 { OP_Delete, 0, 0, 0},
574 { OP_Next, 0, ADDR(1), 0}, /* 8 */
577 sqlite3BeginWriteOperation(pParse, 0, iDb);
578 sqlite3OpenMasterTable(pParse, iDb);
579 base = sqlite3VdbeAddOpList(v, ArraySize(dropTrigger), dropTrigger, iLn);
580 sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
581 sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
582 sqlite3ChangeCookie(pParse, iDb);
583 sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
584 sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
585 if( pParse->nMem<3 ){
586 pParse->nMem = 3;
592 ** Remove a trigger from the hash tables of the sqlite* pointer.
594 void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
595 Trigger *pTrigger;
596 Hash *pHash;
598 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
599 pHash = &(db->aDb[iDb].pSchema->trigHash);
600 pTrigger = sqlite3HashInsert(pHash, zName, 0);
601 if( ALWAYS(pTrigger) ){
602 if( pTrigger->pSchema==pTrigger->pTabSchema ){
603 Table *pTab = tableOfTrigger(pTrigger);
604 Trigger **pp;
605 for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
606 *pp = (*pp)->pNext;
608 sqlite3DeleteTrigger(db, pTrigger);
609 db->flags |= SQLITE_InternChanges;
614 ** pEList is the SET clause of an UPDATE statement. Each entry
615 ** in pEList is of the format <id>=<expr>. If any of the entries
616 ** in pEList have an <id> which matches an identifier in pIdList,
617 ** then return TRUE. If pIdList==NULL, then it is considered a
618 ** wildcard that matches anything. Likewise if pEList==NULL then
619 ** it matches anything so always return true. Return false only
620 ** if there is no match.
622 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
623 int e;
624 if( pIdList==0 || NEVER(pEList==0) ) return 1;
625 for(e=0; e<pEList->nExpr; e++){
626 if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
628 return 0;
632 ** Return a list of all triggers on table pTab if there exists at least
633 ** one trigger that must be fired when an operation of type 'op' is
634 ** performed on the table, and, if that operation is an UPDATE, if at
635 ** least one of the columns in pChanges is being modified.
637 Trigger *sqlite3TriggersExist(
638 Parse *pParse, /* Parse context */
639 Table *pTab, /* The table the contains the triggers */
640 int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
641 ExprList *pChanges, /* Columns that change in an UPDATE statement */
642 int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
644 int mask = 0;
645 Trigger *pList = 0;
646 Trigger *p;
648 if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
649 pList = sqlite3TriggerList(pParse, pTab);
651 assert( pList==0 || IsVirtual(pTab)==0 );
652 for(p=pList; p; p=p->pNext){
653 if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
654 mask |= p->tr_tm;
657 if( pMask ){
658 *pMask = mask;
660 return (mask ? pList : 0);
664 ** Convert the pStep->target token into a SrcList and return a pointer
665 ** to that SrcList.
667 ** This routine adds a specific database name, if needed, to the target when
668 ** forming the SrcList. This prevents a trigger in one database from
669 ** referring to a target in another database. An exception is when the
670 ** trigger is in TEMP in which case it can refer to any other database it
671 ** wants.
673 static SrcList *targetSrcList(
674 Parse *pParse, /* The parsing context */
675 TriggerStep *pStep /* The trigger containing the target token */
677 int iDb; /* Index of the database to use */
678 SrcList *pSrc; /* SrcList to be returned */
680 pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
681 if( pSrc ){
682 assert( pSrc->nSrc>0 );
683 assert( pSrc->a!=0 );
684 iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
685 if( iDb==0 || iDb>=2 ){
686 sqlite3 *db = pParse->db;
687 assert( iDb<pParse->db->nDb );
688 pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
691 return pSrc;
695 ** Generate VDBE code for the statements inside the body of a single
696 ** trigger.
698 static int codeTriggerProgram(
699 Parse *pParse, /* The parser context */
700 TriggerStep *pStepList, /* List of statements inside the trigger body */
701 int orconf /* Conflict algorithm. (OE_Abort, etc) */
703 TriggerStep *pStep;
704 Vdbe *v = pParse->pVdbe;
705 sqlite3 *db = pParse->db;
707 assert( pParse->pTriggerTab && pParse->pToplevel );
708 assert( pStepList );
709 assert( v!=0 );
710 for(pStep=pStepList; pStep; pStep=pStep->pNext){
711 /* Figure out the ON CONFLICT policy that will be used for this step
712 ** of the trigger program. If the statement that caused this trigger
713 ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
714 ** the ON CONFLICT policy that was specified as part of the trigger
715 ** step statement. Example:
717 ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
718 ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
719 ** END;
721 ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy
722 ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy
724 pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
725 assert( pParse->okConstFactor==0 );
727 switch( pStep->op ){
728 case TK_UPDATE: {
729 sqlite3Update(pParse,
730 targetSrcList(pParse, pStep),
731 sqlite3ExprListDup(db, pStep->pExprList, 0),
732 sqlite3ExprDup(db, pStep->pWhere, 0),
733 pParse->eOrconf
735 break;
737 case TK_INSERT: {
738 sqlite3Insert(pParse,
739 targetSrcList(pParse, pStep),
740 sqlite3SelectDup(db, pStep->pSelect, 0),
741 sqlite3IdListDup(db, pStep->pIdList),
742 pParse->eOrconf
744 break;
746 case TK_DELETE: {
747 sqlite3DeleteFrom(pParse,
748 targetSrcList(pParse, pStep),
749 sqlite3ExprDup(db, pStep->pWhere, 0)
751 break;
753 default: assert( pStep->op==TK_SELECT ); {
754 SelectDest sDest;
755 Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
756 sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
757 sqlite3Select(pParse, pSelect, &sDest);
758 sqlite3SelectDelete(db, pSelect);
759 break;
762 if( pStep->op!=TK_SELECT ){
763 sqlite3VdbeAddOp0(v, OP_ResetCount);
767 return 0;
770 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
772 ** This function is used to add VdbeComment() annotations to a VDBE
773 ** program. It is not used in production code, only for debugging.
775 static const char *onErrorText(int onError){
776 switch( onError ){
777 case OE_Abort: return "abort";
778 case OE_Rollback: return "rollback";
779 case OE_Fail: return "fail";
780 case OE_Replace: return "replace";
781 case OE_Ignore: return "ignore";
782 case OE_Default: return "default";
784 return "n/a";
786 #endif
789 ** Parse context structure pFrom has just been used to create a sub-vdbe
790 ** (trigger program). If an error has occurred, transfer error information
791 ** from pFrom to pTo.
793 static void transferParseError(Parse *pTo, Parse *pFrom){
794 assert( pFrom->zErrMsg==0 || pFrom->nErr );
795 assert( pTo->zErrMsg==0 || pTo->nErr );
796 if( pTo->nErr==0 ){
797 pTo->zErrMsg = pFrom->zErrMsg;
798 pTo->nErr = pFrom->nErr;
799 }else{
800 sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
805 ** Create and populate a new TriggerPrg object with a sub-program
806 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
808 static TriggerPrg *codeRowTrigger(
809 Parse *pParse, /* Current parse context */
810 Trigger *pTrigger, /* Trigger to code */
811 Table *pTab, /* The table pTrigger is attached to */
812 int orconf /* ON CONFLICT policy to code trigger program with */
814 Parse *pTop = sqlite3ParseToplevel(pParse);
815 sqlite3 *db = pParse->db; /* Database handle */
816 TriggerPrg *pPrg; /* Value to return */
817 Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */
818 Vdbe *v; /* Temporary VM */
819 NameContext sNC; /* Name context for sub-vdbe */
820 SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */
821 Parse *pSubParse; /* Parse context for sub-vdbe */
822 int iEndTrigger = 0; /* Label to jump to if WHEN is false */
824 assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
825 assert( pTop->pVdbe );
827 /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
828 ** are freed if an error occurs, link them into the Parse.pTriggerPrg
829 ** list of the top-level Parse object sooner rather than later. */
830 pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
831 if( !pPrg ) return 0;
832 pPrg->pNext = pTop->pTriggerPrg;
833 pTop->pTriggerPrg = pPrg;
834 pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
835 if( !pProgram ) return 0;
836 sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
837 pPrg->pTrigger = pTrigger;
838 pPrg->orconf = orconf;
839 pPrg->aColmask[0] = 0xffffffff;
840 pPrg->aColmask[1] = 0xffffffff;
842 /* Allocate and populate a new Parse context to use for coding the
843 ** trigger sub-program. */
844 pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
845 if( !pSubParse ) return 0;
846 memset(&sNC, 0, sizeof(sNC));
847 sNC.pParse = pSubParse;
848 pSubParse->db = db;
849 pSubParse->pTriggerTab = pTab;
850 pSubParse->pToplevel = pTop;
851 pSubParse->zAuthContext = pTrigger->zName;
852 pSubParse->eTriggerOp = pTrigger->op;
853 pSubParse->nQueryLoop = pParse->nQueryLoop;
855 v = sqlite3GetVdbe(pSubParse);
856 if( v ){
857 VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
858 pTrigger->zName, onErrorText(orconf),
859 (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
860 (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
861 (pTrigger->op==TK_INSERT ? "INSERT" : ""),
862 (pTrigger->op==TK_DELETE ? "DELETE" : ""),
863 pTab->zName
865 #ifndef SQLITE_OMIT_TRACE
866 sqlite3VdbeChangeP4(v, -1,
867 sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
869 #endif
871 /* If one was specified, code the WHEN clause. If it evaluates to false
872 ** (or NULL) the sub-vdbe is immediately halted by jumping to the
873 ** OP_Halt inserted at the end of the program. */
874 if( pTrigger->pWhen ){
875 pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
876 if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
877 && db->mallocFailed==0
879 iEndTrigger = sqlite3VdbeMakeLabel(v);
880 sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
882 sqlite3ExprDelete(db, pWhen);
885 /* Code the trigger program into the sub-vdbe. */
886 codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
888 /* Insert an OP_Halt at the end of the sub-program. */
889 if( iEndTrigger ){
890 sqlite3VdbeResolveLabel(v, iEndTrigger);
892 sqlite3VdbeAddOp0(v, OP_Halt);
893 VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
895 transferParseError(pParse, pSubParse);
896 if( db->mallocFailed==0 ){
897 pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
899 pProgram->nMem = pSubParse->nMem;
900 pProgram->nCsr = pSubParse->nTab;
901 pProgram->nOnce = pSubParse->nOnce;
902 pProgram->token = (void *)pTrigger;
903 pPrg->aColmask[0] = pSubParse->oldmask;
904 pPrg->aColmask[1] = pSubParse->newmask;
905 sqlite3VdbeDelete(v);
908 assert( !pSubParse->pAinc && !pSubParse->pZombieTab );
909 assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
910 sqlite3ParserReset(pSubParse);
911 sqlite3StackFree(db, pSubParse);
913 return pPrg;
917 ** Return a pointer to a TriggerPrg object containing the sub-program for
918 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
919 ** TriggerPrg object exists, a new object is allocated and populated before
920 ** being returned.
922 static TriggerPrg *getRowTrigger(
923 Parse *pParse, /* Current parse context */
924 Trigger *pTrigger, /* Trigger to code */
925 Table *pTab, /* The table trigger pTrigger is attached to */
926 int orconf /* ON CONFLICT algorithm. */
928 Parse *pRoot = sqlite3ParseToplevel(pParse);
929 TriggerPrg *pPrg;
931 assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
933 /* It may be that this trigger has already been coded (or is in the
934 ** process of being coded). If this is the case, then an entry with
935 ** a matching TriggerPrg.pTrigger field will be present somewhere
936 ** in the Parse.pTriggerPrg list. Search for such an entry. */
937 for(pPrg=pRoot->pTriggerPrg;
938 pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
939 pPrg=pPrg->pNext
942 /* If an existing TriggerPrg could not be located, create a new one. */
943 if( !pPrg ){
944 pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
947 return pPrg;
951 ** Generate code for the trigger program associated with trigger p on
952 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
953 ** function are the same as those described in the header function for
954 ** sqlite3CodeRowTrigger()
956 void sqlite3CodeRowTriggerDirect(
957 Parse *pParse, /* Parse context */
958 Trigger *p, /* Trigger to code */
959 Table *pTab, /* The table to code triggers from */
960 int reg, /* Reg array containing OLD.* and NEW.* values */
961 int orconf, /* ON CONFLICT policy */
962 int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
964 Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
965 TriggerPrg *pPrg;
966 pPrg = getRowTrigger(pParse, p, pTab, orconf);
967 assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
969 /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
970 ** is a pointer to the sub-vdbe containing the trigger program. */
971 if( pPrg ){
972 int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
974 sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
975 sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
976 VdbeComment(
977 (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
979 /* Set the P5 operand of the OP_Program instruction to non-zero if
980 ** recursive invocation of this trigger program is disallowed. Recursive
981 ** invocation is disallowed if (a) the sub-program is really a trigger,
982 ** not a foreign key action, and (b) the flag to enable recursive triggers
983 ** is clear. */
984 sqlite3VdbeChangeP5(v, (u8)bRecursive);
989 ** This is called to code the required FOR EACH ROW triggers for an operation
990 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
991 ** is given by the op parameter. The tr_tm parameter determines whether the
992 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
993 ** parameter pChanges is passed the list of columns being modified.
995 ** If there are no triggers that fire at the specified time for the specified
996 ** operation on pTab, this function is a no-op.
998 ** The reg argument is the address of the first in an array of registers
999 ** that contain the values substituted for the new.* and old.* references
1000 ** in the trigger program. If N is the number of columns in table pTab
1001 ** (a copy of pTab->nCol), then registers are populated as follows:
1003 ** Register Contains
1004 ** ------------------------------------------------------
1005 ** reg+0 OLD.rowid
1006 ** reg+1 OLD.* value of left-most column of pTab
1007 ** ... ...
1008 ** reg+N OLD.* value of right-most column of pTab
1009 ** reg+N+1 NEW.rowid
1010 ** reg+N+2 OLD.* value of left-most column of pTab
1011 ** ... ...
1012 ** reg+N+N+1 NEW.* value of right-most column of pTab
1014 ** For ON DELETE triggers, the registers containing the NEW.* values will
1015 ** never be accessed by the trigger program, so they are not allocated or
1016 ** populated by the caller (there is no data to populate them with anyway).
1017 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
1018 ** are never accessed, and so are not allocated by the caller. So, for an
1019 ** ON INSERT trigger, the value passed to this function as parameter reg
1020 ** is not a readable register, although registers (reg+N) through
1021 ** (reg+N+N+1) are.
1023 ** Parameter orconf is the default conflict resolution algorithm for the
1024 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
1025 ** is the instruction that control should jump to if a trigger program
1026 ** raises an IGNORE exception.
1028 void sqlite3CodeRowTrigger(
1029 Parse *pParse, /* Parse context */
1030 Trigger *pTrigger, /* List of triggers on table pTab */
1031 int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
1032 ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
1033 int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
1034 Table *pTab, /* The table to code triggers from */
1035 int reg, /* The first in an array of registers (see above) */
1036 int orconf, /* ON CONFLICT policy */
1037 int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
1039 Trigger *p; /* Used to iterate through pTrigger list */
1041 assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
1042 assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
1043 assert( (op==TK_UPDATE)==(pChanges!=0) );
1045 for(p=pTrigger; p; p=p->pNext){
1047 /* Sanity checking: The schema for the trigger and for the table are
1048 ** always defined. The trigger must be in the same schema as the table
1049 ** or else it must be a TEMP trigger. */
1050 assert( p->pSchema!=0 );
1051 assert( p->pTabSchema!=0 );
1052 assert( p->pSchema==p->pTabSchema
1053 || p->pSchema==pParse->db->aDb[1].pSchema );
1055 /* Determine whether we should code this trigger */
1056 if( p->op==op
1057 && p->tr_tm==tr_tm
1058 && checkColumnOverlap(p->pColumns, pChanges)
1060 sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
1066 ** Triggers may access values stored in the old.* or new.* pseudo-table.
1067 ** This function returns a 32-bit bitmask indicating which columns of the
1068 ** old.* or new.* tables actually are used by triggers. This information
1069 ** may be used by the caller, for example, to avoid having to load the entire
1070 ** old.* record into memory when executing an UPDATE or DELETE command.
1072 ** Bit 0 of the returned mask is set if the left-most column of the
1073 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
1074 ** the second leftmost column value is required, and so on. If there
1075 ** are more than 32 columns in the table, and at least one of the columns
1076 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
1078 ** It is not possible to determine if the old.rowid or new.rowid column is
1079 ** accessed by triggers. The caller must always assume that it is.
1081 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
1082 ** applies to the old.* table. If 1, the new.* table.
1084 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
1085 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
1086 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
1087 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
1088 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
1090 u32 sqlite3TriggerColmask(
1091 Parse *pParse, /* Parse context */
1092 Trigger *pTrigger, /* List of triggers on table pTab */
1093 ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
1094 int isNew, /* 1 for new.* ref mask, 0 for old.* ref mask */
1095 int tr_tm, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
1096 Table *pTab, /* The table to code triggers from */
1097 int orconf /* Default ON CONFLICT policy for trigger steps */
1099 const int op = pChanges ? TK_UPDATE : TK_DELETE;
1100 u32 mask = 0;
1101 Trigger *p;
1103 assert( isNew==1 || isNew==0 );
1104 for(p=pTrigger; p; p=p->pNext){
1105 if( p->op==op && (tr_tm&p->tr_tm)
1106 && checkColumnOverlap(p->pColumns,pChanges)
1108 TriggerPrg *pPrg;
1109 pPrg = getRowTrigger(pParse, p, pTab, orconf);
1110 if( pPrg ){
1111 mask |= pPrg->aColmask[isNew];
1116 return mask;
1119 #endif /* !defined(SQLITE_OMIT_TRIGGER) */