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