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 ** to handle UPDATE statements. 14 */ 15 #include "sqliteInt.h" 16 17 #ifndef SQLITE_OMIT_VIRTUALTABLE 18 /* Forward declaration */ 19 static void updateVirtualTable( 20 Parse *pParse, /* The parsing context */ 21 SrcList *pSrc, /* The virtual table to be modified */ 22 Table *pTab, /* The virtual table */ 23 ExprList *pChanges, /* The columns to change in the UPDATE statement */ 24 Expr *pRowidExpr, /* Expression used to recompute the rowid */ 25 int *aXRef, /* Mapping from columns of pTab to entries in pChanges */ 26 Expr *pWhere, /* WHERE clause of the UPDATE statement */ 27 int onError /* ON CONFLICT strategy */ 28 ); 29 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 30 31 /* 32 ** The most recently coded instruction was an OP_Column to retrieve the 33 ** i-th column of table pTab. This routine sets the P4 parameter of the 34 ** OP_Column to the default value, if any. 35 ** 36 ** The default value of a column is specified by a DEFAULT clause in the 37 ** column definition. This was either supplied by the user when the table 38 ** was created, or added later to the table definition by an ALTER TABLE 39 ** command. If the latter, then the row-records in the table btree on disk 40 ** may not contain a value for the column and the default value, taken 41 ** from the P4 parameter of the OP_Column instruction, is returned instead. 42 ** If the former, then all row-records are guaranteed to include a value 43 ** for the column and the P4 value is not required. 44 ** 45 ** Column definitions created by an ALTER TABLE command may only have 46 ** literal default values specified: a number, null or a string. (If a more 47 ** complicated default expression value was provided, it is evaluated 48 ** when the ALTER TABLE is executed and one of the literal values written 49 ** into the sqlite_schema table.) 50 ** 51 ** Therefore, the P4 parameter is only required if the default value for 52 ** the column is a literal number, string or null. The sqlite3ValueFromExpr() 53 ** function is capable of transforming these types of expressions into 54 ** sqlite3_value objects. 55 ** 56 ** If column as REAL affinity and the table is an ordinary b-tree table 57 ** (not a virtual table) then the value might have been stored as an 58 ** integer. In that case, add an OP_RealAffinity opcode to make sure 59 ** it has been converted into REAL. 60 */ 61 void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){ 62 assert( pTab!=0 ); 63 if( !pTab->pSelect ){ 64 sqlite3_value *pValue = 0; 65 u8 enc = ENC(sqlite3VdbeDb(v)); 66 Column *pCol = &pTab->aCol[i]; 67 VdbeComment((v, "%s.%s", pTab->zName, pCol->zName)); 68 assert( i<pTab->nCol ); 69 sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc, 70 pCol->affinity, &pValue); 71 if( pValue ){ 72 sqlite3VdbeAppendP4(v, pValue, P4_MEM); 73 } 74 } 75 #ifndef SQLITE_OMIT_FLOATING_POINT 76 if( pTab->aCol[i].affinity==SQLITE_AFF_REAL && !IsVirtual(pTab) ){ 77 sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg); 78 } 79 #endif 80 } 81 82 /* 83 ** Check to see if column iCol of index pIdx references any of the 84 ** columns defined by aXRef and chngRowid. Return true if it does 85 ** and false if not. This is an optimization. False-positives are a 86 ** performance degradation, but false-negatives can result in a corrupt 87 ** index and incorrect answers. 88 ** 89 ** aXRef[j] will be non-negative if column j of the original table is 90 ** being updated. chngRowid will be true if the rowid of the table is 91 ** being updated. 92 */ 93 static int indexColumnIsBeingUpdated( 94 Index *pIdx, /* The index to check */ 95 int iCol, /* Which column of the index to check */ 96 int *aXRef, /* aXRef[j]>=0 if column j is being updated */ 97 int chngRowid /* true if the rowid is being updated */ 98 ){ 99 i16 iIdxCol = pIdx->aiColumn[iCol]; 100 assert( iIdxCol!=XN_ROWID ); /* Cannot index rowid */ 101 if( iIdxCol>=0 ){ 102 return aXRef[iIdxCol]>=0; 103 } 104 assert( iIdxCol==XN_EXPR ); 105 assert( pIdx->aColExpr!=0 ); 106 assert( pIdx->aColExpr->a[iCol].pExpr!=0 ); 107 return sqlite3ExprReferencesUpdatedColumn(pIdx->aColExpr->a[iCol].pExpr, 108 aXRef,chngRowid); 109 } 110 111 /* 112 ** Check to see if index pIdx is a partial index whose conditional 113 ** expression might change values due to an UPDATE. Return true if 114 ** the index is subject to change and false if the index is guaranteed 115 ** to be unchanged. This is an optimization. False-positives are a 116 ** performance degradation, but false-negatives can result in a corrupt 117 ** index and incorrect answers. 118 ** 119 ** aXRef[j] will be non-negative if column j of the original table is 120 ** being updated. chngRowid will be true if the rowid of the table is 121 ** being updated. 122 */ 123 static int indexWhereClauseMightChange( 124 Index *pIdx, /* The index to check */ 125 int *aXRef, /* aXRef[j]>=0 if column j is being updated */ 126 int chngRowid /* true if the rowid is being updated */ 127 ){ 128 if( pIdx->pPartIdxWhere==0 ) return 0; 129 return sqlite3ExprReferencesUpdatedColumn(pIdx->pPartIdxWhere, 130 aXRef, chngRowid); 131 } 132 133 /* 134 ** Allocate and return a pointer to an expression of type TK_ROW with 135 ** Expr.iColumn set to value (iCol+1). The resolver will modify the 136 ** expression to be a TK_COLUMN reading column iCol of the first 137 ** table in the source-list (pSrc->a[0]). 138 */ 139 static Expr *exprRowColumn(Parse *pParse, int iCol){ 140 Expr *pRet = sqlite3PExpr(pParse, TK_ROW, 0, 0); 141 if( pRet ) pRet->iColumn = iCol+1; 142 return pRet; 143 } 144 145 /* 146 ** Assuming both the pLimit and pOrderBy parameters are NULL, this function 147 ** generates VM code to run the query: 148 ** 149 ** SELECT <other-columns>, pChanges FROM pTabList WHERE pWhere 150 ** 151 ** and write the results to the ephemeral table already opened as cursor 152 ** iEph. None of pChanges, pTabList or pWhere are modified or consumed by 153 ** this function, they must be deleted by the caller. 154 ** 155 ** Or, if pLimit and pOrderBy are not NULL, and pTab is not a view: 156 ** 157 ** SELECT <other-columns>, pChanges FROM pTabList 158 ** WHERE pWhere 159 ** GROUP BY <other-columns> 160 ** ORDER BY pOrderBy LIMIT pLimit 161 ** 162 ** If pTab is a view, the GROUP BY clause is omitted. 163 ** 164 ** Exactly how results are written to table iEph, and exactly what 165 ** the <other-columns> in the query above are is determined by the type 166 ** of table pTabList->a[0].pTab. 167 ** 168 ** If the table is a WITHOUT ROWID table, then argument pPk must be its 169 ** PRIMARY KEY. In this case <other-columns> are the primary key columns 170 ** of the table, in order. The results of the query are written to ephemeral 171 ** table iEph as index keys, using OP_IdxInsert. 172 ** 173 ** If the table is actually a view, then <other-columns> are all columns of 174 ** the view. The results are written to the ephemeral table iEph as records 175 ** with automatically assigned integer keys. 176 ** 177 ** If the table is a virtual or ordinary intkey table, then <other-columns> 178 ** is its rowid. For a virtual table, the results are written to iEph as 179 ** records with automatically assigned integer keys For intkey tables, the 180 ** rowid value in <other-columns> is used as the integer key, and the 181 ** remaining fields make up the table record. 182 */ 183 static void updateFromSelect( 184 Parse *pParse, /* Parse context */ 185 int iEph, /* Cursor for open eph. table */ 186 Index *pPk, /* PK if table 0 is WITHOUT ROWID */ 187 ExprList *pChanges, /* List of expressions to return */ 188 SrcList *pTabList, /* List of tables to select from */ 189 Expr *pWhere, /* WHERE clause for query */ 190 ExprList *pOrderBy, /* ORDER BY clause */ 191 Expr *pLimit /* LIMIT clause */ 192 ){ 193 int i; 194 SelectDest dest; 195 Select *pSelect = 0; 196 ExprList *pList = 0; 197 ExprList *pGrp = 0; 198 Expr *pLimit2 = 0; 199 ExprList *pOrderBy2 = 0; 200 sqlite3 *db = pParse->db; 201 Table *pTab = pTabList->a[0].pTab; 202 SrcList *pSrc; 203 Expr *pWhere2; 204 int eDest; 205 206 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT 207 if( pOrderBy && pLimit==0 ) { 208 sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on UPDATE"); 209 return; 210 } 211 pOrderBy2 = sqlite3ExprListDup(db, pOrderBy, 0); 212 pLimit2 = sqlite3ExprDup(db, pLimit, 0); 213 #else 214 UNUSED_PARAMETER(pOrderBy); 215 UNUSED_PARAMETER(pLimit); 216 #endif 217 218 pSrc = sqlite3SrcListDup(db, pTabList, 0); 219 pWhere2 = sqlite3ExprDup(db, pWhere, 0); 220 221 assert( pTabList->nSrc>1 ); 222 if( pSrc ){ 223 if( pSrc->a[0].zDatabase==0 ){ 224 int iSchema = sqlite3SchemaToIndex(db, pTab->pSchema); 225 pSrc->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iSchema].zDbSName); 226 } 227 pSrc->a[0].iCursor = -1; 228 pSrc->a[0].pTab->nTabRef--; 229 pSrc->a[0].pTab = 0; 230 } 231 if( pPk ){ 232 for(i=0; i<pPk->nKeyCol; i++){ 233 Expr *pNew = exprRowColumn(pParse, pPk->aiColumn[i]); 234 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT 235 if( pLimit ){ 236 pGrp = sqlite3ExprListAppend(pParse, pGrp, sqlite3ExprDup(db, pNew, 0)); 237 } 238 #endif 239 pList = sqlite3ExprListAppend(pParse, pList, pNew); 240 } 241 eDest = IsVirtual(pTab) ? SRT_Table : SRT_Upfrom; 242 }else if( pTab->pSelect ){ 243 for(i=0; i<pTab->nCol; i++){ 244 pList = sqlite3ExprListAppend(pParse, pList, exprRowColumn(pParse, i)); 245 } 246 eDest = SRT_Table; 247 }else{ 248 eDest = IsVirtual(pTab) ? SRT_Table : SRT_Upfrom; 249 pList = sqlite3ExprListAppend(pParse, 0, sqlite3PExpr(pParse,TK_ROW,0,0)); 250 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT 251 if( pLimit ){ 252 pGrp = sqlite3ExprListAppend(pParse, 0, sqlite3PExpr(pParse,TK_ROW,0,0)); 253 } 254 #endif 255 } 256 assert( pChanges!=0 || pParse->db->mallocFailed ); 257 if( pChanges ){ 258 for(i=0; i<pChanges->nExpr; i++){ 259 pList = sqlite3ExprListAppend(pParse, pList, 260 sqlite3ExprDup(db, pChanges->a[i].pExpr, 0) 261 ); 262 } 263 } 264 pSelect = sqlite3SelectNew(pParse, pList, 265 pSrc, pWhere2, pGrp, 0, pOrderBy2, SF_UpdateFrom|SF_IncludeHidden, pLimit2 266 ); 267 sqlite3SelectDestInit(&dest, eDest, iEph); 268 dest.iSDParm2 = (pPk ? pPk->nKeyCol : -1); 269 sqlite3Select(pParse, pSelect, &dest); 270 sqlite3SelectDelete(db, pSelect); 271 } 272 273 /* 274 ** Process an UPDATE statement. 275 ** 276 ** UPDATE OR IGNORE tbl SET a=b, c=d FROM tbl2... WHERE e<5 AND f NOT NULL; 277 ** \_______/ \_/ \______/ \_____/ \________________/ 278 ** onError | pChanges | pWhere 279 ** \_______________________/ 280 ** pTabList 281 */ 282 void sqlite3Update( 283 Parse *pParse, /* The parser context */ 284 SrcList *pTabList, /* The table in which we should change things */ 285 ExprList *pChanges, /* Things to be changed */ 286 Expr *pWhere, /* The WHERE clause. May be null */ 287 int onError, /* How to handle constraint errors */ 288 ExprList *pOrderBy, /* ORDER BY clause. May be null */ 289 Expr *pLimit, /* LIMIT clause. May be null */ 290 Upsert *pUpsert /* ON CONFLICT clause, or null */ 291 ){ 292 int i, j, k; /* Loop counters */ 293 Table *pTab; /* The table to be updated */ 294 int addrTop = 0; /* VDBE instruction address of the start of the loop */ 295 WhereInfo *pWInfo = 0; /* Information about the WHERE clause */ 296 Vdbe *v; /* The virtual database engine */ 297 Index *pIdx; /* For looping over indices */ 298 Index *pPk; /* The PRIMARY KEY index for WITHOUT ROWID tables */ 299 int nIdx; /* Number of indices that need updating */ 300 int nAllIdx; /* Total number of indexes */ 301 int iBaseCur; /* Base cursor number */ 302 int iDataCur; /* Cursor for the canonical data btree */ 303 int iIdxCur; /* Cursor for the first index */ 304 sqlite3 *db; /* The database structure */ 305 int *aRegIdx = 0; /* Registers for to each index and the main table */ 306 int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the 307 ** an expression for the i-th column of the table. 308 ** aXRef[i]==-1 if the i-th column is not changed. */ 309 u8 *aToOpen; /* 1 for tables and indices to be opened */ 310 u8 chngPk; /* PRIMARY KEY changed in a WITHOUT ROWID table */ 311 u8 chngRowid; /* Rowid changed in a normal table */ 312 u8 chngKey; /* Either chngPk or chngRowid */ 313 Expr *pRowidExpr = 0; /* Expression defining the new record number */ 314 int iRowidExpr = -1; /* Index of "rowid=" (or IPK) assignment in pChanges */ 315 AuthContext sContext; /* The authorization context */ 316 NameContext sNC; /* The name-context to resolve expressions in */ 317 int iDb; /* Database containing the table being updated */ 318 int eOnePass; /* ONEPASS_XXX value from where.c */ 319 int hasFK; /* True if foreign key processing is required */ 320 int labelBreak; /* Jump here to break out of UPDATE loop */ 321 int labelContinue; /* Jump here to continue next step of UPDATE loop */ 322 int flags; /* Flags for sqlite3WhereBegin() */ 323 324 #ifndef SQLITE_OMIT_TRIGGER 325 int isView; /* True when updating a view (INSTEAD OF trigger) */ 326 Trigger *pTrigger; /* List of triggers on pTab, if required */ 327 int tmask; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */ 328 #endif 329 int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */ 330 int iEph = 0; /* Ephemeral table holding all primary key values */ 331 int nKey = 0; /* Number of elements in regKey for WITHOUT ROWID */ 332 int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */ 333 int addrOpen = 0; /* Address of OP_OpenEphemeral */ 334 int iPk = 0; /* First of nPk cells holding PRIMARY KEY value */ 335 i16 nPk = 0; /* Number of components of the PRIMARY KEY */ 336 int bReplace = 0; /* True if REPLACE conflict resolution might happen */ 337 int bFinishSeek = 1; /* The OP_FinishSeek opcode is needed */ 338 int nChangeFrom = 0; /* If there is a FROM, pChanges->nExpr, else 0 */ 339 340 /* Register Allocations */ 341 int regRowCount = 0; /* A count of rows changed */ 342 int regOldRowid = 0; /* The old rowid */ 343 int regNewRowid = 0; /* The new rowid */ 344 int regNew = 0; /* Content of the NEW.* table in triggers */ 345 int regOld = 0; /* Content of OLD.* table in triggers */ 346 int regRowSet = 0; /* Rowset of rows to be updated */ 347 int regKey = 0; /* composite PRIMARY KEY value */ 348 349 memset(&sContext, 0, sizeof(sContext)); 350 db = pParse->db; 351 if( pParse->nErr || db->mallocFailed ){ 352 goto update_cleanup; 353 } 354 355 /* Locate the table which we want to update. 356 */ 357 pTab = sqlite3SrcListLookup(pParse, pTabList); 358 if( pTab==0 ) goto update_cleanup; 359 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 360 361 /* Figure out if we have any triggers and if the table being 362 ** updated is a view. 363 */ 364 #ifndef SQLITE_OMIT_TRIGGER 365 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask); 366 isView = pTab->pSelect!=0; 367 assert( pTrigger || tmask==0 ); 368 #else 369 # define pTrigger 0 370 # define isView 0 371 # define tmask 0 372 #endif 373 #ifdef SQLITE_OMIT_VIEW 374 # undef isView 375 # define isView 0 376 #endif 377 378 /* If there was a FROM clause, set nChangeFrom to the number of expressions 379 ** in the change-list. Otherwise, set it to 0. There cannot be a FROM 380 ** clause if this function is being called to generate code for part of 381 ** an UPSERT statement. */ 382 nChangeFrom = (pTabList->nSrc>1) ? pChanges->nExpr : 0; 383 assert( nChangeFrom==0 || pUpsert==0 ); 384 385 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT 386 if( !isView && nChangeFrom==0 ){ 387 pWhere = sqlite3LimitWhere( 388 pParse, pTabList, pWhere, pOrderBy, pLimit, "UPDATE" 389 ); 390 pOrderBy = 0; 391 pLimit = 0; 392 } 393 #endif 394 395 if( sqlite3ViewGetColumnNames(pParse, pTab) ){ 396 goto update_cleanup; 397 } 398 if( sqlite3IsReadOnly(pParse, pTab, tmask) ){ 399 goto update_cleanup; 400 } 401 402 /* Allocate a cursors for the main database table and for all indices. 403 ** The index cursors might not be used, but if they are used they 404 ** need to occur right after the database cursor. So go ahead and 405 ** allocate enough space, just in case. 406 */ 407 iBaseCur = iDataCur = pParse->nTab++; 408 iIdxCur = iDataCur+1; 409 pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab); 410 testcase( pPk!=0 && pPk!=pTab->pIndex ); 411 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ 412 if( pPk==pIdx ){ 413 iDataCur = pParse->nTab; 414 } 415 pParse->nTab++; 416 } 417 if( pUpsert ){ 418 /* On an UPSERT, reuse the same cursors already opened by INSERT */ 419 iDataCur = pUpsert->iDataCur; 420 iIdxCur = pUpsert->iIdxCur; 421 pParse->nTab = iBaseCur; 422 } 423 pTabList->a[0].iCursor = iDataCur; 424 425 /* Allocate space for aXRef[], aRegIdx[], and aToOpen[]. 426 ** Initialize aXRef[] and aToOpen[] to their default values. 427 */ 428 aXRef = sqlite3DbMallocRawNN(db, sizeof(int) * (pTab->nCol+nIdx+1) + nIdx+2 ); 429 if( aXRef==0 ) goto update_cleanup; 430 aRegIdx = aXRef+pTab->nCol; 431 aToOpen = (u8*)(aRegIdx+nIdx+1); 432 memset(aToOpen, 1, nIdx+1); 433 aToOpen[nIdx+1] = 0; 434 for(i=0; i<pTab->nCol; i++) aXRef[i] = -1; 435 436 /* Initialize the name-context */ 437 memset(&sNC, 0, sizeof(sNC)); 438 sNC.pParse = pParse; 439 sNC.pSrcList = pTabList; 440 sNC.uNC.pUpsert = pUpsert; 441 sNC.ncFlags = NC_UUpsert; 442 443 /* Begin generating code. */ 444 v = sqlite3GetVdbe(pParse); 445 if( v==0 ) goto update_cleanup; 446 447 /* Resolve the column names in all the expressions of the 448 ** of the UPDATE statement. Also find the column index 449 ** for each column to be updated in the pChanges array. For each 450 ** column to be updated, make sure we have authorization to change 451 ** that column. 452 */ 453 chngRowid = chngPk = 0; 454 for(i=0; i<pChanges->nExpr; i++){ 455 /* If this is an UPDATE with a FROM clause, do not resolve expressions 456 ** here. The call to sqlite3Select() below will do that. */ 457 if( nChangeFrom==0 && sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){ 458 goto update_cleanup; 459 } 460 for(j=0; j<pTab->nCol; j++){ 461 if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zEName)==0 ){ 462 if( j==pTab->iPKey ){ 463 chngRowid = 1; 464 pRowidExpr = pChanges->a[i].pExpr; 465 iRowidExpr = i; 466 }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){ 467 chngPk = 1; 468 } 469 #ifndef SQLITE_OMIT_GENERATED_COLUMNS 470 else if( pTab->aCol[j].colFlags & COLFLAG_GENERATED ){ 471 testcase( pTab->aCol[j].colFlags & COLFLAG_VIRTUAL ); 472 testcase( pTab->aCol[j].colFlags & COLFLAG_STORED ); 473 sqlite3ErrorMsg(pParse, 474 "cannot UPDATE generated column \"%s\"", 475 pTab->aCol[j].zName); 476 goto update_cleanup; 477 } 478 #endif 479 aXRef[j] = i; 480 break; 481 } 482 } 483 if( j>=pTab->nCol ){ 484 if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zEName) ){ 485 j = -1; 486 chngRowid = 1; 487 pRowidExpr = pChanges->a[i].pExpr; 488 iRowidExpr = i; 489 }else{ 490 sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zEName); 491 pParse->checkSchema = 1; 492 goto update_cleanup; 493 } 494 } 495 #ifndef SQLITE_OMIT_AUTHORIZATION 496 { 497 int rc; 498 rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName, 499 j<0 ? "ROWID" : pTab->aCol[j].zName, 500 db->aDb[iDb].zDbSName); 501 if( rc==SQLITE_DENY ){ 502 goto update_cleanup; 503 }else if( rc==SQLITE_IGNORE ){ 504 aXRef[j] = -1; 505 } 506 } 507 #endif 508 } 509 assert( (chngRowid & chngPk)==0 ); 510 assert( chngRowid==0 || chngRowid==1 ); 511 assert( chngPk==0 || chngPk==1 ); 512 chngKey = chngRowid + chngPk; 513 514 #ifndef SQLITE_OMIT_GENERATED_COLUMNS 515 /* Mark generated columns as changing if their generator expressions 516 ** reference any changing column. The actual aXRef[] value for 517 ** generated expressions is not used, other than to check to see that it 518 ** is non-negative, so the value of aXRef[] for generated columns can be 519 ** set to any non-negative number. We use 99999 so that the value is 520 ** obvious when looking at aXRef[] in a symbolic debugger. 521 */ 522 if( pTab->tabFlags & TF_HasGenerated ){ 523 int bProgress; 524 testcase( pTab->tabFlags & TF_HasVirtual ); 525 testcase( pTab->tabFlags & TF_HasStored ); 526 do{ 527 bProgress = 0; 528 for(i=0; i<pTab->nCol; i++){ 529 if( aXRef[i]>=0 ) continue; 530 if( (pTab->aCol[i].colFlags & COLFLAG_GENERATED)==0 ) continue; 531 if( sqlite3ExprReferencesUpdatedColumn(pTab->aCol[i].pDflt, 532 aXRef, chngRowid) ){ 533 aXRef[i] = 99999; 534 bProgress = 1; 535 } 536 } 537 }while( bProgress ); 538 } 539 #endif 540 541 /* The SET expressions are not actually used inside the WHERE loop. 542 ** So reset the colUsed mask. Unless this is a virtual table. In that 543 ** case, set all bits of the colUsed mask (to ensure that the virtual 544 ** table implementation makes all columns available). 545 */ 546 pTabList->a[0].colUsed = IsVirtual(pTab) ? ALLBITS : 0; 547 548 hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey); 549 550 /* There is one entry in the aRegIdx[] array for each index on the table 551 ** being updated. Fill in aRegIdx[] with a register number that will hold 552 ** the key for accessing each index. 553 */ 554 if( onError==OE_Replace ) bReplace = 1; 555 for(nAllIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nAllIdx++){ 556 int reg; 557 if( chngKey || hasFK>1 || pIdx==pPk 558 || indexWhereClauseMightChange(pIdx,aXRef,chngRowid) 559 ){ 560 reg = ++pParse->nMem; 561 pParse->nMem += pIdx->nColumn; 562 }else{ 563 reg = 0; 564 for(i=0; i<pIdx->nKeyCol; i++){ 565 if( indexColumnIsBeingUpdated(pIdx, i, aXRef, chngRowid) ){ 566 reg = ++pParse->nMem; 567 pParse->nMem += pIdx->nColumn; 568 if( onError==OE_Default && pIdx->onError==OE_Replace ){ 569 bReplace = 1; 570 } 571 break; 572 } 573 } 574 } 575 if( reg==0 ) aToOpen[nAllIdx+1] = 0; 576 aRegIdx[nAllIdx] = reg; 577 } 578 aRegIdx[nAllIdx] = ++pParse->nMem; /* Register storing the table record */ 579 if( bReplace ){ 580 /* If REPLACE conflict resolution might be invoked, open cursors on all 581 ** indexes in case they are needed to delete records. */ 582 memset(aToOpen, 1, nIdx+1); 583 } 584 585 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v); 586 sqlite3BeginWriteOperation(pParse, pTrigger || hasFK, iDb); 587 588 /* Allocate required registers. */ 589 if( !IsVirtual(pTab) ){ 590 /* For now, regRowSet and aRegIdx[nAllIdx] share the same register. 591 ** If regRowSet turns out to be needed, then aRegIdx[nAllIdx] will be 592 ** reallocated. aRegIdx[nAllIdx] is the register in which the main 593 ** table record is written. regRowSet holds the RowSet for the 594 ** two-pass update algorithm. */ 595 assert( aRegIdx[nAllIdx]==pParse->nMem ); 596 regRowSet = aRegIdx[nAllIdx]; 597 regOldRowid = regNewRowid = ++pParse->nMem; 598 if( chngPk || pTrigger || hasFK ){ 599 regOld = pParse->nMem + 1; 600 pParse->nMem += pTab->nCol; 601 } 602 if( chngKey || pTrigger || hasFK ){ 603 regNewRowid = ++pParse->nMem; 604 } 605 regNew = pParse->nMem + 1; 606 pParse->nMem += pTab->nCol; 607 } 608 609 /* Start the view context. */ 610 if( isView ){ 611 sqlite3AuthContextPush(pParse, &sContext, pTab->zName); 612 } 613 614 /* If we are trying to update a view, realize that view into 615 ** an ephemeral table. 616 */ 617 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) 618 if( nChangeFrom==0 && isView ){ 619 sqlite3MaterializeView(pParse, pTab, 620 pWhere, pOrderBy, pLimit, iDataCur 621 ); 622 pOrderBy = 0; 623 pLimit = 0; 624 } 625 #endif 626 627 /* Resolve the column names in all the expressions in the 628 ** WHERE clause. 629 */ 630 if( nChangeFrom==0 && sqlite3ResolveExprNames(&sNC, pWhere) ){ 631 goto update_cleanup; 632 } 633 634 #ifndef SQLITE_OMIT_VIRTUALTABLE 635 /* Virtual tables must be handled separately */ 636 if( IsVirtual(pTab) ){ 637 updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef, 638 pWhere, onError); 639 goto update_cleanup; 640 } 641 #endif 642 643 /* Jump to labelBreak to abandon further processing of this UPDATE */ 644 labelContinue = labelBreak = sqlite3VdbeMakeLabel(pParse); 645 646 /* Not an UPSERT. Normal processing. Begin by 647 ** initialize the count of updated rows */ 648 if( (db->flags&SQLITE_CountRows)!=0 649 && !pParse->pTriggerTab 650 && !pParse->nested 651 && !pParse->bReturning 652 && pUpsert==0 653 ){ 654 regRowCount = ++pParse->nMem; 655 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount); 656 } 657 658 if( nChangeFrom==0 && HasRowid(pTab) ){ 659 sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid); 660 iEph = pParse->nTab++; 661 addrOpen = sqlite3VdbeAddOp3(v, OP_OpenEphemeral, iEph, 0, regRowSet); 662 }else{ 663 assert( pPk!=0 || HasRowid(pTab) ); 664 nPk = pPk ? pPk->nKeyCol : 0; 665 iPk = pParse->nMem+1; 666 pParse->nMem += nPk; 667 pParse->nMem += nChangeFrom; 668 regKey = ++pParse->nMem; 669 if( pUpsert==0 ){ 670 int nEphCol = nPk + nChangeFrom + (isView ? pTab->nCol : 0); 671 iEph = pParse->nTab++; 672 if( pPk ) sqlite3VdbeAddOp3(v, OP_Null, 0, iPk, iPk+nPk-1); 673 addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nEphCol); 674 if( pPk ){ 675 KeyInfo *pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pPk); 676 if( pKeyInfo ){ 677 pKeyInfo->nAllField = nEphCol; 678 sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO); 679 } 680 } 681 if( nChangeFrom ){ 682 updateFromSelect( 683 pParse, iEph, pPk, pChanges, pTabList, pWhere, pOrderBy, pLimit 684 ); 685 #ifndef SQLITE_OMIT_SUBQUERY 686 if( isView ) iDataCur = iEph; 687 #endif 688 } 689 } 690 } 691 692 if( nChangeFrom ){ 693 sqlite3MultiWrite(pParse); 694 eOnePass = ONEPASS_OFF; 695 nKey = nPk; 696 regKey = iPk; 697 }else{ 698 if( pUpsert ){ 699 /* If this is an UPSERT, then all cursors have already been opened by 700 ** the outer INSERT and the data cursor should be pointing at the row 701 ** that is to be updated. So bypass the code that searches for the 702 ** row(s) to be updated. 703 */ 704 pWInfo = 0; 705 eOnePass = ONEPASS_SINGLE; 706 sqlite3ExprIfFalse(pParse, pWhere, labelBreak, SQLITE_JUMPIFNULL); 707 bFinishSeek = 0; 708 }else{ 709 /* Begin the database scan. 710 ** 711 ** Do not consider a single-pass strategy for a multi-row update if 712 ** there are any triggers or foreign keys to process, or rows may 713 ** be deleted as a result of REPLACE conflict handling. Any of these 714 ** things might disturb a cursor being used to scan through the table 715 ** or index, causing a single-pass approach to malfunction. */ 716 flags = WHERE_ONEPASS_DESIRED; 717 if( !pParse->nested && !pTrigger && !hasFK && !chngKey && !bReplace ){ 718 flags |= WHERE_ONEPASS_MULTIROW; 719 } 720 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, flags,iIdxCur); 721 if( pWInfo==0 ) goto update_cleanup; 722 723 /* A one-pass strategy that might update more than one row may not 724 ** be used if any column of the index used for the scan is being 725 ** updated. Otherwise, if there is an index on "b", statements like 726 ** the following could create an infinite loop: 727 ** 728 ** UPDATE t1 SET b=b+1 WHERE b>? 729 ** 730 ** Fall back to ONEPASS_OFF if where.c has selected a ONEPASS_MULTI 731 ** strategy that uses an index for which one or more columns are being 732 ** updated. */ 733 eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass); 734 bFinishSeek = sqlite3WhereUsesDeferredSeek(pWInfo); 735 if( eOnePass!=ONEPASS_SINGLE ){ 736 sqlite3MultiWrite(pParse); 737 if( eOnePass==ONEPASS_MULTI ){ 738 int iCur = aiCurOnePass[1]; 739 if( iCur>=0 && iCur!=iDataCur && aToOpen[iCur-iBaseCur] ){ 740 eOnePass = ONEPASS_OFF; 741 } 742 assert( iCur!=iDataCur || !HasRowid(pTab) ); 743 } 744 } 745 } 746 747 if( HasRowid(pTab) ){ 748 /* Read the rowid of the current row of the WHERE scan. In ONEPASS_OFF 749 ** mode, write the rowid into the FIFO. In either of the one-pass modes, 750 ** leave it in register regOldRowid. */ 751 sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid); 752 if( eOnePass==ONEPASS_OFF ){ 753 aRegIdx[nAllIdx] = ++pParse->nMem; 754 sqlite3VdbeAddOp3(v, OP_Insert, iEph, regRowSet, regOldRowid); 755 }else{ 756 if( ALWAYS(addrOpen) ) sqlite3VdbeChangeToNoop(v, addrOpen); 757 } 758 }else{ 759 /* Read the PK of the current row into an array of registers. In 760 ** ONEPASS_OFF mode, serialize the array into a record and store it in 761 ** the ephemeral table. Or, in ONEPASS_SINGLE or MULTI mode, change 762 ** the OP_OpenEphemeral instruction to a Noop (the ephemeral table 763 ** is not required) and leave the PK fields in the array of registers. */ 764 for(i=0; i<nPk; i++){ 765 assert( pPk->aiColumn[i]>=0 ); 766 sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, 767 pPk->aiColumn[i], iPk+i); 768 } 769 if( eOnePass ){ 770 if( addrOpen ) sqlite3VdbeChangeToNoop(v, addrOpen); 771 nKey = nPk; 772 regKey = iPk; 773 }else{ 774 sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey, 775 sqlite3IndexAffinityStr(db, pPk), nPk); 776 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEph, regKey, iPk, nPk); 777 } 778 } 779 } 780 781 if( pUpsert==0 ){ 782 if( nChangeFrom==0 && eOnePass!=ONEPASS_MULTI ){ 783 sqlite3WhereEnd(pWInfo); 784 } 785 786 if( !isView ){ 787 int addrOnce = 0; 788 789 /* Open every index that needs updating. */ 790 if( eOnePass!=ONEPASS_OFF ){ 791 if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0; 792 if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0; 793 } 794 795 if( eOnePass==ONEPASS_MULTI && (nIdx-(aiCurOnePass[1]>=0))>0 ){ 796 addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); 797 } 798 sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, iBaseCur, 799 aToOpen, 0, 0); 800 if( addrOnce ){ 801 sqlite3VdbeJumpHereOrPopInst(v, addrOnce); 802 } 803 } 804 805 /* Top of the update loop */ 806 if( eOnePass!=ONEPASS_OFF ){ 807 if( aiCurOnePass[0]!=iDataCur 808 && aiCurOnePass[1]!=iDataCur 809 #ifdef SQLITE_ALLOW_ROWID_IN_VIEW 810 && !isView 811 #endif 812 ){ 813 assert( pPk ); 814 sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey,nKey); 815 VdbeCoverage(v); 816 } 817 if( eOnePass!=ONEPASS_SINGLE ){ 818 labelContinue = sqlite3VdbeMakeLabel(pParse); 819 } 820 sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak); 821 VdbeCoverageIf(v, pPk==0); 822 VdbeCoverageIf(v, pPk!=0); 823 }else if( pPk || nChangeFrom ){ 824 labelContinue = sqlite3VdbeMakeLabel(pParse); 825 sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v); 826 addrTop = sqlite3VdbeCurrentAddr(v); 827 if( nChangeFrom ){ 828 if( !isView ){ 829 if( pPk ){ 830 for(i=0; i<nPk; i++){ 831 sqlite3VdbeAddOp3(v, OP_Column, iEph, i, iPk+i); 832 } 833 sqlite3VdbeAddOp4Int( 834 v, OP_NotFound, iDataCur, labelContinue, iPk, nPk 835 ); VdbeCoverage(v); 836 }else{ 837 sqlite3VdbeAddOp2(v, OP_Rowid, iEph, regOldRowid); 838 sqlite3VdbeAddOp3( 839 v, OP_NotExists, iDataCur, labelContinue, regOldRowid 840 ); VdbeCoverage(v); 841 } 842 } 843 }else{ 844 sqlite3VdbeAddOp2(v, OP_RowData, iEph, regKey); 845 sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey,0); 846 VdbeCoverage(v); 847 } 848 }else{ 849 sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v); 850 labelContinue = sqlite3VdbeMakeLabel(pParse); 851 addrTop = sqlite3VdbeAddOp2(v, OP_Rowid, iEph, regOldRowid); 852 VdbeCoverage(v); 853 sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid); 854 VdbeCoverage(v); 855 } 856 } 857 858 /* If the rowid value will change, set register regNewRowid to 859 ** contain the new value. If the rowid is not being modified, 860 ** then regNewRowid is the same register as regOldRowid, which is 861 ** already populated. */ 862 assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid ); 863 if( chngRowid ){ 864 assert( iRowidExpr>=0 ); 865 if( nChangeFrom==0 ){ 866 sqlite3ExprCode(pParse, pRowidExpr, regNewRowid); 867 }else{ 868 sqlite3VdbeAddOp3(v, OP_Column, iEph, iRowidExpr, regNewRowid); 869 } 870 sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v); 871 } 872 873 /* Compute the old pre-UPDATE content of the row being changed, if that 874 ** information is needed */ 875 if( chngPk || hasFK || pTrigger ){ 876 u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0); 877 oldmask |= sqlite3TriggerColmask(pParse, 878 pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError 879 ); 880 for(i=0; i<pTab->nCol; i++){ 881 u32 colFlags = pTab->aCol[i].colFlags; 882 k = sqlite3TableColumnToStorage(pTab, i) + regOld; 883 if( oldmask==0xffffffff 884 || (i<32 && (oldmask & MASKBIT32(i))!=0) 885 || (colFlags & COLFLAG_PRIMKEY)!=0 886 ){ 887 testcase( oldmask!=0xffffffff && i==31 ); 888 sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, k); 889 }else{ 890 sqlite3VdbeAddOp2(v, OP_Null, 0, k); 891 } 892 } 893 if( chngRowid==0 && pPk==0 ){ 894 sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid); 895 } 896 } 897 898 /* Populate the array of registers beginning at regNew with the new 899 ** row data. This array is used to check constants, create the new 900 ** table and index records, and as the values for any new.* references 901 ** made by triggers. 902 ** 903 ** If there are one or more BEFORE triggers, then do not populate the 904 ** registers associated with columns that are (a) not modified by 905 ** this UPDATE statement and (b) not accessed by new.* references. The 906 ** values for registers not modified by the UPDATE must be reloaded from 907 ** the database after the BEFORE triggers are fired anyway (as the trigger 908 ** may have modified them). So not loading those that are not going to 909 ** be used eliminates some redundant opcodes. 910 */ 911 newmask = sqlite3TriggerColmask( 912 pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError 913 ); 914 for(i=0, k=regNew; i<pTab->nCol; i++, k++){ 915 if( i==pTab->iPKey ){ 916 sqlite3VdbeAddOp2(v, OP_Null, 0, k); 917 }else if( (pTab->aCol[i].colFlags & COLFLAG_GENERATED)!=0 ){ 918 if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ) k--; 919 }else{ 920 j = aXRef[i]; 921 if( j>=0 ){ 922 if( nChangeFrom ){ 923 int nOff = (isView ? pTab->nCol : nPk); 924 assert( eOnePass==ONEPASS_OFF ); 925 sqlite3VdbeAddOp3(v, OP_Column, iEph, nOff+j, k); 926 }else{ 927 sqlite3ExprCode(pParse, pChanges->a[j].pExpr, k); 928 } 929 }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){ 930 /* This branch loads the value of a column that will not be changed 931 ** into a register. This is done if there are no BEFORE triggers, or 932 ** if there are one or more BEFORE triggers that use this value via 933 ** a new.* reference in a trigger program. 934 */ 935 testcase( i==31 ); 936 testcase( i==32 ); 937 sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, k); 938 bFinishSeek = 0; 939 }else{ 940 sqlite3VdbeAddOp2(v, OP_Null, 0, k); 941 } 942 } 943 } 944 #ifndef SQLITE_OMIT_GENERATED_COLUMNS 945 if( pTab->tabFlags & TF_HasGenerated ){ 946 testcase( pTab->tabFlags & TF_HasVirtual ); 947 testcase( pTab->tabFlags & TF_HasStored ); 948 sqlite3ComputeGeneratedColumns(pParse, regNew, pTab); 949 } 950 #endif 951 952 /* Fire any BEFORE UPDATE triggers. This happens before constraints are 953 ** verified. One could argue that this is wrong. 954 */ 955 if( tmask&TRIGGER_BEFORE ){ 956 sqlite3TableAffinity(v, pTab, regNew); 957 sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 958 TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue); 959 960 if( !isView ){ 961 /* The row-trigger may have deleted the row being updated. In this 962 ** case, jump to the next row. No updates or AFTER triggers are 963 ** required. This behavior - what happens when the row being updated 964 ** is deleted or renamed by a BEFORE trigger - is left undefined in the 965 ** documentation. 966 */ 967 if( pPk ){ 968 sqlite3VdbeAddOp4Int(v, OP_NotFound,iDataCur,labelContinue,regKey,nKey); 969 VdbeCoverage(v); 970 }else{ 971 sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue,regOldRowid); 972 VdbeCoverage(v); 973 } 974 975 /* After-BEFORE-trigger-reload-loop: 976 ** If it did not delete it, the BEFORE trigger may still have modified 977 ** some of the columns of the row being updated. Load the values for 978 ** all columns not modified by the update statement into their registers 979 ** in case this has happened. Only unmodified columns are reloaded. 980 ** The values computed for modified columns use the values before the 981 ** BEFORE trigger runs. See test case trigger1-18.0 (added 2018-04-26) 982 ** for an example. 983 */ 984 for(i=0, k=regNew; i<pTab->nCol; i++, k++){ 985 if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){ 986 if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ) k--; 987 }else if( aXRef[i]<0 && i!=pTab->iPKey ){ 988 sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, k); 989 } 990 } 991 #ifndef SQLITE_OMIT_GENERATED_COLUMNS 992 if( pTab->tabFlags & TF_HasGenerated ){ 993 testcase( pTab->tabFlags & TF_HasVirtual ); 994 testcase( pTab->tabFlags & TF_HasStored ); 995 sqlite3ComputeGeneratedColumns(pParse, regNew, pTab); 996 } 997 #endif 998 } 999 } 1000 1001 if( !isView ){ 1002 /* Do constraint checks. */ 1003 assert( regOldRowid>0 ); 1004 sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur, 1005 regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace, 1006 aXRef, 0); 1007 1008 /* If REPLACE conflict handling may have been used, or if the PK of the 1009 ** row is changing, then the GenerateConstraintChecks() above may have 1010 ** moved cursor iDataCur. Reseek it. */ 1011 if( bReplace || chngKey ){ 1012 if( pPk ){ 1013 sqlite3VdbeAddOp4Int(v, OP_NotFound,iDataCur,labelContinue,regKey,nKey); 1014 }else{ 1015 sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue,regOldRowid); 1016 } 1017 VdbeCoverageNeverTaken(v); 1018 } 1019 1020 /* Do FK constraint checks. */ 1021 if( hasFK ){ 1022 sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey); 1023 } 1024 1025 /* Delete the index entries associated with the current record. */ 1026 sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx, -1); 1027 1028 /* We must run the OP_FinishSeek opcode to resolve a prior 1029 ** OP_DeferredSeek if there is any possibility that there have been 1030 ** no OP_Column opcodes since the OP_DeferredSeek was issued. But 1031 ** we want to avoid the OP_FinishSeek if possible, as running it 1032 ** costs CPU cycles. */ 1033 if( bFinishSeek ){ 1034 sqlite3VdbeAddOp1(v, OP_FinishSeek, iDataCur); 1035 } 1036 1037 /* If changing the rowid value, or if there are foreign key constraints 1038 ** to process, delete the old record. Otherwise, add a noop OP_Delete 1039 ** to invoke the pre-update hook. 1040 ** 1041 ** That (regNew==regnewRowid+1) is true is also important for the 1042 ** pre-update hook. If the caller invokes preupdate_new(), the returned 1043 ** value is copied from memory cell (regNewRowid+1+iCol), where iCol 1044 ** is the column index supplied by the user. 1045 */ 1046 assert( regNew==regNewRowid+1 ); 1047 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK 1048 sqlite3VdbeAddOp3(v, OP_Delete, iDataCur, 1049 OPFLAG_ISUPDATE | ((hasFK>1 || chngKey) ? 0 : OPFLAG_ISNOOP), 1050 regNewRowid 1051 ); 1052 if( eOnePass==ONEPASS_MULTI ){ 1053 assert( hasFK==0 && chngKey==0 ); 1054 sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION); 1055 } 1056 if( !pParse->nested ){ 1057 sqlite3VdbeAppendP4(v, pTab, P4_TABLE); 1058 } 1059 #else 1060 if( hasFK>1 || chngKey ){ 1061 sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0); 1062 } 1063 #endif 1064 1065 if( hasFK ){ 1066 sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey); 1067 } 1068 1069 /* Insert the new index entries and the new record. */ 1070 sqlite3CompleteInsertion( 1071 pParse, pTab, iDataCur, iIdxCur, regNewRowid, aRegIdx, 1072 OPFLAG_ISUPDATE | (eOnePass==ONEPASS_MULTI ? OPFLAG_SAVEPOSITION : 0), 1073 0, 0 1074 ); 1075 1076 /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to 1077 ** handle rows (possibly in other tables) that refer via a foreign key 1078 ** to the row just updated. */ 1079 if( hasFK ){ 1080 sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey); 1081 } 1082 } 1083 1084 /* Increment the row counter 1085 */ 1086 if( regRowCount ){ 1087 sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1); 1088 } 1089 1090 sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 1091 TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue); 1092 1093 /* Repeat the above with the next record to be updated, until 1094 ** all record selected by the WHERE clause have been updated. 1095 */ 1096 if( eOnePass==ONEPASS_SINGLE ){ 1097 /* Nothing to do at end-of-loop for a single-pass */ 1098 }else if( eOnePass==ONEPASS_MULTI ){ 1099 sqlite3VdbeResolveLabel(v, labelContinue); 1100 sqlite3WhereEnd(pWInfo); 1101 }else{ 1102 sqlite3VdbeResolveLabel(v, labelContinue); 1103 sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v); 1104 } 1105 sqlite3VdbeResolveLabel(v, labelBreak); 1106 1107 /* Update the sqlite_sequence table by storing the content of the 1108 ** maximum rowid counter values recorded while inserting into 1109 ** autoincrement tables. 1110 */ 1111 if( pParse->nested==0 && pParse->pTriggerTab==0 && pUpsert==0 ){ 1112 sqlite3AutoincrementEnd(pParse); 1113 } 1114 1115 /* 1116 ** Return the number of rows that were changed, if we are tracking 1117 ** that information. 1118 */ 1119 if( regRowCount ){ 1120 sqlite3VdbeAddOp2(v, OP_ChngCntRow, regRowCount, 1); 1121 sqlite3VdbeSetNumCols(v, 1); 1122 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC); 1123 } 1124 1125 update_cleanup: 1126 sqlite3AuthContextPop(&sContext); 1127 sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */ 1128 sqlite3SrcListDelete(db, pTabList); 1129 sqlite3ExprListDelete(db, pChanges); 1130 sqlite3ExprDelete(db, pWhere); 1131 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) 1132 sqlite3ExprListDelete(db, pOrderBy); 1133 sqlite3ExprDelete(db, pLimit); 1134 #endif 1135 return; 1136 } 1137 /* Make sure "isView" and other macros defined above are undefined. Otherwise 1138 ** they may interfere with compilation of other functions in this file 1139 ** (or in another file, if this file becomes part of the amalgamation). */ 1140 #ifdef isView 1141 #undef isView 1142 #endif 1143 #ifdef pTrigger 1144 #undef pTrigger 1145 #endif 1146 1147 #ifndef SQLITE_OMIT_VIRTUALTABLE 1148 /* 1149 ** Generate code for an UPDATE of a virtual table. 1150 ** 1151 ** There are two possible strategies - the default and the special 1152 ** "onepass" strategy. Onepass is only used if the virtual table 1153 ** implementation indicates that pWhere may match at most one row. 1154 ** 1155 ** The default strategy is to create an ephemeral table that contains 1156 ** for each row to be changed: 1157 ** 1158 ** (A) The original rowid of that row. 1159 ** (B) The revised rowid for the row. 1160 ** (C) The content of every column in the row. 1161 ** 1162 ** Then loop through the contents of this ephemeral table executing a 1163 ** VUpdate for each row. When finished, drop the ephemeral table. 1164 ** 1165 ** The "onepass" strategy does not use an ephemeral table. Instead, it 1166 ** stores the same values (A, B and C above) in a register array and 1167 ** makes a single invocation of VUpdate. 1168 */ 1169 static void updateVirtualTable( 1170 Parse *pParse, /* The parsing context */ 1171 SrcList *pSrc, /* The virtual table to be modified */ 1172 Table *pTab, /* The virtual table */ 1173 ExprList *pChanges, /* The columns to change in the UPDATE statement */ 1174 Expr *pRowid, /* Expression used to recompute the rowid */ 1175 int *aXRef, /* Mapping from columns of pTab to entries in pChanges */ 1176 Expr *pWhere, /* WHERE clause of the UPDATE statement */ 1177 int onError /* ON CONFLICT strategy */ 1178 ){ 1179 Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */ 1180 int ephemTab; /* Table holding the result of the SELECT */ 1181 int i; /* Loop counter */ 1182 sqlite3 *db = pParse->db; /* Database connection */ 1183 const char *pVTab = (const char*)sqlite3GetVTable(db, pTab); 1184 WhereInfo *pWInfo = 0; 1185 int nArg = 2 + pTab->nCol; /* Number of arguments to VUpdate */ 1186 int regArg; /* First register in VUpdate arg array */ 1187 int regRec; /* Register in which to assemble record */ 1188 int regRowid; /* Register for ephem table rowid */ 1189 int iCsr = pSrc->a[0].iCursor; /* Cursor used for virtual table scan */ 1190 int aDummy[2]; /* Unused arg for sqlite3WhereOkOnePass() */ 1191 int eOnePass; /* True to use onepass strategy */ 1192 int addr; /* Address of OP_OpenEphemeral */ 1193 1194 /* Allocate nArg registers in which to gather the arguments for VUpdate. Then 1195 ** create and open the ephemeral table in which the records created from 1196 ** these arguments will be temporarily stored. */ 1197 assert( v ); 1198 ephemTab = pParse->nTab++; 1199 addr= sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, nArg); 1200 regArg = pParse->nMem + 1; 1201 pParse->nMem += nArg; 1202 if( pSrc->nSrc>1 ){ 1203 Index *pPk = 0; 1204 Expr *pRow; 1205 ExprList *pList; 1206 if( HasRowid(pTab) ){ 1207 if( pRowid ){ 1208 pRow = sqlite3ExprDup(db, pRowid, 0); 1209 }else{ 1210 pRow = sqlite3PExpr(pParse, TK_ROW, 0, 0); 1211 } 1212 }else{ 1213 i16 iPk; /* PRIMARY KEY column */ 1214 pPk = sqlite3PrimaryKeyIndex(pTab); 1215 assert( pPk!=0 ); 1216 assert( pPk->nKeyCol==1 ); 1217 iPk = pPk->aiColumn[0]; 1218 if( aXRef[iPk]>=0 ){ 1219 pRow = sqlite3ExprDup(db, pChanges->a[aXRef[iPk]].pExpr, 0); 1220 }else{ 1221 pRow = exprRowColumn(pParse, iPk); 1222 } 1223 } 1224 pList = sqlite3ExprListAppend(pParse, 0, pRow); 1225 1226 for(i=0; i<pTab->nCol; i++){ 1227 if( aXRef[i]>=0 ){ 1228 pList = sqlite3ExprListAppend(pParse, pList, 1229 sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0) 1230 ); 1231 }else{ 1232 pList = sqlite3ExprListAppend(pParse, pList, exprRowColumn(pParse, i)); 1233 } 1234 } 1235 1236 updateFromSelect(pParse, ephemTab, pPk, pList, pSrc, pWhere, 0, 0); 1237 sqlite3ExprListDelete(db, pList); 1238 eOnePass = ONEPASS_OFF; 1239 }else{ 1240 regRec = ++pParse->nMem; 1241 regRowid = ++pParse->nMem; 1242 1243 /* Start scanning the virtual table */ 1244 pWInfo = sqlite3WhereBegin(pParse, pSrc,pWhere,0,0,WHERE_ONEPASS_DESIRED,0); 1245 if( pWInfo==0 ) return; 1246 1247 /* Populate the argument registers. */ 1248 for(i=0; i<pTab->nCol; i++){ 1249 assert( (pTab->aCol[i].colFlags & COLFLAG_GENERATED)==0 ); 1250 if( aXRef[i]>=0 ){ 1251 sqlite3ExprCode(pParse, pChanges->a[aXRef[i]].pExpr, regArg+2+i); 1252 }else{ 1253 sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, i, regArg+2+i); 1254 sqlite3VdbeChangeP5(v, OPFLAG_NOCHNG);/* For sqlite3_vtab_nochange() */ 1255 } 1256 } 1257 if( HasRowid(pTab) ){ 1258 sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg); 1259 if( pRowid ){ 1260 sqlite3ExprCode(pParse, pRowid, regArg+1); 1261 }else{ 1262 sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg+1); 1263 } 1264 }else{ 1265 Index *pPk; /* PRIMARY KEY index */ 1266 i16 iPk; /* PRIMARY KEY column */ 1267 pPk = sqlite3PrimaryKeyIndex(pTab); 1268 assert( pPk!=0 ); 1269 assert( pPk->nKeyCol==1 ); 1270 iPk = pPk->aiColumn[0]; 1271 sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, iPk, regArg); 1272 sqlite3VdbeAddOp2(v, OP_SCopy, regArg+2+iPk, regArg+1); 1273 } 1274 1275 eOnePass = sqlite3WhereOkOnePass(pWInfo, aDummy); 1276 1277 /* There is no ONEPASS_MULTI on virtual tables */ 1278 assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE ); 1279 1280 if( eOnePass ){ 1281 /* If using the onepass strategy, no-op out the OP_OpenEphemeral coded 1282 ** above. */ 1283 sqlite3VdbeChangeToNoop(v, addr); 1284 sqlite3VdbeAddOp1(v, OP_Close, iCsr); 1285 }else{ 1286 /* Create a record from the argument register contents and insert it into 1287 ** the ephemeral table. */ 1288 sqlite3MultiWrite(pParse); 1289 sqlite3VdbeAddOp3(v, OP_MakeRecord, regArg, nArg, regRec); 1290 #if defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_NULL_TRIM) 1291 /* Signal an assert() within OP_MakeRecord that it is allowed to 1292 ** accept no-change records with serial_type 10 */ 1293 sqlite3VdbeChangeP5(v, OPFLAG_NOCHNG_MAGIC); 1294 #endif 1295 sqlite3VdbeAddOp2(v, OP_NewRowid, ephemTab, regRowid); 1296 sqlite3VdbeAddOp3(v, OP_Insert, ephemTab, regRec, regRowid); 1297 } 1298 } 1299 1300 1301 if( eOnePass==ONEPASS_OFF ){ 1302 /* End the virtual table scan */ 1303 if( pSrc->nSrc==1 ){ 1304 sqlite3WhereEnd(pWInfo); 1305 } 1306 1307 /* Begin scannning through the ephemeral table. */ 1308 addr = sqlite3VdbeAddOp1(v, OP_Rewind, ephemTab); VdbeCoverage(v); 1309 1310 /* Extract arguments from the current row of the ephemeral table and 1311 ** invoke the VUpdate method. */ 1312 for(i=0; i<nArg; i++){ 1313 sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i, regArg+i); 1314 } 1315 } 1316 sqlite3VtabMakeWritable(pParse, pTab); 1317 sqlite3VdbeAddOp4(v, OP_VUpdate, 0, nArg, regArg, pVTab, P4_VTAB); 1318 sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError); 1319 sqlite3MayAbort(pParse); 1320 1321 /* End of the ephemeral table scan. Or, if using the onepass strategy, 1322 ** jump to here if the scan visited zero rows. */ 1323 if( eOnePass==ONEPASS_OFF ){ 1324 sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v); 1325 sqlite3VdbeJumpHere(v, addr); 1326 sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0); 1327 }else{ 1328 sqlite3WhereEnd(pWInfo); 1329 } 1330 } 1331 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 1332