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