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