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 #if TREETRACE_ENABLED 304 if( sqlite3TreeTrace & 0x10000 ){ 305 sqlite3TreeViewDelete(0, pParse->pWith, pTabList, pWhere, 306 pOrderBy, pLimit); 307 } 308 #endif 309 310 /* Locate the table which we want to delete. This table has to be 311 ** put in an SrcList structure because some of the subroutines we 312 ** will be calling are designed to work with multiple tables and expect 313 ** an SrcList* parameter instead of just a Table* parameter. 314 */ 315 pTab = sqlite3SrcListLookup(pParse, pTabList); 316 if( pTab==0 ) goto delete_from_cleanup; 317 318 /* Figure out if we have any triggers and if the table being 319 ** deleted from is a view 320 */ 321 #ifndef SQLITE_OMIT_TRIGGER 322 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0); 323 isView = IsView(pTab); 324 #else 325 # define pTrigger 0 326 # define isView 0 327 #endif 328 bComplex = pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0); 329 #ifdef SQLITE_OMIT_VIEW 330 # undef isView 331 # define isView 0 332 #endif 333 334 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT 335 if( !isView ){ 336 pWhere = sqlite3LimitWhere( 337 pParse, pTabList, pWhere, pOrderBy, pLimit, "DELETE" 338 ); 339 pOrderBy = 0; 340 pLimit = 0; 341 } 342 #endif 343 344 /* If pTab is really a view, make sure it has been initialized. 345 */ 346 if( sqlite3ViewGetColumnNames(pParse, pTab) ){ 347 goto delete_from_cleanup; 348 } 349 350 if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){ 351 goto delete_from_cleanup; 352 } 353 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 354 assert( iDb<db->nDb ); 355 rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, 356 db->aDb[iDb].zDbSName); 357 assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE ); 358 if( rcauth==SQLITE_DENY ){ 359 goto delete_from_cleanup; 360 } 361 assert(!isView || pTrigger); 362 363 /* Assign cursor numbers to the table and all its indices. 364 */ 365 assert( pTabList->nSrc==1 ); 366 iTabCur = pTabList->a[0].iCursor = pParse->nTab++; 367 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ 368 pParse->nTab++; 369 } 370 371 /* Start the view context 372 */ 373 if( isView ){ 374 sqlite3AuthContextPush(pParse, &sContext, pTab->zName); 375 } 376 377 /* Begin generating code. 378 */ 379 v = sqlite3GetVdbe(pParse); 380 if( v==0 ){ 381 goto delete_from_cleanup; 382 } 383 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v); 384 sqlite3BeginWriteOperation(pParse, bComplex, iDb); 385 386 /* If we are trying to delete from a view, realize that view into 387 ** an ephemeral table. 388 */ 389 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) 390 if( isView ){ 391 sqlite3MaterializeView(pParse, pTab, 392 pWhere, pOrderBy, pLimit, iTabCur 393 ); 394 iDataCur = iIdxCur = iTabCur; 395 pOrderBy = 0; 396 pLimit = 0; 397 } 398 #endif 399 400 /* Resolve the column names in the WHERE clause. 401 */ 402 memset(&sNC, 0, sizeof(sNC)); 403 sNC.pParse = pParse; 404 sNC.pSrcList = pTabList; 405 if( sqlite3ResolveExprNames(&sNC, pWhere) ){ 406 goto delete_from_cleanup; 407 } 408 409 /* Initialize the counter of the number of rows deleted, if 410 ** we are counting rows. 411 */ 412 if( (db->flags & SQLITE_CountRows)!=0 413 && !pParse->nested 414 && !pParse->pTriggerTab 415 && !pParse->bReturning 416 ){ 417 memCnt = ++pParse->nMem; 418 sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt); 419 } 420 421 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION 422 /* Special case: A DELETE without a WHERE clause deletes everything. 423 ** It is easier just to erase the whole table. Prior to version 3.6.5, 424 ** this optimization caused the row change count (the value returned by 425 ** API function sqlite3_count_changes) to be set incorrectly. 426 ** 427 ** The "rcauth==SQLITE_OK" terms is the 428 ** IMPLEMENTATION-OF: R-17228-37124 If the action code is SQLITE_DELETE and 429 ** the callback returns SQLITE_IGNORE then the DELETE operation proceeds but 430 ** the truncate optimization is disabled and all rows are deleted 431 ** individually. 432 */ 433 if( rcauth==SQLITE_OK 434 && pWhere==0 435 && !bComplex 436 && !IsVirtual(pTab) 437 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK 438 && db->xPreUpdateCallback==0 439 #endif 440 ){ 441 assert( !isView ); 442 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName); 443 if( HasRowid(pTab) ){ 444 sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt ? memCnt : -1, 445 pTab->zName, P4_STATIC); 446 } 447 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 448 assert( pIdx->pSchema==pTab->pSchema ); 449 sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb); 450 if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){ 451 sqlite3VdbeChangeP3(v, -1, memCnt ? memCnt : -1); 452 } 453 } 454 }else 455 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */ 456 { 457 u16 wcf = WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK; 458 if( sNC.ncFlags & NC_VarSelect ) bComplex = 1; 459 wcf |= (bComplex ? 0 : WHERE_ONEPASS_MULTIROW); 460 if( HasRowid(pTab) ){ 461 /* For a rowid table, initialize the RowSet to an empty set */ 462 pPk = 0; 463 nPk = 1; 464 iRowSet = ++pParse->nMem; 465 sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet); 466 }else{ 467 /* For a WITHOUT ROWID table, create an ephemeral table used to 468 ** hold all primary keys for rows to be deleted. */ 469 pPk = sqlite3PrimaryKeyIndex(pTab); 470 assert( pPk!=0 ); 471 nPk = pPk->nKeyCol; 472 iPk = pParse->nMem+1; 473 pParse->nMem += nPk; 474 iEphCur = pParse->nTab++; 475 addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk); 476 sqlite3VdbeSetP4KeyInfo(pParse, pPk); 477 } 478 479 /* Construct a query to find the rowid or primary key for every row 480 ** to be deleted, based on the WHERE clause. Set variable eOnePass 481 ** to indicate the strategy used to implement this delete: 482 ** 483 ** ONEPASS_OFF: Two-pass approach - use a FIFO for rowids/PK values. 484 ** ONEPASS_SINGLE: One-pass approach - at most one row deleted. 485 ** ONEPASS_MULTI: One-pass approach - any number of rows may be deleted. 486 */ 487 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0,0,wcf,iTabCur+1); 488 if( pWInfo==0 ) goto delete_from_cleanup; 489 eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass); 490 assert( IsVirtual(pTab)==0 || eOnePass!=ONEPASS_MULTI ); 491 assert( IsVirtual(pTab) || bComplex || eOnePass!=ONEPASS_OFF ); 492 if( eOnePass!=ONEPASS_SINGLE ) sqlite3MultiWrite(pParse); 493 if( sqlite3WhereUsesDeferredSeek(pWInfo) ){ 494 sqlite3VdbeAddOp1(v, OP_FinishSeek, iTabCur); 495 } 496 497 /* Keep track of the number of rows to be deleted */ 498 if( memCnt ){ 499 sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1); 500 } 501 502 /* Extract the rowid or primary key for the current row */ 503 if( pPk ){ 504 for(i=0; i<nPk; i++){ 505 assert( pPk->aiColumn[i]>=0 ); 506 sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, 507 pPk->aiColumn[i], iPk+i); 508 } 509 iKey = iPk; 510 }else{ 511 iKey = ++pParse->nMem; 512 sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, -1, iKey); 513 } 514 515 if( eOnePass!=ONEPASS_OFF ){ 516 /* For ONEPASS, no need to store the rowid/primary-key. There is only 517 ** one, so just keep it in its register(s) and fall through to the 518 ** delete code. */ 519 nKey = nPk; /* OP_Found will use an unpacked key */ 520 aToOpen = sqlite3DbMallocRawNN(db, nIdx+2); 521 if( aToOpen==0 ){ 522 sqlite3WhereEnd(pWInfo); 523 goto delete_from_cleanup; 524 } 525 memset(aToOpen, 1, nIdx+1); 526 aToOpen[nIdx+1] = 0; 527 if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0; 528 if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0; 529 if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen); 530 addrBypass = sqlite3VdbeMakeLabel(pParse); 531 }else{ 532 if( pPk ){ 533 /* Add the PK key for this row to the temporary table */ 534 iKey = ++pParse->nMem; 535 nKey = 0; /* Zero tells OP_Found to use a composite key */ 536 sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey, 537 sqlite3IndexAffinityStr(pParse->db, pPk), nPk); 538 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEphCur, iKey, iPk, nPk); 539 }else{ 540 /* Add the rowid of the row to be deleted to the RowSet */ 541 nKey = 1; /* OP_DeferredSeek always uses a single rowid */ 542 sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey); 543 } 544 sqlite3WhereEnd(pWInfo); 545 } 546 547 /* Unless this is a view, open cursors for the table we are 548 ** deleting from and all its indices. If this is a view, then the 549 ** only effect this statement has is to fire the INSTEAD OF 550 ** triggers. 551 */ 552 if( !isView ){ 553 int iAddrOnce = 0; 554 if( eOnePass==ONEPASS_MULTI ){ 555 iAddrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); 556 } 557 testcase( IsVirtual(pTab) ); 558 sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, OPFLAG_FORDELETE, 559 iTabCur, aToOpen, &iDataCur, &iIdxCur); 560 assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur ); 561 assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 ); 562 if( eOnePass==ONEPASS_MULTI ){ 563 sqlite3VdbeJumpHereOrPopInst(v, iAddrOnce); 564 } 565 } 566 567 /* Set up a loop over the rowids/primary-keys that were found in the 568 ** where-clause loop above. 569 */ 570 if( eOnePass!=ONEPASS_OFF ){ 571 assert( nKey==nPk ); /* OP_Found will use an unpacked key */ 572 if( !IsVirtual(pTab) && aToOpen[iDataCur-iTabCur] ){ 573 assert( pPk!=0 || IsView(pTab) ); 574 sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey); 575 VdbeCoverage(v); 576 } 577 }else if( pPk ){ 578 addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v); 579 if( IsVirtual(pTab) ){ 580 sqlite3VdbeAddOp3(v, OP_Column, iEphCur, 0, iKey); 581 }else{ 582 sqlite3VdbeAddOp2(v, OP_RowData, iEphCur, iKey); 583 } 584 assert( nKey==0 ); /* OP_Found will use a composite key */ 585 }else{ 586 addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey); 587 VdbeCoverage(v); 588 assert( nKey==1 ); 589 } 590 591 /* Delete the row */ 592 #ifndef SQLITE_OMIT_VIRTUALTABLE 593 if( IsVirtual(pTab) ){ 594 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab); 595 sqlite3VtabMakeWritable(pParse, pTab); 596 assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE ); 597 sqlite3MayAbort(pParse); 598 if( eOnePass==ONEPASS_SINGLE ){ 599 sqlite3VdbeAddOp1(v, OP_Close, iTabCur); 600 if( sqlite3IsToplevel(pParse) ){ 601 pParse->isMultiWrite = 0; 602 } 603 } 604 sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB); 605 sqlite3VdbeChangeP5(v, OE_Abort); 606 }else 607 #endif 608 { 609 int count = (pParse->nested==0); /* True to count changes */ 610 sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur, 611 iKey, nKey, count, OE_Default, eOnePass, aiCurOnePass[1]); 612 } 613 614 /* End of the loop over all rowids/primary-keys. */ 615 if( eOnePass!=ONEPASS_OFF ){ 616 sqlite3VdbeResolveLabel(v, addrBypass); 617 sqlite3WhereEnd(pWInfo); 618 }else if( pPk ){ 619 sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v); 620 sqlite3VdbeJumpHere(v, addrLoop); 621 }else{ 622 sqlite3VdbeGoto(v, addrLoop); 623 sqlite3VdbeJumpHere(v, addrLoop); 624 } 625 } /* End non-truncate path */ 626 627 /* Update the sqlite_sequence table by storing the content of the 628 ** maximum rowid counter values recorded while inserting into 629 ** autoincrement tables. 630 */ 631 if( pParse->nested==0 && pParse->pTriggerTab==0 ){ 632 sqlite3AutoincrementEnd(pParse); 633 } 634 635 /* Return the number of rows that were deleted. If this routine is 636 ** generating code because of a call to sqlite3NestedParse(), do not 637 ** invoke the callback function. 638 */ 639 if( memCnt ){ 640 sqlite3CodeChangeCount(v, memCnt, "rows deleted"); 641 } 642 643 delete_from_cleanup: 644 sqlite3AuthContextPop(&sContext); 645 sqlite3SrcListDelete(db, pTabList); 646 sqlite3ExprDelete(db, pWhere); 647 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) 648 sqlite3ExprListDelete(db, pOrderBy); 649 sqlite3ExprDelete(db, pLimit); 650 #endif 651 sqlite3DbFree(db, aToOpen); 652 return; 653 } 654 /* Make sure "isView" and other macros defined above are undefined. Otherwise 655 ** they may interfere with compilation of other functions in this file 656 ** (or in another file, if this file becomes part of the amalgamation). */ 657 #ifdef isView 658 #undef isView 659 #endif 660 #ifdef pTrigger 661 #undef pTrigger 662 #endif 663 664 /* 665 ** This routine generates VDBE code that causes a single row of a 666 ** single table to be deleted. Both the original table entry and 667 ** all indices are removed. 668 ** 669 ** Preconditions: 670 ** 671 ** 1. iDataCur is an open cursor on the btree that is the canonical data 672 ** store for the table. (This will be either the table itself, 673 ** in the case of a rowid table, or the PRIMARY KEY index in the case 674 ** of a WITHOUT ROWID table.) 675 ** 676 ** 2. Read/write cursors for all indices of pTab must be open as 677 ** cursor number iIdxCur+i for the i-th index. 678 ** 679 ** 3. The primary key for the row to be deleted must be stored in a 680 ** sequence of nPk memory cells starting at iPk. If nPk==0 that means 681 ** that a search record formed from OP_MakeRecord is contained in the 682 ** single memory location iPk. 683 ** 684 ** eMode: 685 ** Parameter eMode may be passed either ONEPASS_OFF (0), ONEPASS_SINGLE, or 686 ** ONEPASS_MULTI. If eMode is not ONEPASS_OFF, then the cursor 687 ** iDataCur already points to the row to delete. If eMode is ONEPASS_OFF 688 ** then this function must seek iDataCur to the entry identified by iPk 689 ** and nPk before reading from it. 690 ** 691 ** If eMode is ONEPASS_MULTI, then this call is being made as part 692 ** of a ONEPASS delete that affects multiple rows. In this case, if 693 ** iIdxNoSeek is a valid cursor number (>=0) and is not the same as 694 ** iDataCur, then its position should be preserved following the delete 695 ** operation. Or, if iIdxNoSeek is not a valid cursor number, the 696 ** position of iDataCur should be preserved instead. 697 ** 698 ** iIdxNoSeek: 699 ** If iIdxNoSeek is a valid cursor number (>=0) not equal to iDataCur, 700 ** then it identifies an index cursor (from within array of cursors 701 ** starting at iIdxCur) that already points to the index entry to be deleted. 702 ** Except, this optimization is disabled if there are BEFORE triggers since 703 ** the trigger body might have moved the cursor. 704 */ 705 void sqlite3GenerateRowDelete( 706 Parse *pParse, /* Parsing context */ 707 Table *pTab, /* Table containing the row to be deleted */ 708 Trigger *pTrigger, /* List of triggers to (potentially) fire */ 709 int iDataCur, /* Cursor from which column data is extracted */ 710 int iIdxCur, /* First index cursor */ 711 int iPk, /* First memory cell containing the PRIMARY KEY */ 712 i16 nPk, /* Number of PRIMARY KEY memory cells */ 713 u8 count, /* If non-zero, increment the row change counter */ 714 u8 onconf, /* Default ON CONFLICT policy for triggers */ 715 u8 eMode, /* ONEPASS_OFF, _SINGLE, or _MULTI. See above */ 716 int iIdxNoSeek /* Cursor number of cursor that does not need seeking */ 717 ){ 718 Vdbe *v = pParse->pVdbe; /* Vdbe */ 719 int iOld = 0; /* First register in OLD.* array */ 720 int iLabel; /* Label resolved to end of generated code */ 721 u8 opSeek; /* Seek opcode */ 722 723 /* Vdbe is guaranteed to have been allocated by this stage. */ 724 assert( v ); 725 VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)", 726 iDataCur, iIdxCur, iPk, (int)nPk)); 727 728 /* Seek cursor iCur to the row to delete. If this row no longer exists 729 ** (this can happen if a trigger program has already deleted it), do 730 ** not attempt to delete it or fire any DELETE triggers. */ 731 iLabel = sqlite3VdbeMakeLabel(pParse); 732 opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound; 733 if( eMode==ONEPASS_OFF ){ 734 sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk); 735 VdbeCoverageIf(v, opSeek==OP_NotExists); 736 VdbeCoverageIf(v, opSeek==OP_NotFound); 737 } 738 739 /* If there are any triggers to fire, allocate a range of registers to 740 ** use for the old.* references in the triggers. */ 741 if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){ 742 u32 mask; /* Mask of OLD.* columns in use */ 743 int iCol; /* Iterator used while populating OLD.* */ 744 int addrStart; /* Start of BEFORE trigger programs */ 745 746 /* TODO: Could use temporary registers here. Also could attempt to 747 ** avoid copying the contents of the rowid register. */ 748 mask = sqlite3TriggerColmask( 749 pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf 750 ); 751 mask |= sqlite3FkOldmask(pParse, pTab); 752 iOld = pParse->nMem+1; 753 pParse->nMem += (1 + pTab->nCol); 754 755 /* Populate the OLD.* pseudo-table register array. These values will be 756 ** used by any BEFORE and AFTER triggers that exist. */ 757 sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld); 758 for(iCol=0; iCol<pTab->nCol; iCol++){ 759 testcase( mask!=0xffffffff && iCol==31 ); 760 testcase( mask!=0xffffffff && iCol==32 ); 761 if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){ 762 int kk = sqlite3TableColumnToStorage(pTab, iCol); 763 sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+kk+1); 764 } 765 } 766 767 /* Invoke BEFORE DELETE trigger programs. */ 768 addrStart = sqlite3VdbeCurrentAddr(v); 769 sqlite3CodeRowTrigger(pParse, pTrigger, 770 TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel 771 ); 772 773 /* If any BEFORE triggers were coded, then seek the cursor to the 774 ** row to be deleted again. It may be that the BEFORE triggers moved 775 ** the cursor or already deleted the row that the cursor was 776 ** pointing to. 777 ** 778 ** Also disable the iIdxNoSeek optimization since the BEFORE trigger 779 ** may have moved that cursor. 780 */ 781 if( addrStart<sqlite3VdbeCurrentAddr(v) ){ 782 sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk); 783 VdbeCoverageIf(v, opSeek==OP_NotExists); 784 VdbeCoverageIf(v, opSeek==OP_NotFound); 785 testcase( iIdxNoSeek>=0 ); 786 iIdxNoSeek = -1; 787 } 788 789 /* Do FK processing. This call checks that any FK constraints that 790 ** refer to this table (i.e. constraints attached to other tables) 791 ** are not violated by deleting this row. */ 792 sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0); 793 } 794 795 /* Delete the index and table entries. Skip this step if pTab is really 796 ** a view (in which case the only effect of the DELETE statement is to 797 ** fire the INSTEAD OF triggers). 798 ** 799 ** If variable 'count' is non-zero, then this OP_Delete instruction should 800 ** invoke the update-hook. The pre-update-hook, on the other hand should 801 ** be invoked unless table pTab is a system table. The difference is that 802 ** the update-hook is not invoked for rows removed by REPLACE, but the 803 ** pre-update-hook is. 804 */ 805 if( !IsView(pTab) ){ 806 u8 p5 = 0; 807 sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,iIdxNoSeek); 808 sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0)); 809 if( pParse->nested==0 || 0==sqlite3_stricmp(pTab->zName, "sqlite_stat1") ){ 810 sqlite3VdbeAppendP4(v, (char*)pTab, P4_TABLE); 811 } 812 if( eMode!=ONEPASS_OFF ){ 813 sqlite3VdbeChangeP5(v, OPFLAG_AUXDELETE); 814 } 815 if( iIdxNoSeek>=0 && iIdxNoSeek!=iDataCur ){ 816 sqlite3VdbeAddOp1(v, OP_Delete, iIdxNoSeek); 817 } 818 if( eMode==ONEPASS_MULTI ) p5 |= OPFLAG_SAVEPOSITION; 819 sqlite3VdbeChangeP5(v, p5); 820 } 821 822 /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to 823 ** handle rows (possibly in other tables) that refer via a foreign key 824 ** to the row just deleted. */ 825 sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0); 826 827 /* Invoke AFTER DELETE trigger programs. */ 828 sqlite3CodeRowTrigger(pParse, pTrigger, 829 TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel 830 ); 831 832 /* Jump here if the row had already been deleted before any BEFORE 833 ** trigger programs were invoked. Or if a trigger program throws a 834 ** RAISE(IGNORE) exception. */ 835 sqlite3VdbeResolveLabel(v, iLabel); 836 VdbeModuleComment((v, "END: GenRowDel()")); 837 } 838 839 /* 840 ** This routine generates VDBE code that causes the deletion of all 841 ** index entries associated with a single row of a single table, pTab 842 ** 843 ** Preconditions: 844 ** 845 ** 1. A read/write cursor "iDataCur" must be open on the canonical storage 846 ** btree for the table pTab. (This will be either the table itself 847 ** for rowid tables or to the primary key index for WITHOUT ROWID 848 ** tables.) 849 ** 850 ** 2. Read/write cursors for all indices of pTab must be open as 851 ** cursor number iIdxCur+i for the i-th index. (The pTab->pIndex 852 ** index is the 0-th index.) 853 ** 854 ** 3. The "iDataCur" cursor must be already be positioned on the row 855 ** that is to be deleted. 856 */ 857 void sqlite3GenerateRowIndexDelete( 858 Parse *pParse, /* Parsing and code generating context */ 859 Table *pTab, /* Table containing the row to be deleted */ 860 int iDataCur, /* Cursor of table holding data. */ 861 int iIdxCur, /* First index cursor */ 862 int *aRegIdx, /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */ 863 int iIdxNoSeek /* Do not delete from this cursor */ 864 ){ 865 int i; /* Index loop counter */ 866 int r1 = -1; /* Register holding an index key */ 867 int iPartIdxLabel; /* Jump destination for skipping partial index entries */ 868 Index *pIdx; /* Current index */ 869 Index *pPrior = 0; /* Prior index */ 870 Vdbe *v; /* The prepared statement under construction */ 871 Index *pPk; /* PRIMARY KEY index, or NULL for rowid tables */ 872 873 v = pParse->pVdbe; 874 pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab); 875 for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){ 876 assert( iIdxCur+i!=iDataCur || pPk==pIdx ); 877 if( aRegIdx!=0 && aRegIdx[i]==0 ) continue; 878 if( pIdx==pPk ) continue; 879 if( iIdxCur+i==iIdxNoSeek ) continue; 880 VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName)); 881 r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1, 882 &iPartIdxLabel, pPrior, r1); 883 sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1, 884 pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn); 885 sqlite3VdbeChangeP5(v, 1); /* Cause IdxDelete to error if no entry found */ 886 sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel); 887 pPrior = pIdx; 888 } 889 } 890 891 /* 892 ** Generate code that will assemble an index key and stores it in register 893 ** regOut. The key with be for index pIdx which is an index on pTab. 894 ** iCur is the index of a cursor open on the pTab table and pointing to 895 ** the entry that needs indexing. If pTab is a WITHOUT ROWID table, then 896 ** iCur must be the cursor of the PRIMARY KEY index. 897 ** 898 ** Return a register number which is the first in a block of 899 ** registers that holds the elements of the index key. The 900 ** block of registers has already been deallocated by the time 901 ** this routine returns. 902 ** 903 ** If *piPartIdxLabel is not NULL, fill it in with a label and jump 904 ** to that label if pIdx is a partial index that should be skipped. 905 ** The label should be resolved using sqlite3ResolvePartIdxLabel(). 906 ** A partial index should be skipped if its WHERE clause evaluates 907 ** to false or null. If pIdx is not a partial index, *piPartIdxLabel 908 ** will be set to zero which is an empty label that is ignored by 909 ** sqlite3ResolvePartIdxLabel(). 910 ** 911 ** The pPrior and regPrior parameters are used to implement a cache to 912 ** avoid unnecessary register loads. If pPrior is not NULL, then it is 913 ** a pointer to a different index for which an index key has just been 914 ** computed into register regPrior. If the current pIdx index is generating 915 ** its key into the same sequence of registers and if pPrior and pIdx share 916 ** a column in common, then the register corresponding to that column already 917 ** holds the correct value and the loading of that register is skipped. 918 ** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK 919 ** on a table with multiple indices, and especially with the ROWID or 920 ** PRIMARY KEY columns of the index. 921 */ 922 int sqlite3GenerateIndexKey( 923 Parse *pParse, /* Parsing context */ 924 Index *pIdx, /* The index for which to generate a key */ 925 int iDataCur, /* Cursor number from which to take column data */ 926 int regOut, /* Put the new key into this register if not 0 */ 927 int prefixOnly, /* Compute only a unique prefix of the key */ 928 int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */ 929 Index *pPrior, /* Previously generated index key */ 930 int regPrior /* Register holding previous generated key */ 931 ){ 932 Vdbe *v = pParse->pVdbe; 933 int j; 934 int regBase; 935 int nCol; 936 937 if( piPartIdxLabel ){ 938 if( pIdx->pPartIdxWhere ){ 939 *piPartIdxLabel = sqlite3VdbeMakeLabel(pParse); 940 pParse->iSelfTab = iDataCur + 1; 941 sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel, 942 SQLITE_JUMPIFNULL); 943 pParse->iSelfTab = 0; 944 pPrior = 0; /* Ticket a9efb42811fa41ee 2019-11-02; 945 ** pPartIdxWhere may have corrupted regPrior registers */ 946 }else{ 947 *piPartIdxLabel = 0; 948 } 949 } 950 nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn; 951 regBase = sqlite3GetTempRange(pParse, nCol); 952 if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0; 953 for(j=0; j<nCol; j++){ 954 if( pPrior 955 && pPrior->aiColumn[j]==pIdx->aiColumn[j] 956 && pPrior->aiColumn[j]!=XN_EXPR 957 ){ 958 /* This column was already computed by the previous index */ 959 continue; 960 } 961 sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iDataCur, j, regBase+j); 962 if( pIdx->aiColumn[j]>=0 ){ 963 /* If the column affinity is REAL but the number is an integer, then it 964 ** might be stored in the table as an integer (using a compact 965 ** representation) then converted to REAL by an OP_RealAffinity opcode. 966 ** But we are getting ready to store this value back into an index, where 967 ** it should be converted by to INTEGER again. So omit the 968 ** OP_RealAffinity opcode if it is present */ 969 sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity); 970 } 971 } 972 if( regOut ){ 973 sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut); 974 } 975 sqlite3ReleaseTempRange(pParse, regBase, nCol); 976 return regBase; 977 } 978 979 /* 980 ** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label 981 ** because it was a partial index, then this routine should be called to 982 ** resolve that label. 983 */ 984 void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){ 985 if( iLabel ){ 986 sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel); 987 } 988 } 989