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 #include "sqliteInt.h" 16 17 /* 18 ** While a SrcList can in general represent multiple tables and subqueries 19 ** (as in the FROM clause of a SELECT statement) in this case it contains 20 ** the name of a single table, as one might find in an INSERT, DELETE, 21 ** or UPDATE statement. Look up that table in the symbol table and 22 ** return a pointer. Set an error message and return NULL if the table 23 ** name is not found or if any other error occurs. 24 ** 25 ** The following fields are initialized appropriate in pSrc: 26 ** 27 ** pSrc->a[0].pTab Pointer to the Table object 28 ** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one 29 ** 30 */ 31 Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){ 32 struct SrcList_item *pItem = pSrc->a; 33 Table *pTab; 34 assert( pItem && pSrc->nSrc==1 ); 35 pTab = sqlite3LocateTableItem(pParse, 0, pItem); 36 sqlite3DeleteTable(pParse->db, pItem->pTab); 37 pItem->pTab = pTab; 38 if( pTab ){ 39 pTab->nTabRef++; 40 } 41 if( sqlite3IndexedByLookup(pParse, pItem) ){ 42 pTab = 0; 43 } 44 return pTab; 45 } 46 47 /* 48 ** Check to make sure the given table is writable. If it is not 49 ** writable, generate an error message and return 1. If it is 50 ** writable return 0; 51 */ 52 int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){ 53 /* A table is not writable under the following circumstances: 54 ** 55 ** 1) It is a virtual table and no implementation of the xUpdate method 56 ** has been provided, or 57 ** 2) It is a system table (i.e. sqlite_master), this call is not 58 ** part of a nested parse and writable_schema pragma has not 59 ** been specified. 60 ** 61 ** In either case leave an error message in pParse and return non-zero. 62 */ 63 if( ( IsVirtual(pTab) 64 && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 ) 65 || ( (pTab->tabFlags & TF_Readonly)!=0 66 && (pParse->db->flags & SQLITE_WriteSchema)==0 67 && pParse->nested==0 ) 68 ){ 69 sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName); 70 return 1; 71 } 72 73 #ifndef SQLITE_OMIT_VIEW 74 if( !viewOk && pTab->pSelect ){ 75 sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName); 76 return 1; 77 } 78 #endif 79 return 0; 80 } 81 82 83 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) 84 /* 85 ** Evaluate a view and store its result in an ephemeral table. The 86 ** pWhere argument is an optional WHERE clause that restricts the 87 ** set of rows in the view that are to be added to the ephemeral table. 88 */ 89 void sqlite3MaterializeView( 90 Parse *pParse, /* Parsing context */ 91 Table *pView, /* View definition */ 92 Expr *pWhere, /* Optional WHERE clause to be added */ 93 ExprList *pOrderBy, /* Optional ORDER BY clause */ 94 Expr *pLimit, /* Optional LIMIT clause */ 95 int iCur /* Cursor number for ephemeral table */ 96 ){ 97 SelectDest dest; 98 Select *pSel; 99 SrcList *pFrom; 100 sqlite3 *db = pParse->db; 101 int iDb = sqlite3SchemaToIndex(db, pView->pSchema); 102 pWhere = sqlite3ExprDup(db, pWhere, 0); 103 pFrom = sqlite3SrcListAppend(db, 0, 0, 0); 104 if( pFrom ){ 105 assert( pFrom->nSrc==1 ); 106 pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName); 107 pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zDbSName); 108 assert( pFrom->a[0].pOn==0 ); 109 assert( pFrom->a[0].pUsing==0 ); 110 } 111 pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, pOrderBy, 112 SF_IncludeHidden, pLimit); 113 sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur); 114 sqlite3Select(pParse, pSel, &dest); 115 sqlite3SelectDelete(db, pSel); 116 } 117 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */ 118 119 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) 120 /* 121 ** Generate an expression tree to implement the WHERE, ORDER BY, 122 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements. 123 ** 124 ** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1; 125 ** \__________________________/ 126 ** pLimitWhere (pInClause) 127 */ 128 Expr *sqlite3LimitWhere( 129 Parse *pParse, /* The parser context */ 130 SrcList *pSrc, /* the FROM clause -- which tables to scan */ 131 Expr *pWhere, /* The WHERE clause. May be null */ 132 ExprList *pOrderBy, /* The ORDER BY clause. May be null */ 133 Expr *pLimit, /* The LIMIT clause. May be null */ 134 char *zStmtType /* Either DELETE or UPDATE. For err msgs. */ 135 ){ 136 sqlite3 *db = pParse->db; 137 Expr *pLhs = NULL; /* LHS of IN(SELECT...) operator */ 138 Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */ 139 ExprList *pEList = NULL; /* Expression list contaning only pSelectRowid */ 140 SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */ 141 Select *pSelect = NULL; /* Complete SELECT tree */ 142 Table *pTab; 143 144 /* Check that there isn't an ORDER BY without a LIMIT clause. 145 */ 146 if( pOrderBy && pLimit==0 ) { 147 sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType); 148 sqlite3ExprDelete(pParse->db, pWhere); 149 sqlite3ExprListDelete(pParse->db, pOrderBy); 150 return 0; 151 } 152 153 /* We only need to generate a select expression if there 154 ** is a limit/offset term to enforce. 155 */ 156 if( pLimit == 0 ) { 157 return pWhere; 158 } 159 160 /* Generate a select expression tree to enforce the limit/offset 161 ** term for the DELETE or UPDATE statement. For example: 162 ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1 163 ** becomes: 164 ** DELETE FROM table_a WHERE rowid IN ( 165 ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1 166 ** ); 167 */ 168 169 pTab = pSrc->a[0].pTab; 170 if( HasRowid(pTab) ){ 171 pLhs = sqlite3PExpr(pParse, TK_ROW, 0, 0); 172 pEList = sqlite3ExprListAppend( 173 pParse, 0, sqlite3PExpr(pParse, TK_ROW, 0, 0) 174 ); 175 }else{ 176 Index *pPk = sqlite3PrimaryKeyIndex(pTab); 177 if( pPk->nKeyCol==1 ){ 178 const char *zName = pTab->aCol[pPk->aiColumn[0]].zName; 179 pLhs = sqlite3Expr(db, TK_ID, zName); 180 pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, zName)); 181 }else{ 182 int i; 183 for(i=0; i<pPk->nKeyCol; i++){ 184 Expr *p = sqlite3Expr(db, TK_ID, pTab->aCol[pPk->aiColumn[i]].zName); 185 pEList = sqlite3ExprListAppend(pParse, pEList, p); 186 } 187 pLhs = sqlite3PExpr(pParse, TK_VECTOR, 0, 0); 188 if( pLhs ){ 189 pLhs->x.pList = sqlite3ExprListDup(db, pEList, 0); 190 } 191 } 192 } 193 194 /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree 195 ** and the SELECT subtree. */ 196 pSrc->a[0].pTab = 0; 197 pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0); 198 pSrc->a[0].pTab = pTab; 199 pSrc->a[0].pIBIndex = 0; 200 201 /* generate the SELECT expression tree. */ 202 pSelect = sqlite3SelectNew(pParse, pEList, pSelectSrc, pWhere, 0 ,0, 203 pOrderBy,0,pLimit 204 ); 205 206 /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */ 207 pInClause = sqlite3PExpr(pParse, TK_IN, pLhs, 0); 208 sqlite3PExprAddSelect(pParse, pInClause, pSelect); 209 return pInClause; 210 } 211 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */ 212 /* && !defined(SQLITE_OMIT_SUBQUERY) */ 213 214 /* 215 ** Generate code for a DELETE FROM statement. 216 ** 217 ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL; 218 ** \________/ \________________/ 219 ** pTabList pWhere 220 */ 221 void sqlite3DeleteFrom( 222 Parse *pParse, /* The parser context */ 223 SrcList *pTabList, /* The table from which we should delete things */ 224 Expr *pWhere, /* The WHERE clause. May be null */ 225 ExprList *pOrderBy, /* ORDER BY clause. May be null */ 226 Expr *pLimit /* LIMIT clause. May be null */ 227 ){ 228 Vdbe *v; /* The virtual database engine */ 229 Table *pTab; /* The table from which records will be deleted */ 230 int i; /* Loop counter */ 231 WhereInfo *pWInfo; /* Information about the WHERE clause */ 232 Index *pIdx; /* For looping over indices of the table */ 233 int iTabCur; /* Cursor number for the table */ 234 int iDataCur = 0; /* VDBE cursor for the canonical data source */ 235 int iIdxCur = 0; /* Cursor number of the first index */ 236 int nIdx; /* Number of indices */ 237 sqlite3 *db; /* Main database structure */ 238 AuthContext sContext; /* Authorization context */ 239 NameContext sNC; /* Name context to resolve expressions in */ 240 int iDb; /* Database number */ 241 int memCnt = -1; /* Memory cell used for change counting */ 242 int rcauth; /* Value returned by authorization callback */ 243 int eOnePass; /* ONEPASS_OFF or _SINGLE or _MULTI */ 244 int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */ 245 u8 *aToOpen = 0; /* Open cursor iTabCur+j if aToOpen[j] is true */ 246 Index *pPk; /* The PRIMARY KEY index on the table */ 247 int iPk = 0; /* First of nPk registers holding PRIMARY KEY value */ 248 i16 nPk = 1; /* Number of columns in the PRIMARY KEY */ 249 int iKey; /* Memory cell holding key of row to be deleted */ 250 i16 nKey; /* Number of memory cells in the row key */ 251 int iEphCur = 0; /* Ephemeral table holding all primary key values */ 252 int iRowSet = 0; /* Register for rowset of rows to delete */ 253 int addrBypass = 0; /* Address of jump over the delete logic */ 254 int addrLoop = 0; /* Top of the delete loop */ 255 int addrEphOpen = 0; /* Instruction to open the Ephemeral table */ 256 int bComplex; /* True if there are triggers or FKs or 257 ** subqueries in the WHERE clause */ 258 259 #ifndef SQLITE_OMIT_TRIGGER 260 int isView; /* True if attempting to delete from a view */ 261 Trigger *pTrigger; /* List of table triggers, if required */ 262 #endif 263 264 memset(&sContext, 0, sizeof(sContext)); 265 db = pParse->db; 266 if( pParse->nErr || db->mallocFailed ){ 267 goto delete_from_cleanup; 268 } 269 assert( pTabList->nSrc==1 ); 270 271 272 /* Locate the table which we want to delete. This table has to be 273 ** put in an SrcList structure because some of the subroutines we 274 ** will be calling are designed to work with multiple tables and expect 275 ** an SrcList* parameter instead of just a Table* parameter. 276 */ 277 pTab = sqlite3SrcListLookup(pParse, pTabList); 278 if( pTab==0 ) goto delete_from_cleanup; 279 280 /* Figure out if we have any triggers and if the table being 281 ** deleted from is a view 282 */ 283 #ifndef SQLITE_OMIT_TRIGGER 284 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0); 285 isView = pTab->pSelect!=0; 286 bComplex = pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0); 287 #else 288 # define pTrigger 0 289 # define isView 0 290 #endif 291 #ifdef SQLITE_OMIT_VIEW 292 # undef isView 293 # define isView 0 294 #endif 295 296 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT 297 if( !isView ){ 298 pWhere = sqlite3LimitWhere( 299 pParse, pTabList, pWhere, pOrderBy, pLimit, "DELETE" 300 ); 301 pOrderBy = 0; 302 pLimit = 0; 303 } 304 #endif 305 306 /* If pTab is really a view, make sure it has been initialized. 307 */ 308 if( sqlite3ViewGetColumnNames(pParse, pTab) ){ 309 goto delete_from_cleanup; 310 } 311 312 if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){ 313 goto delete_from_cleanup; 314 } 315 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 316 assert( iDb<db->nDb ); 317 rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, 318 db->aDb[iDb].zDbSName); 319 assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE ); 320 if( rcauth==SQLITE_DENY ){ 321 goto delete_from_cleanup; 322 } 323 assert(!isView || pTrigger); 324 325 /* Assign cursor numbers to the table and all its indices. 326 */ 327 assert( pTabList->nSrc==1 ); 328 iTabCur = pTabList->a[0].iCursor = pParse->nTab++; 329 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ 330 pParse->nTab++; 331 } 332 333 /* Start the view context 334 */ 335 if( isView ){ 336 sqlite3AuthContextPush(pParse, &sContext, pTab->zName); 337 } 338 339 /* Begin generating code. 340 */ 341 v = sqlite3GetVdbe(pParse); 342 if( v==0 ){ 343 goto delete_from_cleanup; 344 } 345 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v); 346 sqlite3BeginWriteOperation(pParse, 1, iDb); 347 348 /* If we are trying to delete from a view, realize that view into 349 ** an ephemeral table. 350 */ 351 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) 352 if( isView ){ 353 sqlite3MaterializeView(pParse, pTab, 354 pWhere, pOrderBy, pLimit, iTabCur 355 ); 356 iDataCur = iIdxCur = iTabCur; 357 pOrderBy = 0; 358 pLimit = 0; 359 } 360 #endif 361 362 /* Resolve the column names in the WHERE clause. 363 */ 364 memset(&sNC, 0, sizeof(sNC)); 365 sNC.pParse = pParse; 366 sNC.pSrcList = pTabList; 367 if( sqlite3ResolveExprNames(&sNC, pWhere) ){ 368 goto delete_from_cleanup; 369 } 370 371 /* Initialize the counter of the number of rows deleted, if 372 ** we are counting rows. 373 */ 374 if( db->flags & SQLITE_CountRows ){ 375 memCnt = ++pParse->nMem; 376 sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt); 377 } 378 379 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION 380 /* Special case: A DELETE without a WHERE clause deletes everything. 381 ** It is easier just to erase the whole table. Prior to version 3.6.5, 382 ** this optimization caused the row change count (the value returned by 383 ** API function sqlite3_count_changes) to be set incorrectly. 384 ** 385 ** The "rcauth==SQLITE_OK" terms is the 386 ** IMPLEMENTATION-OF: R-17228-37124 If the action code is SQLITE_DELETE and 387 ** the callback returns SQLITE_IGNORE then the DELETE operation proceeds but 388 ** the truncate optimization is disabled and all rows are deleted 389 ** individually. 390 */ 391 if( rcauth==SQLITE_OK 392 && pWhere==0 393 && !bComplex 394 && !IsVirtual(pTab) 395 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK 396 && db->xPreUpdateCallback==0 397 #endif 398 ){ 399 assert( !isView ); 400 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName); 401 if( HasRowid(pTab) ){ 402 sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt, 403 pTab->zName, P4_STATIC); 404 } 405 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 406 assert( pIdx->pSchema==pTab->pSchema ); 407 sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb); 408 } 409 }else 410 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */ 411 { 412 u16 wcf = WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK|WHERE_SEEK_TABLE; 413 if( sNC.ncFlags & NC_VarSelect ) bComplex = 1; 414 wcf |= (bComplex ? 0 : WHERE_ONEPASS_MULTIROW); 415 if( HasRowid(pTab) ){ 416 /* For a rowid table, initialize the RowSet to an empty set */ 417 pPk = 0; 418 nPk = 1; 419 iRowSet = ++pParse->nMem; 420 sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet); 421 }else{ 422 /* For a WITHOUT ROWID table, create an ephemeral table used to 423 ** hold all primary keys for rows to be deleted. */ 424 pPk = sqlite3PrimaryKeyIndex(pTab); 425 assert( pPk!=0 ); 426 nPk = pPk->nKeyCol; 427 iPk = pParse->nMem+1; 428 pParse->nMem += nPk; 429 iEphCur = pParse->nTab++; 430 addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk); 431 sqlite3VdbeSetP4KeyInfo(pParse, pPk); 432 } 433 434 /* Construct a query to find the rowid or primary key for every row 435 ** to be deleted, based on the WHERE clause. Set variable eOnePass 436 ** to indicate the strategy used to implement this delete: 437 ** 438 ** ONEPASS_OFF: Two-pass approach - use a FIFO for rowids/PK values. 439 ** ONEPASS_SINGLE: One-pass approach - at most one row deleted. 440 ** ONEPASS_MULTI: One-pass approach - any number of rows may be deleted. 441 */ 442 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, wcf, iTabCur+1); 443 if( pWInfo==0 ) goto delete_from_cleanup; 444 eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass); 445 assert( IsVirtual(pTab)==0 || eOnePass!=ONEPASS_MULTI ); 446 assert( IsVirtual(pTab) || bComplex || eOnePass!=ONEPASS_OFF ); 447 448 /* Keep track of the number of rows to be deleted */ 449 if( db->flags & SQLITE_CountRows ){ 450 sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1); 451 } 452 453 /* Extract the rowid or primary key for the current row */ 454 if( pPk ){ 455 for(i=0; i<nPk; i++){ 456 assert( pPk->aiColumn[i]>=0 ); 457 sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, 458 pPk->aiColumn[i], iPk+i); 459 } 460 iKey = iPk; 461 }else{ 462 iKey = pParse->nMem + 1; 463 iKey = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iTabCur, iKey, 0); 464 if( iKey>pParse->nMem ) pParse->nMem = iKey; 465 } 466 467 if( eOnePass!=ONEPASS_OFF ){ 468 /* For ONEPASS, no need to store the rowid/primary-key. There is only 469 ** one, so just keep it in its register(s) and fall through to the 470 ** delete code. */ 471 nKey = nPk; /* OP_Found will use an unpacked key */ 472 aToOpen = sqlite3DbMallocRawNN(db, nIdx+2); 473 if( aToOpen==0 ){ 474 sqlite3WhereEnd(pWInfo); 475 goto delete_from_cleanup; 476 } 477 memset(aToOpen, 1, nIdx+1); 478 aToOpen[nIdx+1] = 0; 479 if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0; 480 if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0; 481 if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen); 482 }else{ 483 if( pPk ){ 484 /* Add the PK key for this row to the temporary table */ 485 iKey = ++pParse->nMem; 486 nKey = 0; /* Zero tells OP_Found to use a composite key */ 487 sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey, 488 sqlite3IndexAffinityStr(pParse->db, pPk), nPk); 489 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEphCur, iKey, iPk, nPk); 490 }else{ 491 /* Add the rowid of the row to be deleted to the RowSet */ 492 nKey = 1; /* OP_DeferredSeek always uses a single rowid */ 493 sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey); 494 } 495 } 496 497 /* If this DELETE cannot use the ONEPASS strategy, this is the 498 ** end of the WHERE loop */ 499 if( eOnePass!=ONEPASS_OFF ){ 500 addrBypass = sqlite3VdbeMakeLabel(v); 501 }else{ 502 sqlite3WhereEnd(pWInfo); 503 } 504 505 /* Unless this is a view, open cursors for the table we are 506 ** deleting from and all its indices. If this is a view, then the 507 ** only effect this statement has is to fire the INSTEAD OF 508 ** triggers. 509 */ 510 if( !isView ){ 511 int iAddrOnce = 0; 512 if( eOnePass==ONEPASS_MULTI ){ 513 iAddrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); 514 } 515 testcase( IsVirtual(pTab) ); 516 sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, OPFLAG_FORDELETE, 517 iTabCur, aToOpen, &iDataCur, &iIdxCur); 518 assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur ); 519 assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 ); 520 if( eOnePass==ONEPASS_MULTI ) sqlite3VdbeJumpHere(v, iAddrOnce); 521 } 522 523 /* Set up a loop over the rowids/primary-keys that were found in the 524 ** where-clause loop above. 525 */ 526 if( eOnePass!=ONEPASS_OFF ){ 527 assert( nKey==nPk ); /* OP_Found will use an unpacked key */ 528 if( !IsVirtual(pTab) && aToOpen[iDataCur-iTabCur] ){ 529 assert( pPk!=0 || pTab->pSelect!=0 ); 530 sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey); 531 VdbeCoverage(v); 532 } 533 }else if( pPk ){ 534 addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v); 535 if( IsVirtual(pTab) ){ 536 sqlite3VdbeAddOp3(v, OP_Column, iEphCur, 0, iKey); 537 }else{ 538 sqlite3VdbeAddOp2(v, OP_RowData, iEphCur, iKey); 539 } 540 assert( nKey==0 ); /* OP_Found will use a composite key */ 541 }else{ 542 addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey); 543 VdbeCoverage(v); 544 assert( nKey==1 ); 545 } 546 547 /* Delete the row */ 548 #ifndef SQLITE_OMIT_VIRTUALTABLE 549 if( IsVirtual(pTab) ){ 550 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab); 551 sqlite3VtabMakeWritable(pParse, pTab); 552 sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB); 553 sqlite3VdbeChangeP5(v, OE_Abort); 554 assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE ); 555 sqlite3MayAbort(pParse); 556 if( eOnePass==ONEPASS_SINGLE && sqlite3IsToplevel(pParse) ){ 557 pParse->isMultiWrite = 0; 558 } 559 }else 560 #endif 561 { 562 int count = (pParse->nested==0); /* True to count changes */ 563 sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur, 564 iKey, nKey, count, OE_Default, eOnePass, aiCurOnePass[1]); 565 } 566 567 /* End of the loop over all rowids/primary-keys. */ 568 if( eOnePass!=ONEPASS_OFF ){ 569 sqlite3VdbeResolveLabel(v, addrBypass); 570 sqlite3WhereEnd(pWInfo); 571 }else if( pPk ){ 572 sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v); 573 sqlite3VdbeJumpHere(v, addrLoop); 574 }else{ 575 sqlite3VdbeGoto(v, addrLoop); 576 sqlite3VdbeJumpHere(v, addrLoop); 577 } 578 } /* End non-truncate path */ 579 580 /* Update the sqlite_sequence table by storing the content of the 581 ** maximum rowid counter values recorded while inserting into 582 ** autoincrement tables. 583 */ 584 if( pParse->nested==0 && pParse->pTriggerTab==0 ){ 585 sqlite3AutoincrementEnd(pParse); 586 } 587 588 /* Return the number of rows that were deleted. If this routine is 589 ** generating code because of a call to sqlite3NestedParse(), do not 590 ** invoke the callback function. 591 */ 592 if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){ 593 sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1); 594 sqlite3VdbeSetNumCols(v, 1); 595 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC); 596 } 597 598 delete_from_cleanup: 599 sqlite3AuthContextPop(&sContext); 600 sqlite3SrcListDelete(db, pTabList); 601 sqlite3ExprDelete(db, pWhere); 602 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) 603 sqlite3ExprListDelete(db, pOrderBy); 604 sqlite3ExprDelete(db, pLimit); 605 #endif 606 sqlite3DbFree(db, aToOpen); 607 return; 608 } 609 /* Make sure "isView" and other macros defined above are undefined. Otherwise 610 ** they may interfere with compilation of other functions in this file 611 ** (or in another file, if this file becomes part of the amalgamation). */ 612 #ifdef isView 613 #undef isView 614 #endif 615 #ifdef pTrigger 616 #undef pTrigger 617 #endif 618 619 /* 620 ** This routine generates VDBE code that causes a single row of a 621 ** single table to be deleted. Both the original table entry and 622 ** all indices are removed. 623 ** 624 ** Preconditions: 625 ** 626 ** 1. iDataCur is an open cursor on the btree that is the canonical data 627 ** store for the table. (This will be either the table itself, 628 ** in the case of a rowid table, or the PRIMARY KEY index in the case 629 ** of a WITHOUT ROWID table.) 630 ** 631 ** 2. Read/write cursors for all indices of pTab must be open as 632 ** cursor number iIdxCur+i for the i-th index. 633 ** 634 ** 3. The primary key for the row to be deleted must be stored in a 635 ** sequence of nPk memory cells starting at iPk. If nPk==0 that means 636 ** that a search record formed from OP_MakeRecord is contained in the 637 ** single memory location iPk. 638 ** 639 ** eMode: 640 ** Parameter eMode may be passed either ONEPASS_OFF (0), ONEPASS_SINGLE, or 641 ** ONEPASS_MULTI. If eMode is not ONEPASS_OFF, then the cursor 642 ** iDataCur already points to the row to delete. If eMode is ONEPASS_OFF 643 ** then this function must seek iDataCur to the entry identified by iPk 644 ** and nPk before reading from it. 645 ** 646 ** If eMode is ONEPASS_MULTI, then this call is being made as part 647 ** of a ONEPASS delete that affects multiple rows. In this case, if 648 ** iIdxNoSeek is a valid cursor number (>=0) and is not the same as 649 ** iDataCur, then its position should be preserved following the delete 650 ** operation. Or, if iIdxNoSeek is not a valid cursor number, the 651 ** position of iDataCur should be preserved instead. 652 ** 653 ** iIdxNoSeek: 654 ** If iIdxNoSeek is a valid cursor number (>=0) not equal to iDataCur, 655 ** then it identifies an index cursor (from within array of cursors 656 ** starting at iIdxCur) that already points to the index entry to be deleted. 657 ** Except, this optimization is disabled if there are BEFORE triggers since 658 ** the trigger body might have moved the cursor. 659 */ 660 void sqlite3GenerateRowDelete( 661 Parse *pParse, /* Parsing context */ 662 Table *pTab, /* Table containing the row to be deleted */ 663 Trigger *pTrigger, /* List of triggers to (potentially) fire */ 664 int iDataCur, /* Cursor from which column data is extracted */ 665 int iIdxCur, /* First index cursor */ 666 int iPk, /* First memory cell containing the PRIMARY KEY */ 667 i16 nPk, /* Number of PRIMARY KEY memory cells */ 668 u8 count, /* If non-zero, increment the row change counter */ 669 u8 onconf, /* Default ON CONFLICT policy for triggers */ 670 u8 eMode, /* ONEPASS_OFF, _SINGLE, or _MULTI. See above */ 671 int iIdxNoSeek /* Cursor number of cursor that does not need seeking */ 672 ){ 673 Vdbe *v = pParse->pVdbe; /* Vdbe */ 674 int iOld = 0; /* First register in OLD.* array */ 675 int iLabel; /* Label resolved to end of generated code */ 676 u8 opSeek; /* Seek opcode */ 677 678 /* Vdbe is guaranteed to have been allocated by this stage. */ 679 assert( v ); 680 VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)", 681 iDataCur, iIdxCur, iPk, (int)nPk)); 682 683 /* Seek cursor iCur to the row to delete. If this row no longer exists 684 ** (this can happen if a trigger program has already deleted it), do 685 ** not attempt to delete it or fire any DELETE triggers. */ 686 iLabel = sqlite3VdbeMakeLabel(v); 687 opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound; 688 if( eMode==ONEPASS_OFF ){ 689 sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk); 690 VdbeCoverageIf(v, opSeek==OP_NotExists); 691 VdbeCoverageIf(v, opSeek==OP_NotFound); 692 } 693 694 /* If there are any triggers to fire, allocate a range of registers to 695 ** use for the old.* references in the triggers. */ 696 if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){ 697 u32 mask; /* Mask of OLD.* columns in use */ 698 int iCol; /* Iterator used while populating OLD.* */ 699 int addrStart; /* Start of BEFORE trigger programs */ 700 701 /* TODO: Could use temporary registers here. Also could attempt to 702 ** avoid copying the contents of the rowid register. */ 703 mask = sqlite3TriggerColmask( 704 pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf 705 ); 706 mask |= sqlite3FkOldmask(pParse, pTab); 707 iOld = pParse->nMem+1; 708 pParse->nMem += (1 + pTab->nCol); 709 710 /* Populate the OLD.* pseudo-table register array. These values will be 711 ** used by any BEFORE and AFTER triggers that exist. */ 712 sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld); 713 for(iCol=0; iCol<pTab->nCol; iCol++){ 714 testcase( mask!=0xffffffff && iCol==31 ); 715 testcase( mask!=0xffffffff && iCol==32 ); 716 if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){ 717 sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+iCol+1); 718 } 719 } 720 721 /* Invoke BEFORE DELETE trigger programs. */ 722 addrStart = sqlite3VdbeCurrentAddr(v); 723 sqlite3CodeRowTrigger(pParse, pTrigger, 724 TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel 725 ); 726 727 /* If any BEFORE triggers were coded, then seek the cursor to the 728 ** row to be deleted again. It may be that the BEFORE triggers moved 729 ** the cursor or already deleted the row that the cursor was 730 ** pointing to. 731 ** 732 ** Also disable the iIdxNoSeek optimization since the BEFORE trigger 733 ** may have moved that cursor. 734 */ 735 if( addrStart<sqlite3VdbeCurrentAddr(v) ){ 736 sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk); 737 VdbeCoverageIf(v, opSeek==OP_NotExists); 738 VdbeCoverageIf(v, opSeek==OP_NotFound); 739 testcase( iIdxNoSeek>=0 ); 740 iIdxNoSeek = -1; 741 } 742 743 /* Do FK processing. This call checks that any FK constraints that 744 ** refer to this table (i.e. constraints attached to other tables) 745 ** are not violated by deleting this row. */ 746 sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0); 747 } 748 749 /* Delete the index and table entries. Skip this step if pTab is really 750 ** a view (in which case the only effect of the DELETE statement is to 751 ** fire the INSTEAD OF triggers). 752 ** 753 ** If variable 'count' is non-zero, then this OP_Delete instruction should 754 ** invoke the update-hook. The pre-update-hook, on the other hand should 755 ** be invoked unless table pTab is a system table. The difference is that 756 ** the update-hook is not invoked for rows removed by REPLACE, but the 757 ** pre-update-hook is. 758 */ 759 if( pTab->pSelect==0 ){ 760 u8 p5 = 0; 761 sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,iIdxNoSeek); 762 sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0)); 763 if( pParse->nested==0 ){ 764 sqlite3VdbeAppendP4(v, (char*)pTab, P4_TABLE); 765 } 766 if( eMode!=ONEPASS_OFF ){ 767 sqlite3VdbeChangeP5(v, OPFLAG_AUXDELETE); 768 } 769 if( iIdxNoSeek>=0 && iIdxNoSeek!=iDataCur ){ 770 sqlite3VdbeAddOp1(v, OP_Delete, iIdxNoSeek); 771 } 772 if( eMode==ONEPASS_MULTI ) p5 |= OPFLAG_SAVEPOSITION; 773 sqlite3VdbeChangeP5(v, p5); 774 } 775 776 /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to 777 ** handle rows (possibly in other tables) that refer via a foreign key 778 ** to the row just deleted. */ 779 sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0); 780 781 /* Invoke AFTER DELETE trigger programs. */ 782 sqlite3CodeRowTrigger(pParse, pTrigger, 783 TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel 784 ); 785 786 /* Jump here if the row had already been deleted before any BEFORE 787 ** trigger programs were invoked. Or if a trigger program throws a 788 ** RAISE(IGNORE) exception. */ 789 sqlite3VdbeResolveLabel(v, iLabel); 790 VdbeModuleComment((v, "END: GenRowDel()")); 791 } 792 793 /* 794 ** This routine generates VDBE code that causes the deletion of all 795 ** index entries associated with a single row of a single table, pTab 796 ** 797 ** Preconditions: 798 ** 799 ** 1. A read/write cursor "iDataCur" must be open on the canonical storage 800 ** btree for the table pTab. (This will be either the table itself 801 ** for rowid tables or to the primary key index for WITHOUT ROWID 802 ** tables.) 803 ** 804 ** 2. Read/write cursors for all indices of pTab must be open as 805 ** cursor number iIdxCur+i for the i-th index. (The pTab->pIndex 806 ** index is the 0-th index.) 807 ** 808 ** 3. The "iDataCur" cursor must be already be positioned on the row 809 ** that is to be deleted. 810 */ 811 void sqlite3GenerateRowIndexDelete( 812 Parse *pParse, /* Parsing and code generating context */ 813 Table *pTab, /* Table containing the row to be deleted */ 814 int iDataCur, /* Cursor of table holding data. */ 815 int iIdxCur, /* First index cursor */ 816 int *aRegIdx, /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */ 817 int iIdxNoSeek /* Do not delete from this cursor */ 818 ){ 819 int i; /* Index loop counter */ 820 int r1 = -1; /* Register holding an index key */ 821 int iPartIdxLabel; /* Jump destination for skipping partial index entries */ 822 Index *pIdx; /* Current index */ 823 Index *pPrior = 0; /* Prior index */ 824 Vdbe *v; /* The prepared statement under construction */ 825 Index *pPk; /* PRIMARY KEY index, or NULL for rowid tables */ 826 827 v = pParse->pVdbe; 828 pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab); 829 for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){ 830 assert( iIdxCur+i!=iDataCur || pPk==pIdx ); 831 if( aRegIdx!=0 && aRegIdx[i]==0 ) continue; 832 if( pIdx==pPk ) continue; 833 if( iIdxCur+i==iIdxNoSeek ) continue; 834 VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName)); 835 r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1, 836 &iPartIdxLabel, pPrior, r1); 837 sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1, 838 pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn); 839 sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel); 840 pPrior = pIdx; 841 } 842 } 843 844 /* 845 ** Generate code that will assemble an index key and stores it in register 846 ** regOut. The key with be for index pIdx which is an index on pTab. 847 ** iCur is the index of a cursor open on the pTab table and pointing to 848 ** the entry that needs indexing. If pTab is a WITHOUT ROWID table, then 849 ** iCur must be the cursor of the PRIMARY KEY index. 850 ** 851 ** Return a register number which is the first in a block of 852 ** registers that holds the elements of the index key. The 853 ** block of registers has already been deallocated by the time 854 ** this routine returns. 855 ** 856 ** If *piPartIdxLabel is not NULL, fill it in with a label and jump 857 ** to that label if pIdx is a partial index that should be skipped. 858 ** The label should be resolved using sqlite3ResolvePartIdxLabel(). 859 ** A partial index should be skipped if its WHERE clause evaluates 860 ** to false or null. If pIdx is not a partial index, *piPartIdxLabel 861 ** will be set to zero which is an empty label that is ignored by 862 ** sqlite3ResolvePartIdxLabel(). 863 ** 864 ** The pPrior and regPrior parameters are used to implement a cache to 865 ** avoid unnecessary register loads. If pPrior is not NULL, then it is 866 ** a pointer to a different index for which an index key has just been 867 ** computed into register regPrior. If the current pIdx index is generating 868 ** its key into the same sequence of registers and if pPrior and pIdx share 869 ** a column in common, then the register corresponding to that column already 870 ** holds the correct value and the loading of that register is skipped. 871 ** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK 872 ** on a table with multiple indices, and especially with the ROWID or 873 ** PRIMARY KEY columns of the index. 874 */ 875 int sqlite3GenerateIndexKey( 876 Parse *pParse, /* Parsing context */ 877 Index *pIdx, /* The index for which to generate a key */ 878 int iDataCur, /* Cursor number from which to take column data */ 879 int regOut, /* Put the new key into this register if not 0 */ 880 int prefixOnly, /* Compute only a unique prefix of the key */ 881 int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */ 882 Index *pPrior, /* Previously generated index key */ 883 int regPrior /* Register holding previous generated key */ 884 ){ 885 Vdbe *v = pParse->pVdbe; 886 int j; 887 int regBase; 888 int nCol; 889 890 if( piPartIdxLabel ){ 891 if( pIdx->pPartIdxWhere ){ 892 *piPartIdxLabel = sqlite3VdbeMakeLabel(v); 893 pParse->iSelfTab = iDataCur + 1; 894 sqlite3ExprCachePush(pParse); 895 sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel, 896 SQLITE_JUMPIFNULL); 897 pParse->iSelfTab = 0; 898 }else{ 899 *piPartIdxLabel = 0; 900 } 901 } 902 nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn; 903 regBase = sqlite3GetTempRange(pParse, nCol); 904 if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0; 905 for(j=0; j<nCol; j++){ 906 if( pPrior 907 && pPrior->aiColumn[j]==pIdx->aiColumn[j] 908 && pPrior->aiColumn[j]!=XN_EXPR 909 ){ 910 /* This column was already computed by the previous index */ 911 continue; 912 } 913 sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iDataCur, j, regBase+j); 914 /* If the column affinity is REAL but the number is an integer, then it 915 ** might be stored in the table as an integer (using a compact 916 ** representation) then converted to REAL by an OP_RealAffinity opcode. 917 ** But we are getting ready to store this value back into an index, where 918 ** it should be converted by to INTEGER again. So omit the OP_RealAffinity 919 ** opcode if it is present */ 920 sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity); 921 } 922 if( regOut ){ 923 sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut); 924 if( pIdx->pTable->pSelect ){ 925 const char *zAff = sqlite3IndexAffinityStr(pParse->db, pIdx); 926 sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT); 927 } 928 } 929 sqlite3ReleaseTempRange(pParse, regBase, nCol); 930 return regBase; 931 } 932 933 /* 934 ** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label 935 ** because it was a partial index, then this routine should be called to 936 ** resolve that label. 937 */ 938 void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){ 939 if( iLabel ){ 940 sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel); 941 sqlite3ExprCachePop(pParse); 942 } 943 } 944