1 /* 2 ** 2001 September 15 3 ** 4 ** The author disclaims copyright to this source code. In place of 5 ** a legal notice, here is a blessing: 6 ** 7 ** May you do good and not evil. 8 ** May you find forgiveness for yourself and forgive others. 9 ** May you share freely, never taking more than you give. 10 ** 11 ************************************************************************* 12 ** This file contains C code routines that are called by the parser 13 ** in order to generate code for DELETE FROM statements. 14 ** 15 ** $Id: delete.c,v 1.175 2008/09/01 21:59:43 shane Exp $ 16 */ 17 #include "sqliteInt.h" 18 19 /* 20 ** Look up every table that is named in pSrc. If any table is not found, 21 ** add an error message to pParse->zErrMsg and return NULL. If all tables 22 ** are found, return a pointer to the last table. 23 */ 24 Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){ 25 Table *pTab = 0; 26 int i; 27 struct SrcList_item *pItem; 28 for(i=0, pItem=pSrc->a; i<pSrc->nSrc; i++, pItem++){ 29 pTab = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase); 30 sqlite3DeleteTable(pItem->pTab); 31 pItem->pTab = pTab; 32 if( pTab ){ 33 pTab->nRef++; 34 } 35 } 36 return pTab; 37 } 38 39 /* 40 ** Check to make sure the given table is writable. If it is not 41 ** writable, generate an error message and return 1. If it is 42 ** writable return 0; 43 */ 44 int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){ 45 if( ((pTab->tabFlags & TF_Readonly)!=0 46 && (pParse->db->flags & SQLITE_WriteSchema)==0 47 && pParse->nested==0) 48 #ifndef SQLITE_OMIT_VIRTUALTABLE 49 || (pTab->pMod && pTab->pMod->pModule->xUpdate==0) 50 #endif 51 ){ 52 sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName); 53 return 1; 54 } 55 #ifndef SQLITE_OMIT_VIEW 56 if( !viewOk && pTab->pSelect ){ 57 sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName); 58 return 1; 59 } 60 #endif 61 return 0; 62 } 63 64 /* 65 ** Generate code that will open a table for reading. 66 */ 67 void sqlite3OpenTable( 68 Parse *p, /* Generate code into this VDBE */ 69 int iCur, /* The cursor number of the table */ 70 int iDb, /* The database index in sqlite3.aDb[] */ 71 Table *pTab, /* The table to be opened */ 72 int opcode /* OP_OpenRead or OP_OpenWrite */ 73 ){ 74 Vdbe *v; 75 if( IsVirtual(pTab) ) return; 76 v = sqlite3GetVdbe(p); 77 assert( opcode==OP_OpenWrite || opcode==OP_OpenRead ); 78 sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite), pTab->zName); 79 sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol); 80 sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb); 81 VdbeComment((v, "%s", pTab->zName)); 82 } 83 84 85 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) 86 /* 87 ** Evaluate a view and store its result in an ephemeral table. The 88 ** pWhere argument is an optional WHERE clause that restricts the 89 ** set of rows in the view that are to be added to the ephemeral table. 90 */ 91 void sqlite3MaterializeView( 92 Parse *pParse, /* Parsing context */ 93 Table *pView, /* View definition */ 94 Expr *pWhere, /* Optional WHERE clause to be added */ 95 int iCur /* Cursor number for ephemerial table */ 96 ){ 97 SelectDest dest; 98 Select *pDup; 99 sqlite3 *db = pParse->db; 100 101 pDup = sqlite3SelectDup(db, pView->pSelect); 102 if( pWhere ){ 103 SrcList *pFrom; 104 Token viewName; 105 106 pWhere = sqlite3ExprDup(db, pWhere); 107 viewName.z = (u8*)pView->zName; 108 viewName.n = (unsigned int)strlen((const char*)viewName.z); 109 pFrom = sqlite3SrcListAppendFromTerm(pParse, 0, 0, 0, &viewName, pDup, 0,0); 110 pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0); 111 } 112 sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur); 113 sqlite3Select(pParse, pDup, &dest); 114 sqlite3SelectDelete(db, pDup); 115 } 116 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */ 117 118 119 /* 120 ** Generate code for a DELETE FROM statement. 121 ** 122 ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL; 123 ** \________/ \________________/ 124 ** pTabList pWhere 125 */ 126 void sqlite3DeleteFrom( 127 Parse *pParse, /* The parser context */ 128 SrcList *pTabList, /* The table from which we should delete things */ 129 Expr *pWhere /* The WHERE clause. May be null */ 130 ){ 131 Vdbe *v; /* The virtual database engine */ 132 Table *pTab; /* The table from which records will be deleted */ 133 const char *zDb; /* Name of database holding pTab */ 134 int end, addr = 0; /* A couple addresses of generated code */ 135 int i; /* Loop counter */ 136 WhereInfo *pWInfo; /* Information about the WHERE clause */ 137 Index *pIdx; /* For looping over indices of the table */ 138 int iCur; /* VDBE Cursor number for pTab */ 139 sqlite3 *db; /* Main database structure */ 140 AuthContext sContext; /* Authorization context */ 141 int oldIdx = -1; /* Cursor for the OLD table of AFTER triggers */ 142 NameContext sNC; /* Name context to resolve expressions in */ 143 int iDb; /* Database number */ 144 int memCnt = 0; /* Memory cell used for change counting */ 145 146 #ifndef SQLITE_OMIT_TRIGGER 147 int isView; /* True if attempting to delete from a view */ 148 int triggers_exist = 0; /* True if any triggers exist */ 149 #endif 150 int iBeginAfterTrigger; /* Address of after trigger program */ 151 int iEndAfterTrigger; /* Exit of after trigger program */ 152 int iBeginBeforeTrigger; /* Address of before trigger program */ 153 int iEndBeforeTrigger; /* Exit of before trigger program */ 154 u32 old_col_mask = 0; /* Mask of OLD.* columns in use */ 155 156 sContext.pParse = 0; 157 db = pParse->db; 158 if( pParse->nErr || db->mallocFailed ){ 159 goto delete_from_cleanup; 160 } 161 assert( pTabList->nSrc==1 ); 162 163 /* Locate the table which we want to delete. This table has to be 164 ** put in an SrcList structure because some of the subroutines we 165 ** will be calling are designed to work with multiple tables and expect 166 ** an SrcList* parameter instead of just a Table* parameter. 167 */ 168 pTab = sqlite3SrcListLookup(pParse, pTabList); 169 if( pTab==0 ) goto delete_from_cleanup; 170 171 /* Figure out if we have any triggers and if the table being 172 ** deleted from is a view 173 */ 174 #ifndef SQLITE_OMIT_TRIGGER 175 triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0); 176 isView = pTab->pSelect!=0; 177 #else 178 # define triggers_exist 0 179 # define isView 0 180 #endif 181 #ifdef SQLITE_OMIT_VIEW 182 # undef isView 183 # define isView 0 184 #endif 185 186 if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){ 187 goto delete_from_cleanup; 188 } 189 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 190 assert( iDb<db->nDb ); 191 zDb = db->aDb[iDb].zName; 192 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){ 193 goto delete_from_cleanup; 194 } 195 196 /* If pTab is really a view, make sure it has been initialized. 197 */ 198 if( sqlite3ViewGetColumnNames(pParse, pTab) ){ 199 goto delete_from_cleanup; 200 } 201 202 /* Allocate a cursor used to store the old.* data for a trigger. 203 */ 204 if( triggers_exist ){ 205 oldIdx = pParse->nTab++; 206 } 207 208 /* Assign cursor number to the table and all its indices. 209 */ 210 assert( pTabList->nSrc==1 ); 211 iCur = pTabList->a[0].iCursor = pParse->nTab++; 212 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 213 pParse->nTab++; 214 } 215 216 /* Start the view context 217 */ 218 if( isView ){ 219 sqlite3AuthContextPush(pParse, &sContext, pTab->zName); 220 } 221 222 /* Begin generating code. 223 */ 224 v = sqlite3GetVdbe(pParse); 225 if( v==0 ){ 226 goto delete_from_cleanup; 227 } 228 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v); 229 sqlite3BeginWriteOperation(pParse, triggers_exist, iDb); 230 231 if( triggers_exist ){ 232 int orconf = ((pParse->trigStack)?pParse->trigStack->orconf:OE_Default); 233 int iGoto = sqlite3VdbeAddOp0(v, OP_Goto); 234 addr = sqlite3VdbeMakeLabel(v); 235 236 iBeginBeforeTrigger = sqlite3VdbeCurrentAddr(v); 237 (void)sqlite3CodeRowTrigger(pParse, TK_DELETE, 0, TRIGGER_BEFORE, pTab, 238 -1, oldIdx, orconf, addr, &old_col_mask, 0); 239 iEndBeforeTrigger = sqlite3VdbeAddOp0(v, OP_Goto); 240 241 iBeginAfterTrigger = sqlite3VdbeCurrentAddr(v); 242 (void)sqlite3CodeRowTrigger(pParse, TK_DELETE, 0, TRIGGER_AFTER, pTab, -1, 243 oldIdx, orconf, addr, &old_col_mask, 0); 244 iEndAfterTrigger = sqlite3VdbeAddOp0(v, OP_Goto); 245 246 sqlite3VdbeJumpHere(v, iGoto); 247 } 248 249 /* If we are trying to delete from a view, realize that view into 250 ** a ephemeral table. 251 */ 252 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) 253 if( isView ){ 254 sqlite3MaterializeView(pParse, pTab, pWhere, iCur); 255 } 256 #endif 257 258 /* Resolve the column names in the WHERE clause. 259 */ 260 memset(&sNC, 0, sizeof(sNC)); 261 sNC.pParse = pParse; 262 sNC.pSrcList = pTabList; 263 if( sqlite3ResolveExprNames(&sNC, pWhere) ){ 264 goto delete_from_cleanup; 265 } 266 267 /* Initialize the counter of the number of rows deleted, if 268 ** we are counting rows. 269 */ 270 if( db->flags & SQLITE_CountRows ){ 271 memCnt = ++pParse->nMem; 272 sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt); 273 } 274 275 /* Special case: A DELETE without a WHERE clause deletes everything. 276 ** It is easier just to erase the whole table. Note, however, that 277 ** this means that the row change count will be incorrect. 278 */ 279 if( pWhere==0 && !triggers_exist && !IsVirtual(pTab) ){ 280 if( db->flags & SQLITE_CountRows ){ 281 /* If counting rows deleted, just count the total number of 282 ** entries in the table. */ 283 int addr2; 284 if( !isView ){ 285 sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead); 286 } 287 sqlite3VdbeAddOp2(v, OP_Rewind, iCur, sqlite3VdbeCurrentAddr(v)+2); 288 addr2 = sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1); 289 sqlite3VdbeAddOp2(v, OP_Next, iCur, addr2); 290 sqlite3VdbeAddOp1(v, OP_Close, iCur); 291 } 292 if( !isView ){ 293 sqlite3VdbeAddOp2(v, OP_Clear, pTab->tnum, iDb); 294 if( !pParse->nested ){ 295 sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC); 296 } 297 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 298 assert( pIdx->pSchema==pTab->pSchema ); 299 sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb); 300 } 301 } 302 } 303 /* The usual case: There is a WHERE clause so we have to scan through 304 ** the table and pick which records to delete. 305 */ 306 else{ 307 int iRowid = ++pParse->nMem; /* Used for storing rowid values. */ 308 309 /* Begin the database scan 310 */ 311 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0); 312 if( pWInfo==0 ) goto delete_from_cleanup; 313 314 /* Remember the rowid of every item to be deleted. 315 */ 316 sqlite3VdbeAddOp2(v, IsVirtual(pTab) ? OP_VRowid : OP_Rowid, iCur, iRowid); 317 sqlite3VdbeAddOp1(v, OP_FifoWrite, iRowid); 318 if( db->flags & SQLITE_CountRows ){ 319 sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1); 320 } 321 322 /* End the database scan loop. 323 */ 324 sqlite3WhereEnd(pWInfo); 325 326 /* Open the pseudo-table used to store OLD if there are triggers. 327 */ 328 if( triggers_exist ){ 329 sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol); 330 sqlite3VdbeAddOp1(v, OP_OpenPseudo, oldIdx); 331 } 332 333 /* Delete every item whose key was written to the list during the 334 ** database scan. We have to delete items after the scan is complete 335 ** because deleting an item can change the scan order. 336 */ 337 end = sqlite3VdbeMakeLabel(v); 338 339 if( !isView ){ 340 /* Open cursors for the table we are deleting from and 341 ** all its indices. 342 */ 343 sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite); 344 } 345 346 /* This is the beginning of the delete loop. If a trigger encounters 347 ** an IGNORE constraint, it jumps back to here. 348 */ 349 if( triggers_exist ){ 350 sqlite3VdbeResolveLabel(v, addr); 351 } 352 addr = sqlite3VdbeAddOp2(v, OP_FifoRead, iRowid, end); 353 354 if( triggers_exist ){ 355 int iData = ++pParse->nMem; /* For storing row data of OLD table */ 356 357 /* If the record is no longer present in the table, jump to the 358 ** next iteration of the loop through the contents of the fifo. 359 */ 360 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, iRowid); 361 362 /* Populate the OLD.* pseudo-table */ 363 if( old_col_mask ){ 364 sqlite3VdbeAddOp2(v, OP_RowData, iCur, iData); 365 }else{ 366 sqlite3VdbeAddOp2(v, OP_Null, 0, iData); 367 } 368 sqlite3VdbeAddOp3(v, OP_Insert, oldIdx, iData, iRowid); 369 370 /* Jump back and run the BEFORE triggers */ 371 sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginBeforeTrigger); 372 sqlite3VdbeJumpHere(v, iEndBeforeTrigger); 373 } 374 375 if( !isView ){ 376 /* Delete the row */ 377 #ifndef SQLITE_OMIT_VIRTUALTABLE 378 if( IsVirtual(pTab) ){ 379 const char *pVtab = (const char *)pTab->pVtab; 380 sqlite3VtabMakeWritable(pParse, pTab); 381 sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVtab, P4_VTAB); 382 }else 383 #endif 384 { 385 sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, pParse->nested==0); 386 } 387 } 388 389 /* If there are row triggers, close all cursors then invoke 390 ** the AFTER triggers 391 */ 392 if( triggers_exist ){ 393 /* Jump back and run the AFTER triggers */ 394 sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginAfterTrigger); 395 sqlite3VdbeJumpHere(v, iEndAfterTrigger); 396 } 397 398 /* End of the delete loop */ 399 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr); 400 sqlite3VdbeResolveLabel(v, end); 401 402 /* Close the cursors after the loop if there are no row triggers */ 403 if( !isView && !IsVirtual(pTab) ){ 404 for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){ 405 sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum); 406 } 407 sqlite3VdbeAddOp1(v, OP_Close, iCur); 408 } 409 } 410 411 /* 412 ** Return the number of rows that were deleted. If this routine is 413 ** generating code because of a call to sqlite3NestedParse(), do not 414 ** invoke the callback function. 415 */ 416 if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){ 417 sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1); 418 sqlite3VdbeSetNumCols(v, 1); 419 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", P4_STATIC); 420 } 421 422 delete_from_cleanup: 423 sqlite3AuthContextPop(&sContext); 424 sqlite3SrcListDelete(db, pTabList); 425 sqlite3ExprDelete(db, pWhere); 426 return; 427 } 428 429 /* 430 ** This routine generates VDBE code that causes a single row of a 431 ** single table to be deleted. 432 ** 433 ** The VDBE must be in a particular state when this routine is called. 434 ** These are the requirements: 435 ** 436 ** 1. A read/write cursor pointing to pTab, the table containing the row 437 ** to be deleted, must be opened as cursor number "base". 438 ** 439 ** 2. Read/write cursors for all indices of pTab must be open as 440 ** cursor number base+i for the i-th index. 441 ** 442 ** 3. The record number of the row to be deleted must be stored in 443 ** memory cell iRowid. 444 ** 445 ** This routine pops the top of the stack to remove the record number 446 ** and then generates code to remove both the table record and all index 447 ** entries that point to that record. 448 */ 449 void sqlite3GenerateRowDelete( 450 Parse *pParse, /* Parsing context */ 451 Table *pTab, /* Table containing the row to be deleted */ 452 int iCur, /* Cursor number for the table */ 453 int iRowid, /* Memory cell that contains the rowid to delete */ 454 int count /* Increment the row change counter */ 455 ){ 456 int addr; 457 Vdbe *v; 458 459 v = pParse->pVdbe; 460 addr = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowid); 461 sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0); 462 sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0)); 463 if( count ){ 464 sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC); 465 } 466 sqlite3VdbeJumpHere(v, addr); 467 } 468 469 /* 470 ** This routine generates VDBE code that causes the deletion of all 471 ** index entries associated with a single row of a single table. 472 ** 473 ** The VDBE must be in a particular state when this routine is called. 474 ** These are the requirements: 475 ** 476 ** 1. A read/write cursor pointing to pTab, the table containing the row 477 ** to be deleted, must be opened as cursor number "iCur". 478 ** 479 ** 2. Read/write cursors for all indices of pTab must be open as 480 ** cursor number iCur+i for the i-th index. 481 ** 482 ** 3. The "iCur" cursor must be pointing to the row that is to be 483 ** deleted. 484 */ 485 void sqlite3GenerateRowIndexDelete( 486 Parse *pParse, /* Parsing and code generating context */ 487 Table *pTab, /* Table containing the row to be deleted */ 488 int iCur, /* Cursor number for the table */ 489 int *aRegIdx /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */ 490 ){ 491 int i; 492 Index *pIdx; 493 int r1; 494 495 for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){ 496 if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue; 497 r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0); 498 sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1); 499 } 500 } 501 502 /* 503 ** Generate code that will assemble an index key and put it in register 504 ** regOut. The key with be for index pIdx which is an index on pTab. 505 ** iCur is the index of a cursor open on the pTab table and pointing to 506 ** the entry that needs indexing. 507 ** 508 ** Return a register number which is the first in a block of 509 ** registers that holds the elements of the index key. The 510 ** block of registers has already been deallocated by the time 511 ** this routine returns. 512 */ 513 int sqlite3GenerateIndexKey( 514 Parse *pParse, /* Parsing context */ 515 Index *pIdx, /* The index for which to generate a key */ 516 int iCur, /* Cursor number for the pIdx->pTable table */ 517 int regOut, /* Write the new index key to this register */ 518 int doMakeRec /* Run the OP_MakeRecord instruction if true */ 519 ){ 520 Vdbe *v = pParse->pVdbe; 521 int j; 522 Table *pTab = pIdx->pTable; 523 int regBase; 524 int nCol; 525 526 nCol = pIdx->nColumn; 527 regBase = sqlite3GetTempRange(pParse, nCol+1); 528 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol); 529 for(j=0; j<nCol; j++){ 530 int idx = pIdx->aiColumn[j]; 531 if( idx==pTab->iPKey ){ 532 sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j); 533 }else{ 534 sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j); 535 sqlite3ColumnDefault(v, pTab, idx); 536 } 537 } 538 if( doMakeRec ){ 539 sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut); 540 sqlite3IndexAffinityStr(v, pIdx); 541 sqlite3ExprCacheAffinityChange(pParse, regBase, nCol+1); 542 } 543 sqlite3ReleaseTempRange(pParse, regBase, nCol+1); 544 return regBase; 545 } 546 547 /* Make sure "isView" gets undefined in case this file becomes part of 548 ** the amalgamation - so that subsequent files do not see isView as a 549 ** macro. */ 550 #undef isView 551