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 ** 12 ** 13 ** $Id: trigger.c,v 1.139 2009/05/09 00:18:38 drh Exp $ 14 */ 15 #include "sqliteInt.h" 16 17 #ifndef SQLITE_OMIT_TRIGGER 18 /* 19 ** Delete a linked list of TriggerStep structures. 20 */ 21 void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){ 22 while( pTriggerStep ){ 23 TriggerStep * pTmp = pTriggerStep; 24 pTriggerStep = pTriggerStep->pNext; 25 26 if( pTmp->target.dyn ) sqlite3DbFree(db, (char*)pTmp->target.z); 27 sqlite3ExprDelete(db, pTmp->pWhere); 28 sqlite3ExprListDelete(db, pTmp->pExprList); 29 sqlite3SelectDelete(db, pTmp->pSelect); 30 sqlite3IdListDelete(db, pTmp->pIdList); 31 32 sqlite3DbFree(db, pTmp); 33 } 34 } 35 36 /* 37 ** Given table pTab, return a list of all the triggers attached to 38 ** the table. The list is connected by Trigger.pNext pointers. 39 ** 40 ** All of the triggers on pTab that are in the same database as pTab 41 ** are already attached to pTab->pTrigger. But there might be additional 42 ** triggers on pTab in the TEMP schema. This routine prepends all 43 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list 44 ** and returns the combined list. 45 ** 46 ** To state it another way: This routine returns a list of all triggers 47 ** that fire off of pTab. The list will include any TEMP triggers on 48 ** pTab as well as the triggers lised in pTab->pTrigger. 49 */ 50 Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){ 51 Schema * const pTmpSchema = pParse->db->aDb[1].pSchema; 52 Trigger *pList = 0; /* List of triggers to return */ 53 54 if( pTmpSchema!=pTab->pSchema ){ 55 HashElem *p; 56 for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){ 57 Trigger *pTrig = (Trigger *)sqliteHashData(p); 58 if( pTrig->pTabSchema==pTab->pSchema 59 && 0==sqlite3StrICmp(pTrig->table, pTab->zName) 60 ){ 61 pTrig->pNext = (pList ? pList : pTab->pTrigger); 62 pList = pTrig; 63 } 64 } 65 } 66 67 return (pList ? pList : pTab->pTrigger); 68 } 69 70 /* 71 ** This is called by the parser when it sees a CREATE TRIGGER statement 72 ** up to the point of the BEGIN before the trigger actions. A Trigger 73 ** structure is generated based on the information available and stored 74 ** in pParse->pNewTrigger. After the trigger actions have been parsed, the 75 ** sqlite3FinishTrigger() function is called to complete the trigger 76 ** construction process. 77 */ 78 void sqlite3BeginTrigger( 79 Parse *pParse, /* The parse context of the CREATE TRIGGER statement */ 80 Token *pName1, /* The name of the trigger */ 81 Token *pName2, /* The name of the trigger */ 82 int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */ 83 int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */ 84 IdList *pColumns, /* column list if this is an UPDATE OF trigger */ 85 SrcList *pTableName,/* The name of the table/view the trigger applies to */ 86 Expr *pWhen, /* WHEN clause */ 87 int isTemp, /* True if the TEMPORARY keyword is present */ 88 int noErr /* Suppress errors if the trigger already exists */ 89 ){ 90 Trigger *pTrigger = 0; 91 Table *pTab; 92 char *zName = 0; /* Name of the trigger */ 93 sqlite3 *db = pParse->db; 94 int iDb; /* The database to store the trigger in */ 95 Token *pName; /* The unqualified db name */ 96 DbFixer sFix; 97 int iTabDb; 98 99 assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */ 100 assert( pName2!=0 ); 101 assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE ); 102 assert( op>0 && op<0xff ); 103 if( isTemp ){ 104 /* If TEMP was specified, then the trigger name may not be qualified. */ 105 if( pName2->n>0 ){ 106 sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name"); 107 goto trigger_cleanup; 108 } 109 iDb = 1; 110 pName = pName1; 111 }else{ 112 /* Figure out the db that the the trigger will be created in */ 113 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName); 114 if( iDb<0 ){ 115 goto trigger_cleanup; 116 } 117 } 118 119 /* If the trigger name was unqualified, and the table is a temp table, 120 ** then set iDb to 1 to create the trigger in the temporary database. 121 ** If sqlite3SrcListLookup() returns 0, indicating the table does not 122 ** exist, the error is caught by the block below. 123 */ 124 if( !pTableName || db->mallocFailed ){ 125 goto trigger_cleanup; 126 } 127 pTab = sqlite3SrcListLookup(pParse, pTableName); 128 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){ 129 iDb = 1; 130 } 131 132 /* Ensure the table name matches database name and that the table exists */ 133 if( db->mallocFailed ) goto trigger_cleanup; 134 assert( pTableName->nSrc==1 ); 135 if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) && 136 sqlite3FixSrcList(&sFix, pTableName) ){ 137 goto trigger_cleanup; 138 } 139 pTab = sqlite3SrcListLookup(pParse, pTableName); 140 if( !pTab ){ 141 /* The table does not exist. */ 142 goto trigger_cleanup; 143 } 144 if( IsVirtual(pTab) ){ 145 sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables"); 146 goto trigger_cleanup; 147 } 148 149 /* Check that the trigger name is not reserved and that no trigger of the 150 ** specified name exists */ 151 zName = sqlite3NameFromToken(db, pName); 152 if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ 153 goto trigger_cleanup; 154 } 155 if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash), 156 zName, sqlite3Strlen30(zName)) ){ 157 if( !noErr ){ 158 sqlite3ErrorMsg(pParse, "trigger %T already exists", pName); 159 } 160 goto trigger_cleanup; 161 } 162 163 /* Do not create a trigger on a system table */ 164 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){ 165 sqlite3ErrorMsg(pParse, "cannot create trigger on system table"); 166 pParse->nErr++; 167 goto trigger_cleanup; 168 } 169 170 /* INSTEAD of triggers are only for views and views only support INSTEAD 171 ** of triggers. 172 */ 173 if( pTab->pSelect && tr_tm!=TK_INSTEAD ){ 174 sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S", 175 (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0); 176 goto trigger_cleanup; 177 } 178 if( !pTab->pSelect && tr_tm==TK_INSTEAD ){ 179 sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF" 180 " trigger on table: %S", pTableName, 0); 181 goto trigger_cleanup; 182 } 183 iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema); 184 185 #ifndef SQLITE_OMIT_AUTHORIZATION 186 { 187 int code = SQLITE_CREATE_TRIGGER; 188 const char *zDb = db->aDb[iTabDb].zName; 189 const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb; 190 if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER; 191 if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){ 192 goto trigger_cleanup; 193 } 194 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){ 195 goto trigger_cleanup; 196 } 197 } 198 #endif 199 200 /* INSTEAD OF triggers can only appear on views and BEFORE triggers 201 ** cannot appear on views. So we might as well translate every 202 ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code 203 ** elsewhere. 204 */ 205 if (tr_tm == TK_INSTEAD){ 206 tr_tm = TK_BEFORE; 207 } 208 209 /* Build the Trigger object */ 210 pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger)); 211 if( pTrigger==0 ) goto trigger_cleanup; 212 pTrigger->name = zName; 213 zName = 0; 214 pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName); 215 pTrigger->pSchema = db->aDb[iDb].pSchema; 216 pTrigger->pTabSchema = pTab->pSchema; 217 pTrigger->op = (u8)op; 218 pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER; 219 pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE); 220 pTrigger->pColumns = sqlite3IdListDup(db, pColumns); 221 sqlite3TokenCopy(db, &pTrigger->nameToken, pName); 222 assert( pParse->pNewTrigger==0 ); 223 pParse->pNewTrigger = pTrigger; 224 225 trigger_cleanup: 226 sqlite3DbFree(db, zName); 227 sqlite3SrcListDelete(db, pTableName); 228 sqlite3IdListDelete(db, pColumns); 229 sqlite3ExprDelete(db, pWhen); 230 if( !pParse->pNewTrigger ){ 231 sqlite3DeleteTrigger(db, pTrigger); 232 }else{ 233 assert( pParse->pNewTrigger==pTrigger ); 234 } 235 } 236 237 /* 238 ** This routine is called after all of the trigger actions have been parsed 239 ** in order to complete the process of building the trigger. 240 */ 241 void sqlite3FinishTrigger( 242 Parse *pParse, /* Parser context */ 243 TriggerStep *pStepList, /* The triggered program */ 244 Token *pAll /* Token that describes the complete CREATE TRIGGER */ 245 ){ 246 Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */ 247 char *zName; /* Name of trigger */ 248 sqlite3 *db = pParse->db; /* The database */ 249 DbFixer sFix; 250 int iDb; /* Database containing the trigger */ 251 252 pTrig = pParse->pNewTrigger; 253 pParse->pNewTrigger = 0; 254 if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup; 255 zName = pTrig->name; 256 iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema); 257 pTrig->step_list = pStepList; 258 while( pStepList ){ 259 pStepList->pTrig = pTrig; 260 pStepList = pStepList->pNext; 261 } 262 if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &pTrig->nameToken) 263 && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){ 264 goto triggerfinish_cleanup; 265 } 266 267 /* if we are not initializing, and this trigger is not on a TEMP table, 268 ** build the sqlite_master entry 269 */ 270 if( !db->init.busy ){ 271 Vdbe *v; 272 char *z; 273 274 /* Make an entry in the sqlite_master table */ 275 v = sqlite3GetVdbe(pParse); 276 if( v==0 ) goto triggerfinish_cleanup; 277 sqlite3BeginWriteOperation(pParse, 0, iDb); 278 z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n); 279 sqlite3NestedParse(pParse, 280 "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')", 281 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName, 282 pTrig->table, z); 283 sqlite3DbFree(db, z); 284 sqlite3ChangeCookie(pParse, iDb); 285 sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, sqlite3MPrintf( 286 db, "type='trigger' AND name='%q'", zName), P4_DYNAMIC 287 ); 288 } 289 290 if( db->init.busy ){ 291 Trigger *pLink = pTrig; 292 Hash *pHash = &db->aDb[iDb].pSchema->trigHash; 293 pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig); 294 if( pTrig ){ 295 db->mallocFailed = 1; 296 }else if( pLink->pSchema==pLink->pTabSchema ){ 297 Table *pTab; 298 int n = sqlite3Strlen30(pLink->table); 299 pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n); 300 assert( pTab!=0 ); 301 pLink->pNext = pTab->pTrigger; 302 pTab->pTrigger = pLink; 303 } 304 } 305 306 triggerfinish_cleanup: 307 sqlite3DeleteTrigger(db, pTrig); 308 assert( !pParse->pNewTrigger ); 309 sqlite3DeleteTriggerStep(db, pStepList); 310 } 311 312 /* 313 ** Make a copy of all components of the given trigger step. This has 314 ** the effect of copying all Expr.token.z values into memory obtained 315 ** from sqlite3_malloc(). As initially created, the Expr.token.z values 316 ** all point to the input string that was fed to the parser. But that 317 ** string is ephemeral - it will go away as soon as the sqlite3_exec() 318 ** call that started the parser exits. This routine makes a persistent 319 ** copy of all the Expr.token.z strings so that the TriggerStep structure 320 ** will be valid even after the sqlite3_exec() call returns. 321 */ 322 static void sqlitePersistTriggerStep(sqlite3 *db, TriggerStep *p){ 323 if( p->target.z ){ 324 p->target.z = (u8*)sqlite3DbStrNDup(db, (char*)p->target.z, p->target.n); 325 p->target.dyn = 1; 326 } 327 if( p->pSelect ){ 328 Select *pNew = sqlite3SelectDup(db, p->pSelect, 1); 329 sqlite3SelectDelete(db, p->pSelect); 330 p->pSelect = pNew; 331 } 332 if( p->pWhere ){ 333 Expr *pNew = sqlite3ExprDup(db, p->pWhere, EXPRDUP_REDUCE); 334 sqlite3ExprDelete(db, p->pWhere); 335 p->pWhere = pNew; 336 } 337 if( p->pExprList ){ 338 ExprList *pNew = sqlite3ExprListDup(db, p->pExprList, 1); 339 sqlite3ExprListDelete(db, p->pExprList); 340 p->pExprList = pNew; 341 } 342 if( p->pIdList ){ 343 IdList *pNew = sqlite3IdListDup(db, p->pIdList); 344 sqlite3IdListDelete(db, p->pIdList); 345 p->pIdList = pNew; 346 } 347 } 348 349 /* 350 ** Turn a SELECT statement (that the pSelect parameter points to) into 351 ** a trigger step. Return a pointer to a TriggerStep structure. 352 ** 353 ** The parser calls this routine when it finds a SELECT statement in 354 ** body of a TRIGGER. 355 */ 356 TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){ 357 TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep)); 358 if( pTriggerStep==0 ) { 359 sqlite3SelectDelete(db, pSelect); 360 return 0; 361 } 362 363 pTriggerStep->op = TK_SELECT; 364 pTriggerStep->pSelect = pSelect; 365 pTriggerStep->orconf = OE_Default; 366 sqlitePersistTriggerStep(db, pTriggerStep); 367 368 return pTriggerStep; 369 } 370 371 /* 372 ** Build a trigger step out of an INSERT statement. Return a pointer 373 ** to the new trigger step. 374 ** 375 ** The parser calls this routine when it sees an INSERT inside the 376 ** body of a trigger. 377 */ 378 TriggerStep *sqlite3TriggerInsertStep( 379 sqlite3 *db, /* The database connection */ 380 Token *pTableName, /* Name of the table into which we insert */ 381 IdList *pColumn, /* List of columns in pTableName to insert into */ 382 ExprList *pEList, /* The VALUE clause: a list of values to be inserted */ 383 Select *pSelect, /* A SELECT statement that supplies values */ 384 int orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */ 385 ){ 386 TriggerStep *pTriggerStep; 387 388 assert(pEList == 0 || pSelect == 0); 389 assert(pEList != 0 || pSelect != 0 || db->mallocFailed); 390 391 pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep)); 392 if( pTriggerStep ){ 393 pTriggerStep->op = TK_INSERT; 394 pTriggerStep->pSelect = pSelect; 395 pTriggerStep->target = *pTableName; 396 pTriggerStep->pIdList = pColumn; 397 pTriggerStep->pExprList = pEList; 398 pTriggerStep->orconf = orconf; 399 sqlitePersistTriggerStep(db, pTriggerStep); 400 }else{ 401 sqlite3IdListDelete(db, pColumn); 402 sqlite3ExprListDelete(db, pEList); 403 sqlite3SelectDelete(db, pSelect); 404 } 405 406 return pTriggerStep; 407 } 408 409 /* 410 ** Construct a trigger step that implements an UPDATE statement and return 411 ** a pointer to that trigger step. The parser calls this routine when it 412 ** sees an UPDATE statement inside the body of a CREATE TRIGGER. 413 */ 414 TriggerStep *sqlite3TriggerUpdateStep( 415 sqlite3 *db, /* The database connection */ 416 Token *pTableName, /* Name of the table to be updated */ 417 ExprList *pEList, /* The SET clause: list of column and new values */ 418 Expr *pWhere, /* The WHERE clause */ 419 int orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */ 420 ){ 421 TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep)); 422 if( pTriggerStep==0 ){ 423 sqlite3ExprListDelete(db, pEList); 424 sqlite3ExprDelete(db, pWhere); 425 return 0; 426 } 427 428 pTriggerStep->op = TK_UPDATE; 429 pTriggerStep->target = *pTableName; 430 pTriggerStep->pExprList = pEList; 431 pTriggerStep->pWhere = pWhere; 432 pTriggerStep->orconf = orconf; 433 sqlitePersistTriggerStep(db, pTriggerStep); 434 435 return pTriggerStep; 436 } 437 438 /* 439 ** Construct a trigger step that implements a DELETE statement and return 440 ** a pointer to that trigger step. The parser calls this routine when it 441 ** sees a DELETE statement inside the body of a CREATE TRIGGER. 442 */ 443 TriggerStep *sqlite3TriggerDeleteStep( 444 sqlite3 *db, /* Database connection */ 445 Token *pTableName, /* The table from which rows are deleted */ 446 Expr *pWhere /* The WHERE clause */ 447 ){ 448 TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep)); 449 if( pTriggerStep==0 ){ 450 sqlite3ExprDelete(db, pWhere); 451 return 0; 452 } 453 454 pTriggerStep->op = TK_DELETE; 455 pTriggerStep->target = *pTableName; 456 pTriggerStep->pWhere = pWhere; 457 pTriggerStep->orconf = OE_Default; 458 sqlitePersistTriggerStep(db, pTriggerStep); 459 460 return pTriggerStep; 461 } 462 463 /* 464 ** Recursively delete a Trigger structure 465 */ 466 void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){ 467 if( pTrigger==0 ) return; 468 sqlite3DeleteTriggerStep(db, pTrigger->step_list); 469 sqlite3DbFree(db, pTrigger->name); 470 sqlite3DbFree(db, pTrigger->table); 471 sqlite3ExprDelete(db, pTrigger->pWhen); 472 sqlite3IdListDelete(db, pTrigger->pColumns); 473 assert( pTrigger->nameToken.dyn ); 474 sqlite3DbFree(db, (char*)pTrigger->nameToken.z); 475 sqlite3DbFree(db, pTrigger); 476 } 477 478 /* 479 ** This function is called to drop a trigger from the database schema. 480 ** 481 ** This may be called directly from the parser and therefore identifies 482 ** the trigger by name. The sqlite3DropTriggerPtr() routine does the 483 ** same job as this routine except it takes a pointer to the trigger 484 ** instead of the trigger name. 485 **/ 486 void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){ 487 Trigger *pTrigger = 0; 488 int i; 489 const char *zDb; 490 const char *zName; 491 int nName; 492 sqlite3 *db = pParse->db; 493 494 if( db->mallocFailed ) goto drop_trigger_cleanup; 495 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ 496 goto drop_trigger_cleanup; 497 } 498 499 assert( pName->nSrc==1 ); 500 zDb = pName->a[0].zDatabase; 501 zName = pName->a[0].zName; 502 nName = sqlite3Strlen30(zName); 503 for(i=OMIT_TEMPDB; i<db->nDb; i++){ 504 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */ 505 if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue; 506 pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName); 507 if( pTrigger ) break; 508 } 509 if( !pTrigger ){ 510 if( !noErr ){ 511 sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0); 512 } 513 goto drop_trigger_cleanup; 514 } 515 sqlite3DropTriggerPtr(pParse, pTrigger); 516 517 drop_trigger_cleanup: 518 sqlite3SrcListDelete(db, pName); 519 } 520 521 /* 522 ** Return a pointer to the Table structure for the table that a trigger 523 ** is set on. 524 */ 525 static Table *tableOfTrigger(Trigger *pTrigger){ 526 int n = sqlite3Strlen30(pTrigger->table); 527 return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n); 528 } 529 530 531 /* 532 ** Drop a trigger given a pointer to that trigger. 533 */ 534 void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){ 535 Table *pTable; 536 Vdbe *v; 537 sqlite3 *db = pParse->db; 538 int iDb; 539 540 iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema); 541 assert( iDb>=0 && iDb<db->nDb ); 542 pTable = tableOfTrigger(pTrigger); 543 assert( pTable ); 544 assert( pTable->pSchema==pTrigger->pSchema || iDb==1 ); 545 #ifndef SQLITE_OMIT_AUTHORIZATION 546 { 547 int code = SQLITE_DROP_TRIGGER; 548 const char *zDb = db->aDb[iDb].zName; 549 const char *zTab = SCHEMA_TABLE(iDb); 550 if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER; 551 if( sqlite3AuthCheck(pParse, code, pTrigger->name, pTable->zName, zDb) || 552 sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){ 553 return; 554 } 555 } 556 #endif 557 558 /* Generate code to destroy the database record of the trigger. 559 */ 560 assert( pTable!=0 ); 561 if( (v = sqlite3GetVdbe(pParse))!=0 ){ 562 int base; 563 static const VdbeOpList dropTrigger[] = { 564 { OP_Rewind, 0, ADDR(9), 0}, 565 { OP_String8, 0, 1, 0}, /* 1 */ 566 { OP_Column, 0, 1, 2}, 567 { OP_Ne, 2, ADDR(8), 1}, 568 { OP_String8, 0, 1, 0}, /* 4: "trigger" */ 569 { OP_Column, 0, 0, 2}, 570 { OP_Ne, 2, ADDR(8), 1}, 571 { OP_Delete, 0, 0, 0}, 572 { OP_Next, 0, ADDR(1), 0}, /* 8 */ 573 }; 574 575 sqlite3BeginWriteOperation(pParse, 0, iDb); 576 sqlite3OpenMasterTable(pParse, iDb); 577 base = sqlite3VdbeAddOpList(v, ArraySize(dropTrigger), dropTrigger); 578 sqlite3VdbeChangeP4(v, base+1, pTrigger->name, 0); 579 sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC); 580 sqlite3ChangeCookie(pParse, iDb); 581 sqlite3VdbeAddOp2(v, OP_Close, 0, 0); 582 sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->name, 0); 583 if( pParse->nMem<3 ){ 584 pParse->nMem = 3; 585 } 586 } 587 } 588 589 /* 590 ** Remove a trigger from the hash tables of the sqlite* pointer. 591 */ 592 void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){ 593 Hash *pHash = &(db->aDb[iDb].pSchema->trigHash); 594 Trigger *pTrigger; 595 pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0); 596 if( ALWAYS(pTrigger) ){ 597 if( pTrigger->pSchema==pTrigger->pTabSchema ){ 598 Table *pTab = tableOfTrigger(pTrigger); 599 Trigger **pp; 600 for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext)); 601 *pp = (*pp)->pNext; 602 } 603 sqlite3DeleteTrigger(db, pTrigger); 604 db->flags |= SQLITE_InternChanges; 605 } 606 } 607 608 /* 609 ** pEList is the SET clause of an UPDATE statement. Each entry 610 ** in pEList is of the format <id>=<expr>. If any of the entries 611 ** in pEList have an <id> which matches an identifier in pIdList, 612 ** then return TRUE. If pIdList==NULL, then it is considered a 613 ** wildcard that matches anything. Likewise if pEList==NULL then 614 ** it matches anything so always return true. Return false only 615 ** if there is no match. 616 */ 617 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){ 618 int e; 619 if( pIdList==0 || NEVER(pEList==0) ) return 1; 620 for(e=0; e<pEList->nExpr; e++){ 621 if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1; 622 } 623 return 0; 624 } 625 626 /* 627 ** Return a list of all triggers on table pTab if there exists at least 628 ** one trigger that must be fired when an operation of type 'op' is 629 ** performed on the table, and, if that operation is an UPDATE, if at 630 ** least one of the columns in pChanges is being modified. 631 */ 632 Trigger *sqlite3TriggersExist( 633 Parse *pParse, /* Parse context */ 634 Table *pTab, /* The table the contains the triggers */ 635 int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */ 636 ExprList *pChanges, /* Columns that change in an UPDATE statement */ 637 int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */ 638 ){ 639 int mask = 0; 640 Trigger *pList = sqlite3TriggerList(pParse, pTab); 641 Trigger *p; 642 assert( pList==0 || IsVirtual(pTab)==0 ); 643 for(p=pList; p; p=p->pNext){ 644 if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){ 645 mask |= p->tr_tm; 646 } 647 } 648 if( pMask ){ 649 *pMask = mask; 650 } 651 return (mask ? pList : 0); 652 } 653 654 /* 655 ** Convert the pStep->target token into a SrcList and return a pointer 656 ** to that SrcList. 657 ** 658 ** This routine adds a specific database name, if needed, to the target when 659 ** forming the SrcList. This prevents a trigger in one database from 660 ** referring to a target in another database. An exception is when the 661 ** trigger is in TEMP in which case it can refer to any other database it 662 ** wants. 663 */ 664 static SrcList *targetSrcList( 665 Parse *pParse, /* The parsing context */ 666 TriggerStep *pStep /* The trigger containing the target token */ 667 ){ 668 Token sDb; /* Dummy database name token */ 669 int iDb; /* Index of the database to use */ 670 SrcList *pSrc; /* SrcList to be returned */ 671 672 iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema); 673 if( iDb==0 || iDb>=2 ){ 674 assert( iDb<pParse->db->nDb ); 675 sDb.z = (u8*)pParse->db->aDb[iDb].zName; 676 sDb.n = sqlite3Strlen30((char*)sDb.z); 677 sDb.quoted = 0; 678 pSrc = sqlite3SrcListAppend(pParse->db, 0, &sDb, &pStep->target); 679 } else { 680 pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0); 681 } 682 return pSrc; 683 } 684 685 /* 686 ** Generate VDBE code for zero or more statements inside the body of a 687 ** trigger. 688 */ 689 static int codeTriggerProgram( 690 Parse *pParse, /* The parser context */ 691 TriggerStep *pStepList, /* List of statements inside the trigger body */ 692 int orconfin /* Conflict algorithm. (OE_Abort, etc) */ 693 ){ 694 TriggerStep * pTriggerStep = pStepList; 695 int orconf; 696 Vdbe *v = pParse->pVdbe; 697 sqlite3 *db = pParse->db; 698 699 assert( pTriggerStep!=0 ); 700 assert( v!=0 ); 701 sqlite3VdbeAddOp2(v, OP_ContextPush, 0, 0); 702 VdbeComment((v, "begin trigger %s", pStepList->pTrig->name)); 703 while( pTriggerStep ){ 704 sqlite3ExprCacheClear(pParse); 705 orconf = (orconfin == OE_Default)?pTriggerStep->orconf:orconfin; 706 pParse->trigStack->orconf = orconf; 707 switch( pTriggerStep->op ){ 708 case TK_UPDATE: { 709 SrcList *pSrc; 710 pSrc = targetSrcList(pParse, pTriggerStep); 711 sqlite3VdbeAddOp2(v, OP_ResetCount, 0, 0); 712 sqlite3Update(pParse, pSrc, 713 sqlite3ExprListDup(db, pTriggerStep->pExprList, 0), 714 sqlite3ExprDup(db, pTriggerStep->pWhere, 0), orconf); 715 sqlite3VdbeAddOp2(v, OP_ResetCount, 1, 0); 716 break; 717 } 718 case TK_INSERT: { 719 SrcList *pSrc; 720 pSrc = targetSrcList(pParse, pTriggerStep); 721 sqlite3VdbeAddOp2(v, OP_ResetCount, 0, 0); 722 sqlite3Insert(pParse, pSrc, 723 sqlite3ExprListDup(db, pTriggerStep->pExprList, 0), 724 sqlite3SelectDup(db, pTriggerStep->pSelect, 0), 725 sqlite3IdListDup(db, pTriggerStep->pIdList), orconf); 726 sqlite3VdbeAddOp2(v, OP_ResetCount, 1, 0); 727 break; 728 } 729 case TK_DELETE: { 730 SrcList *pSrc; 731 sqlite3VdbeAddOp2(v, OP_ResetCount, 0, 0); 732 pSrc = targetSrcList(pParse, pTriggerStep); 733 sqlite3DeleteFrom(pParse, pSrc, 734 sqlite3ExprDup(db, pTriggerStep->pWhere, 0)); 735 sqlite3VdbeAddOp2(v, OP_ResetCount, 1, 0); 736 break; 737 } 738 default: assert( pTriggerStep->op==TK_SELECT ); { 739 Select *ss = sqlite3SelectDup(db, pTriggerStep->pSelect, 0); 740 if( ss ){ 741 SelectDest dest; 742 743 sqlite3SelectDestInit(&dest, SRT_Discard, 0); 744 sqlite3Select(pParse, ss, &dest); 745 sqlite3SelectDelete(db, ss); 746 } 747 break; 748 } 749 } 750 pTriggerStep = pTriggerStep->pNext; 751 } 752 sqlite3VdbeAddOp2(v, OP_ContextPop, 0, 0); 753 VdbeComment((v, "end trigger %s", pStepList->pTrig->name)); 754 755 return 0; 756 } 757 758 /* 759 ** This is called to code FOR EACH ROW triggers. 760 ** 761 ** When the code that this function generates is executed, the following 762 ** must be true: 763 ** 764 ** 1. No cursors may be open in the main database. (But newIdx and oldIdx 765 ** can be indices of cursors in temporary tables. See below.) 766 ** 767 ** 2. If the triggers being coded are ON INSERT or ON UPDATE triggers, then 768 ** a temporary vdbe cursor (index newIdx) must be open and pointing at 769 ** a row containing values to be substituted for new.* expressions in the 770 ** trigger program(s). 771 ** 772 ** 3. If the triggers being coded are ON DELETE or ON UPDATE triggers, then 773 ** a temporary vdbe cursor (index oldIdx) must be open and pointing at 774 ** a row containing values to be substituted for old.* expressions in the 775 ** trigger program(s). 776 ** 777 ** If they are not NULL, the piOldColMask and piNewColMask output variables 778 ** are set to values that describe the columns used by the trigger program 779 ** in the OLD.* and NEW.* tables respectively. If column N of the 780 ** pseudo-table is read at least once, the corresponding bit of the output 781 ** mask is set. If a column with an index greater than 32 is read, the 782 ** output mask is set to the special value 0xffffffff. 783 ** 784 */ 785 int sqlite3CodeRowTrigger( 786 Parse *pParse, /* Parse context */ 787 Trigger *pTrigger, /* List of triggers on table pTab */ 788 int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */ 789 ExprList *pChanges, /* Changes list for any UPDATE OF triggers */ 790 int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */ 791 Table *pTab, /* The table to code triggers from */ 792 int newIdx, /* The indice of the "new" row to access */ 793 int oldIdx, /* The indice of the "old" row to access */ 794 int orconf, /* ON CONFLICT policy */ 795 int ignoreJump, /* Instruction to jump to for RAISE(IGNORE) */ 796 u32 *piOldColMask, /* OUT: Mask of columns used from the OLD.* table */ 797 u32 *piNewColMask /* OUT: Mask of columns used from the NEW.* table */ 798 ){ 799 Trigger *p; 800 sqlite3 *db = pParse->db; 801 TriggerStack trigStackEntry; 802 803 trigStackEntry.oldColMask = 0; 804 trigStackEntry.newColMask = 0; 805 806 assert(op == TK_UPDATE || op == TK_INSERT || op == TK_DELETE); 807 assert(tr_tm == TRIGGER_BEFORE || tr_tm == TRIGGER_AFTER ); 808 809 assert(newIdx != -1 || oldIdx != -1); 810 811 for(p=pTrigger; p; p=p->pNext){ 812 int fire_this = 0; 813 814 /* Sanity checking: The schema for the trigger and for the table are 815 ** always defined. The trigger must be in the same schema as the table 816 ** or else it must be a TEMP trigger. */ 817 assert( p->pSchema!=0 ); 818 assert( p->pTabSchema!=0 ); 819 assert( p->pSchema==p->pTabSchema || p->pSchema==db->aDb[1].pSchema ); 820 821 /* Determine whether we should code this trigger */ 822 if( 823 p->op==op && 824 p->tr_tm==tr_tm && 825 checkColumnOverlap(p->pColumns,pChanges) 826 ){ 827 TriggerStack *pS; /* Pointer to trigger-stack entry */ 828 for(pS=pParse->trigStack; pS && p!=pS->pTrigger; pS=pS->pNext){} 829 if( !pS ){ 830 fire_this = 1; 831 } 832 #if 0 /* Give no warning for recursive triggers. Just do not do them */ 833 else{ 834 sqlite3ErrorMsg(pParse, "recursive triggers not supported (%s)", 835 p->name); 836 return SQLITE_ERROR; 837 } 838 #endif 839 } 840 841 if( fire_this ){ 842 int endTrigger; 843 Expr * whenExpr; 844 AuthContext sContext; 845 NameContext sNC; 846 847 #ifndef SQLITE_OMIT_TRACE 848 sqlite3VdbeAddOp4(pParse->pVdbe, OP_Trace, 0, 0, 0, 849 sqlite3MPrintf(db, "-- TRIGGER %s", p->name), 850 P4_DYNAMIC); 851 #endif 852 memset(&sNC, 0, sizeof(sNC)); 853 sNC.pParse = pParse; 854 855 /* Push an entry on to the trigger stack */ 856 trigStackEntry.pTrigger = p; 857 trigStackEntry.newIdx = newIdx; 858 trigStackEntry.oldIdx = oldIdx; 859 trigStackEntry.pTab = pTab; 860 trigStackEntry.pNext = pParse->trigStack; 861 trigStackEntry.ignoreJump = ignoreJump; 862 pParse->trigStack = &trigStackEntry; 863 sqlite3AuthContextPush(pParse, &sContext, p->name); 864 865 /* code the WHEN clause */ 866 endTrigger = sqlite3VdbeMakeLabel(pParse->pVdbe); 867 whenExpr = sqlite3ExprDup(db, p->pWhen, 0); 868 if( db->mallocFailed || sqlite3ResolveExprNames(&sNC, whenExpr) ){ 869 pParse->trigStack = trigStackEntry.pNext; 870 sqlite3ExprDelete(db, whenExpr); 871 return 1; 872 } 873 sqlite3ExprIfFalse(pParse, whenExpr, endTrigger, SQLITE_JUMPIFNULL); 874 sqlite3ExprDelete(db, whenExpr); 875 876 codeTriggerProgram(pParse, p->step_list, orconf); 877 878 /* Pop the entry off the trigger stack */ 879 pParse->trigStack = trigStackEntry.pNext; 880 sqlite3AuthContextPop(&sContext); 881 882 sqlite3VdbeResolveLabel(pParse->pVdbe, endTrigger); 883 } 884 } 885 if( piOldColMask ) *piOldColMask |= trigStackEntry.oldColMask; 886 if( piNewColMask ) *piNewColMask |= trigStackEntry.newColMask; 887 return 0; 888 } 889 #endif /* !defined(SQLITE_OMIT_TRIGGER) */ 890