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 INSERT statements in SQLite. 14 */ 15 #include "sqliteInt.h" 16 17 /* 18 ** Generate code that will 19 ** 20 ** (1) acquire a lock for table pTab then 21 ** (2) open pTab as cursor iCur. 22 ** 23 ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index 24 ** for that table that is actually opened. 25 */ 26 void sqlite3OpenTable( 27 Parse *pParse, /* Generate code into this VDBE */ 28 int iCur, /* The cursor number of the table */ 29 int iDb, /* The database index in sqlite3.aDb[] */ 30 Table *pTab, /* The table to be opened */ 31 int opcode /* OP_OpenRead or OP_OpenWrite */ 32 ){ 33 Vdbe *v; 34 assert( !IsVirtual(pTab) ); 35 v = sqlite3GetVdbe(pParse); 36 assert( opcode==OP_OpenWrite || opcode==OP_OpenRead ); 37 sqlite3TableLock(pParse, iDb, pTab->tnum, 38 (opcode==OP_OpenWrite)?1:0, pTab->zName); 39 if( HasRowid(pTab) ){ 40 sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol); 41 VdbeComment((v, "%s", pTab->zName)); 42 }else{ 43 Index *pPk = sqlite3PrimaryKeyIndex(pTab); 44 assert( pPk!=0 ); 45 assert( pPk->tnum==pTab->tnum ); 46 sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb); 47 sqlite3VdbeSetP4KeyInfo(pParse, pPk); 48 VdbeComment((v, "%s", pTab->zName)); 49 } 50 } 51 52 /* 53 ** Return a pointer to the column affinity string associated with index 54 ** pIdx. A column affinity string has one character for each column in 55 ** the table, according to the affinity of the column: 56 ** 57 ** Character Column affinity 58 ** ------------------------------ 59 ** 'A' BLOB 60 ** 'B' TEXT 61 ** 'C' NUMERIC 62 ** 'D' INTEGER 63 ** 'F' REAL 64 ** 65 ** An extra 'D' is appended to the end of the string to cover the 66 ** rowid that appears as the last column in every index. 67 ** 68 ** Memory for the buffer containing the column index affinity string 69 ** is managed along with the rest of the Index structure. It will be 70 ** released when sqlite3DeleteIndex() is called. 71 */ 72 const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){ 73 if( !pIdx->zColAff ){ 74 /* The first time a column affinity string for a particular index is 75 ** required, it is allocated and populated here. It is then stored as 76 ** a member of the Index structure for subsequent use. 77 ** 78 ** The column affinity string will eventually be deleted by 79 ** sqliteDeleteIndex() when the Index structure itself is cleaned 80 ** up. 81 */ 82 int n; 83 Table *pTab = pIdx->pTable; 84 pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1); 85 if( !pIdx->zColAff ){ 86 db->mallocFailed = 1; 87 return 0; 88 } 89 for(n=0; n<pIdx->nColumn; n++){ 90 i16 x = pIdx->aiColumn[n]; 91 if( x>=0 ){ 92 pIdx->zColAff[n] = pTab->aCol[x].affinity; 93 }else if( x==XN_ROWID ){ 94 pIdx->zColAff[n] = SQLITE_AFF_INTEGER; 95 }else{ 96 char aff; 97 assert( x==XN_EXPR ); 98 assert( pIdx->aColExpr!=0 ); 99 aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr); 100 if( aff==0 ) aff = SQLITE_AFF_BLOB; 101 pIdx->zColAff[n] = aff; 102 } 103 } 104 pIdx->zColAff[n] = 0; 105 } 106 107 return pIdx->zColAff; 108 } 109 110 /* 111 ** Compute the affinity string for table pTab, if it has not already been 112 ** computed. As an optimization, omit trailing SQLITE_AFF_BLOB affinities. 113 ** 114 ** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and 115 ** if iReg>0 then code an OP_Affinity opcode that will set the affinities 116 ** for register iReg and following. Or if affinities exists and iReg==0, 117 ** then just set the P4 operand of the previous opcode (which should be 118 ** an OP_MakeRecord) to the affinity string. 119 ** 120 ** A column affinity string has one character per column: 121 ** 122 ** Character Column affinity 123 ** ------------------------------ 124 ** 'A' BLOB 125 ** 'B' TEXT 126 ** 'C' NUMERIC 127 ** 'D' INTEGER 128 ** 'E' REAL 129 */ 130 void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){ 131 int i; 132 char *zColAff = pTab->zColAff; 133 if( zColAff==0 ){ 134 sqlite3 *db = sqlite3VdbeDb(v); 135 zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1); 136 if( !zColAff ){ 137 db->mallocFailed = 1; 138 return; 139 } 140 141 for(i=0; i<pTab->nCol; i++){ 142 zColAff[i] = pTab->aCol[i].affinity; 143 } 144 do{ 145 zColAff[i--] = 0; 146 }while( i>=0 && zColAff[i]==SQLITE_AFF_BLOB ); 147 pTab->zColAff = zColAff; 148 } 149 i = sqlite3Strlen30(zColAff); 150 if( i ){ 151 if( iReg ){ 152 sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i); 153 }else{ 154 sqlite3VdbeChangeP4(v, -1, zColAff, i); 155 } 156 } 157 } 158 159 /* 160 ** Return non-zero if the table pTab in database iDb or any of its indices 161 ** have been opened at any point in the VDBE program. This is used to see if 162 ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can 163 ** run without using a temporary table for the results of the SELECT. 164 */ 165 static int readsTable(Parse *p, int iDb, Table *pTab){ 166 Vdbe *v = sqlite3GetVdbe(p); 167 int i; 168 int iEnd = sqlite3VdbeCurrentAddr(v); 169 #ifndef SQLITE_OMIT_VIRTUALTABLE 170 VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0; 171 #endif 172 173 for(i=1; i<iEnd; i++){ 174 VdbeOp *pOp = sqlite3VdbeGetOp(v, i); 175 assert( pOp!=0 ); 176 if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){ 177 Index *pIndex; 178 int tnum = pOp->p2; 179 if( tnum==pTab->tnum ){ 180 return 1; 181 } 182 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){ 183 if( tnum==pIndex->tnum ){ 184 return 1; 185 } 186 } 187 } 188 #ifndef SQLITE_OMIT_VIRTUALTABLE 189 if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){ 190 assert( pOp->p4.pVtab!=0 ); 191 assert( pOp->p4type==P4_VTAB ); 192 return 1; 193 } 194 #endif 195 } 196 return 0; 197 } 198 199 #ifndef SQLITE_OMIT_AUTOINCREMENT 200 /* 201 ** Locate or create an AutoincInfo structure associated with table pTab 202 ** which is in database iDb. Return the register number for the register 203 ** that holds the maximum rowid. 204 ** 205 ** There is at most one AutoincInfo structure per table even if the 206 ** same table is autoincremented multiple times due to inserts within 207 ** triggers. A new AutoincInfo structure is created if this is the 208 ** first use of table pTab. On 2nd and subsequent uses, the original 209 ** AutoincInfo structure is used. 210 ** 211 ** Three memory locations are allocated: 212 ** 213 ** (1) Register to hold the name of the pTab table. 214 ** (2) Register to hold the maximum ROWID of pTab. 215 ** (3) Register to hold the rowid in sqlite_sequence of pTab 216 ** 217 ** The 2nd register is the one that is returned. That is all the 218 ** insert routine needs to know about. 219 */ 220 static int autoIncBegin( 221 Parse *pParse, /* Parsing context */ 222 int iDb, /* Index of the database holding pTab */ 223 Table *pTab /* The table we are writing to */ 224 ){ 225 int memId = 0; /* Register holding maximum rowid */ 226 if( pTab->tabFlags & TF_Autoincrement ){ 227 Parse *pToplevel = sqlite3ParseToplevel(pParse); 228 AutoincInfo *pInfo; 229 230 pInfo = pToplevel->pAinc; 231 while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; } 232 if( pInfo==0 ){ 233 pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo)); 234 if( pInfo==0 ) return 0; 235 pInfo->pNext = pToplevel->pAinc; 236 pToplevel->pAinc = pInfo; 237 pInfo->pTab = pTab; 238 pInfo->iDb = iDb; 239 pToplevel->nMem++; /* Register to hold name of table */ 240 pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */ 241 pToplevel->nMem++; /* Rowid in sqlite_sequence */ 242 } 243 memId = pInfo->regCtr; 244 } 245 return memId; 246 } 247 248 /* 249 ** This routine generates code that will initialize all of the 250 ** register used by the autoincrement tracker. 251 */ 252 void sqlite3AutoincrementBegin(Parse *pParse){ 253 AutoincInfo *p; /* Information about an AUTOINCREMENT */ 254 sqlite3 *db = pParse->db; /* The database connection */ 255 Db *pDb; /* Database only autoinc table */ 256 int memId; /* Register holding max rowid */ 257 int addr; /* A VDBE address */ 258 Vdbe *v = pParse->pVdbe; /* VDBE under construction */ 259 260 /* This routine is never called during trigger-generation. It is 261 ** only called from the top-level */ 262 assert( pParse->pTriggerTab==0 ); 263 assert( sqlite3IsToplevel(pParse) ); 264 265 assert( v ); /* We failed long ago if this is not so */ 266 for(p = pParse->pAinc; p; p = p->pNext){ 267 pDb = &db->aDb[p->iDb]; 268 memId = p->regCtr; 269 assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) ); 270 sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead); 271 sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1); 272 addr = sqlite3VdbeCurrentAddr(v); 273 sqlite3VdbeLoadString(v, memId-1, p->pTab->zName); 274 sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9); VdbeCoverage(v); 275 sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId); 276 sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId); VdbeCoverage(v); 277 sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL); 278 sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1); 279 sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId); 280 sqlite3VdbeGoto(v, addr+9); 281 sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2); VdbeCoverage(v); 282 sqlite3VdbeAddOp2(v, OP_Integer, 0, memId); 283 sqlite3VdbeAddOp0(v, OP_Close); 284 } 285 } 286 287 /* 288 ** Update the maximum rowid for an autoincrement calculation. 289 ** 290 ** This routine should be called when the top of the stack holds a 291 ** new rowid that is about to be inserted. If that new rowid is 292 ** larger than the maximum rowid in the memId memory cell, then the 293 ** memory cell is updated. The stack is unchanged. 294 */ 295 static void autoIncStep(Parse *pParse, int memId, int regRowid){ 296 if( memId>0 ){ 297 sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid); 298 } 299 } 300 301 /* 302 ** This routine generates the code needed to write autoincrement 303 ** maximum rowid values back into the sqlite_sequence register. 304 ** Every statement that might do an INSERT into an autoincrement 305 ** table (either directly or through triggers) needs to call this 306 ** routine just before the "exit" code. 307 */ 308 void sqlite3AutoincrementEnd(Parse *pParse){ 309 AutoincInfo *p; 310 Vdbe *v = pParse->pVdbe; 311 sqlite3 *db = pParse->db; 312 313 assert( v ); 314 for(p = pParse->pAinc; p; p = p->pNext){ 315 Db *pDb = &db->aDb[p->iDb]; 316 int addr1; 317 int iRec; 318 int memId = p->regCtr; 319 320 iRec = sqlite3GetTempReg(pParse); 321 assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) ); 322 sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite); 323 addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1); VdbeCoverage(v); 324 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1); 325 sqlite3VdbeJumpHere(v, addr1); 326 sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec); 327 sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1); 328 sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 329 sqlite3VdbeAddOp0(v, OP_Close); 330 sqlite3ReleaseTempReg(pParse, iRec); 331 } 332 } 333 #else 334 /* 335 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines 336 ** above are all no-ops 337 */ 338 # define autoIncBegin(A,B,C) (0) 339 # define autoIncStep(A,B,C) 340 #endif /* SQLITE_OMIT_AUTOINCREMENT */ 341 342 343 /* Forward declaration */ 344 static int xferOptimization( 345 Parse *pParse, /* Parser context */ 346 Table *pDest, /* The table we are inserting into */ 347 Select *pSelect, /* A SELECT statement to use as the data source */ 348 int onError, /* How to handle constraint errors */ 349 int iDbDest /* The database of pDest */ 350 ); 351 352 /* 353 ** This routine is called to handle SQL of the following forms: 354 ** 355 ** insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),... 356 ** insert into TABLE (IDLIST) select 357 ** insert into TABLE (IDLIST) default values 358 ** 359 ** The IDLIST following the table name is always optional. If omitted, 360 ** then a list of all (non-hidden) columns for the table is substituted. 361 ** The IDLIST appears in the pColumn parameter. pColumn is NULL if IDLIST 362 ** is omitted. 363 ** 364 ** For the pSelect parameter holds the values to be inserted for the 365 ** first two forms shown above. A VALUES clause is really just short-hand 366 ** for a SELECT statement that omits the FROM clause and everything else 367 ** that follows. If the pSelect parameter is NULL, that means that the 368 ** DEFAULT VALUES form of the INSERT statement is intended. 369 ** 370 ** The code generated follows one of four templates. For a simple 371 ** insert with data coming from a single-row VALUES clause, the code executes 372 ** once straight down through. Pseudo-code follows (we call this 373 ** the "1st template"): 374 ** 375 ** open write cursor to <table> and its indices 376 ** put VALUES clause expressions into registers 377 ** write the resulting record into <table> 378 ** cleanup 379 ** 380 ** The three remaining templates assume the statement is of the form 381 ** 382 ** INSERT INTO <table> SELECT ... 383 ** 384 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" - 385 ** in other words if the SELECT pulls all columns from a single table 386 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and 387 ** if <table2> and <table1> are distinct tables but have identical 388 ** schemas, including all the same indices, then a special optimization 389 ** is invoked that copies raw records from <table2> over to <table1>. 390 ** See the xferOptimization() function for the implementation of this 391 ** template. This is the 2nd template. 392 ** 393 ** open a write cursor to <table> 394 ** open read cursor on <table2> 395 ** transfer all records in <table2> over to <table> 396 ** close cursors 397 ** foreach index on <table> 398 ** open a write cursor on the <table> index 399 ** open a read cursor on the corresponding <table2> index 400 ** transfer all records from the read to the write cursors 401 ** close cursors 402 ** end foreach 403 ** 404 ** The 3rd template is for when the second template does not apply 405 ** and the SELECT clause does not read from <table> at any time. 406 ** The generated code follows this template: 407 ** 408 ** X <- A 409 ** goto B 410 ** A: setup for the SELECT 411 ** loop over the rows in the SELECT 412 ** load values into registers R..R+n 413 ** yield X 414 ** end loop 415 ** cleanup after the SELECT 416 ** end-coroutine X 417 ** B: open write cursor to <table> and its indices 418 ** C: yield X, at EOF goto D 419 ** insert the select result into <table> from R..R+n 420 ** goto C 421 ** D: cleanup 422 ** 423 ** The 4th template is used if the insert statement takes its 424 ** values from a SELECT but the data is being inserted into a table 425 ** that is also read as part of the SELECT. In the third form, 426 ** we have to use an intermediate table to store the results of 427 ** the select. The template is like this: 428 ** 429 ** X <- A 430 ** goto B 431 ** A: setup for the SELECT 432 ** loop over the tables in the SELECT 433 ** load value into register R..R+n 434 ** yield X 435 ** end loop 436 ** cleanup after the SELECT 437 ** end co-routine R 438 ** B: open temp table 439 ** L: yield X, at EOF goto M 440 ** insert row from R..R+n into temp table 441 ** goto L 442 ** M: open write cursor to <table> and its indices 443 ** rewind temp table 444 ** C: loop over rows of intermediate table 445 ** transfer values form intermediate table into <table> 446 ** end loop 447 ** D: cleanup 448 */ 449 void sqlite3Insert( 450 Parse *pParse, /* Parser context */ 451 SrcList *pTabList, /* Name of table into which we are inserting */ 452 Select *pSelect, /* A SELECT statement to use as the data source */ 453 IdList *pColumn, /* Column names corresponding to IDLIST. */ 454 int onError /* How to handle constraint errors */ 455 ){ 456 sqlite3 *db; /* The main database structure */ 457 Table *pTab; /* The table to insert into. aka TABLE */ 458 char *zTab; /* Name of the table into which we are inserting */ 459 const char *zDb; /* Name of the database holding this table */ 460 int i, j, idx; /* Loop counters */ 461 Vdbe *v; /* Generate code into this virtual machine */ 462 Index *pIdx; /* For looping over indices of the table */ 463 int nColumn; /* Number of columns in the data */ 464 int nHidden = 0; /* Number of hidden columns if TABLE is virtual */ 465 int iDataCur = 0; /* VDBE cursor that is the main data repository */ 466 int iIdxCur = 0; /* First index cursor */ 467 int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */ 468 int endOfLoop; /* Label for the end of the insertion loop */ 469 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */ 470 int addrInsTop = 0; /* Jump to label "D" */ 471 int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */ 472 SelectDest dest; /* Destination for SELECT on rhs of INSERT */ 473 int iDb; /* Index of database holding TABLE */ 474 Db *pDb; /* The database containing table being inserted into */ 475 u8 useTempTable = 0; /* Store SELECT results in intermediate table */ 476 u8 appendFlag = 0; /* True if the insert is likely to be an append */ 477 u8 withoutRowid; /* 0 for normal table. 1 for WITHOUT ROWID table */ 478 u8 bIdListInOrder; /* True if IDLIST is in table order */ 479 ExprList *pList = 0; /* List of VALUES() to be inserted */ 480 481 /* Register allocations */ 482 int regFromSelect = 0;/* Base register for data coming from SELECT */ 483 int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */ 484 int regRowCount = 0; /* Memory cell used for the row counter */ 485 int regIns; /* Block of regs holding rowid+data being inserted */ 486 int regRowid; /* registers holding insert rowid */ 487 int regData; /* register holding first column to insert */ 488 int *aRegIdx = 0; /* One register allocated to each index */ 489 490 #ifndef SQLITE_OMIT_TRIGGER 491 int isView; /* True if attempting to insert into a view */ 492 Trigger *pTrigger; /* List of triggers on pTab, if required */ 493 int tmask; /* Mask of trigger times */ 494 #endif 495 496 db = pParse->db; 497 memset(&dest, 0, sizeof(dest)); 498 if( pParse->nErr || db->mallocFailed ){ 499 goto insert_cleanup; 500 } 501 502 /* If the Select object is really just a simple VALUES() list with a 503 ** single row (the common case) then keep that one row of values 504 ** and discard the other (unused) parts of the pSelect object 505 */ 506 if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){ 507 pList = pSelect->pEList; 508 pSelect->pEList = 0; 509 sqlite3SelectDelete(db, pSelect); 510 pSelect = 0; 511 } 512 513 /* Locate the table into which we will be inserting new information. 514 */ 515 assert( pTabList->nSrc==1 ); 516 zTab = pTabList->a[0].zName; 517 if( NEVER(zTab==0) ) goto insert_cleanup; 518 pTab = sqlite3SrcListLookup(pParse, pTabList); 519 if( pTab==0 ){ 520 goto insert_cleanup; 521 } 522 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 523 assert( iDb<db->nDb ); 524 pDb = &db->aDb[iDb]; 525 zDb = pDb->zName; 526 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){ 527 goto insert_cleanup; 528 } 529 withoutRowid = !HasRowid(pTab); 530 531 /* Figure out if we have any triggers and if the table being 532 ** inserted into is a view 533 */ 534 #ifndef SQLITE_OMIT_TRIGGER 535 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask); 536 isView = pTab->pSelect!=0; 537 #else 538 # define pTrigger 0 539 # define tmask 0 540 # define isView 0 541 #endif 542 #ifdef SQLITE_OMIT_VIEW 543 # undef isView 544 # define isView 0 545 #endif 546 assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) ); 547 548 /* If pTab is really a view, make sure it has been initialized. 549 ** ViewGetColumnNames() is a no-op if pTab is not a view. 550 */ 551 if( sqlite3ViewGetColumnNames(pParse, pTab) ){ 552 goto insert_cleanup; 553 } 554 555 /* Cannot insert into a read-only table. 556 */ 557 if( sqlite3IsReadOnly(pParse, pTab, tmask) ){ 558 goto insert_cleanup; 559 } 560 561 /* Allocate a VDBE 562 */ 563 v = sqlite3GetVdbe(pParse); 564 if( v==0 ) goto insert_cleanup; 565 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v); 566 sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb); 567 568 #ifndef SQLITE_OMIT_XFER_OPT 569 /* If the statement is of the form 570 ** 571 ** INSERT INTO <table1> SELECT * FROM <table2>; 572 ** 573 ** Then special optimizations can be applied that make the transfer 574 ** very fast and which reduce fragmentation of indices. 575 ** 576 ** This is the 2nd template. 577 */ 578 if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){ 579 assert( !pTrigger ); 580 assert( pList==0 ); 581 goto insert_end; 582 } 583 #endif /* SQLITE_OMIT_XFER_OPT */ 584 585 /* If this is an AUTOINCREMENT table, look up the sequence number in the 586 ** sqlite_sequence table and store it in memory cell regAutoinc. 587 */ 588 regAutoinc = autoIncBegin(pParse, iDb, pTab); 589 590 /* Allocate registers for holding the rowid of the new row, 591 ** the content of the new row, and the assembled row record. 592 */ 593 regRowid = regIns = pParse->nMem+1; 594 pParse->nMem += pTab->nCol + 1; 595 if( IsVirtual(pTab) ){ 596 regRowid++; 597 pParse->nMem++; 598 } 599 regData = regRowid+1; 600 601 /* If the INSERT statement included an IDLIST term, then make sure 602 ** all elements of the IDLIST really are columns of the table and 603 ** remember the column indices. 604 ** 605 ** If the table has an INTEGER PRIMARY KEY column and that column 606 ** is named in the IDLIST, then record in the ipkColumn variable 607 ** the index into IDLIST of the primary key column. ipkColumn is 608 ** the index of the primary key as it appears in IDLIST, not as 609 ** is appears in the original table. (The index of the INTEGER 610 ** PRIMARY KEY in the original table is pTab->iPKey.) 611 */ 612 bIdListInOrder = (pTab->tabFlags & TF_OOOHidden)==0; 613 if( pColumn ){ 614 for(i=0; i<pColumn->nId; i++){ 615 pColumn->a[i].idx = -1; 616 } 617 for(i=0; i<pColumn->nId; i++){ 618 for(j=0; j<pTab->nCol; j++){ 619 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){ 620 pColumn->a[i].idx = j; 621 if( i!=j ) bIdListInOrder = 0; 622 if( j==pTab->iPKey ){ 623 ipkColumn = i; assert( !withoutRowid ); 624 } 625 break; 626 } 627 } 628 if( j>=pTab->nCol ){ 629 if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){ 630 ipkColumn = i; 631 bIdListInOrder = 0; 632 }else{ 633 sqlite3ErrorMsg(pParse, "table %S has no column named %s", 634 pTabList, 0, pColumn->a[i].zName); 635 pParse->checkSchema = 1; 636 goto insert_cleanup; 637 } 638 } 639 } 640 } 641 642 /* Figure out how many columns of data are supplied. If the data 643 ** is coming from a SELECT statement, then generate a co-routine that 644 ** produces a single row of the SELECT on each invocation. The 645 ** co-routine is the common header to the 3rd and 4th templates. 646 */ 647 if( pSelect ){ 648 /* Data is coming from a SELECT or from a multi-row VALUES clause. 649 ** Generate a co-routine to run the SELECT. */ 650 int regYield; /* Register holding co-routine entry-point */ 651 int addrTop; /* Top of the co-routine */ 652 int rc; /* Result code */ 653 654 regYield = ++pParse->nMem; 655 addrTop = sqlite3VdbeCurrentAddr(v) + 1; 656 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop); 657 sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield); 658 dest.iSdst = bIdListInOrder ? regData : 0; 659 dest.nSdst = pTab->nCol; 660 rc = sqlite3Select(pParse, pSelect, &dest); 661 regFromSelect = dest.iSdst; 662 if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup; 663 sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield); 664 sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */ 665 assert( pSelect->pEList ); 666 nColumn = pSelect->pEList->nExpr; 667 668 /* Set useTempTable to TRUE if the result of the SELECT statement 669 ** should be written into a temporary table (template 4). Set to 670 ** FALSE if each output row of the SELECT can be written directly into 671 ** the destination table (template 3). 672 ** 673 ** A temp table must be used if the table being updated is also one 674 ** of the tables being read by the SELECT statement. Also use a 675 ** temp table in the case of row triggers. 676 */ 677 if( pTrigger || readsTable(pParse, iDb, pTab) ){ 678 useTempTable = 1; 679 } 680 681 if( useTempTable ){ 682 /* Invoke the coroutine to extract information from the SELECT 683 ** and add it to a transient table srcTab. The code generated 684 ** here is from the 4th template: 685 ** 686 ** B: open temp table 687 ** L: yield X, goto M at EOF 688 ** insert row from R..R+n into temp table 689 ** goto L 690 ** M: ... 691 */ 692 int regRec; /* Register to hold packed record */ 693 int regTempRowid; /* Register to hold temp table ROWID */ 694 int addrL; /* Label "L" */ 695 696 srcTab = pParse->nTab++; 697 regRec = sqlite3GetTempReg(pParse); 698 regTempRowid = sqlite3GetTempReg(pParse); 699 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn); 700 addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v); 701 sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec); 702 sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid); 703 sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid); 704 sqlite3VdbeGoto(v, addrL); 705 sqlite3VdbeJumpHere(v, addrL); 706 sqlite3ReleaseTempReg(pParse, regRec); 707 sqlite3ReleaseTempReg(pParse, regTempRowid); 708 } 709 }else{ 710 /* This is the case if the data for the INSERT is coming from a 711 ** single-row VALUES clause 712 */ 713 NameContext sNC; 714 memset(&sNC, 0, sizeof(sNC)); 715 sNC.pParse = pParse; 716 srcTab = -1; 717 assert( useTempTable==0 ); 718 if( pList ){ 719 nColumn = pList->nExpr; 720 if( sqlite3ResolveExprListNames(&sNC, pList) ){ 721 goto insert_cleanup; 722 } 723 }else{ 724 nColumn = 0; 725 } 726 } 727 728 /* If there is no IDLIST term but the table has an integer primary 729 ** key, the set the ipkColumn variable to the integer primary key 730 ** column index in the original table definition. 731 */ 732 if( pColumn==0 && nColumn>0 ){ 733 ipkColumn = pTab->iPKey; 734 } 735 736 /* Make sure the number of columns in the source data matches the number 737 ** of columns to be inserted into the table. 738 */ 739 for(i=0; i<pTab->nCol; i++){ 740 nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0); 741 } 742 if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){ 743 sqlite3ErrorMsg(pParse, 744 "table %S has %d columns but %d values were supplied", 745 pTabList, 0, pTab->nCol-nHidden, nColumn); 746 goto insert_cleanup; 747 } 748 if( pColumn!=0 && nColumn!=pColumn->nId ){ 749 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId); 750 goto insert_cleanup; 751 } 752 753 /* Initialize the count of rows to be inserted 754 */ 755 if( db->flags & SQLITE_CountRows ){ 756 regRowCount = ++pParse->nMem; 757 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount); 758 } 759 760 /* If this is not a view, open the table and and all indices */ 761 if( !isView ){ 762 int nIdx; 763 nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0, 764 &iDataCur, &iIdxCur); 765 aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1)); 766 if( aRegIdx==0 ){ 767 goto insert_cleanup; 768 } 769 for(i=0; i<nIdx; i++){ 770 aRegIdx[i] = ++pParse->nMem; 771 } 772 } 773 774 /* This is the top of the main insertion loop */ 775 if( useTempTable ){ 776 /* This block codes the top of loop only. The complete loop is the 777 ** following pseudocode (template 4): 778 ** 779 ** rewind temp table, if empty goto D 780 ** C: loop over rows of intermediate table 781 ** transfer values form intermediate table into <table> 782 ** end loop 783 ** D: ... 784 */ 785 addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v); 786 addrCont = sqlite3VdbeCurrentAddr(v); 787 }else if( pSelect ){ 788 /* This block codes the top of loop only. The complete loop is the 789 ** following pseudocode (template 3): 790 ** 791 ** C: yield X, at EOF goto D 792 ** insert the select result into <table> from R..R+n 793 ** goto C 794 ** D: ... 795 */ 796 addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); 797 VdbeCoverage(v); 798 } 799 800 /* Run the BEFORE and INSTEAD OF triggers, if there are any 801 */ 802 endOfLoop = sqlite3VdbeMakeLabel(v); 803 if( tmask & TRIGGER_BEFORE ){ 804 int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1); 805 806 /* build the NEW.* reference row. Note that if there is an INTEGER 807 ** PRIMARY KEY into which a NULL is being inserted, that NULL will be 808 ** translated into a unique ID for the row. But on a BEFORE trigger, 809 ** we do not know what the unique ID will be (because the insert has 810 ** not happened yet) so we substitute a rowid of -1 811 */ 812 if( ipkColumn<0 ){ 813 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols); 814 }else{ 815 int addr1; 816 assert( !withoutRowid ); 817 if( useTempTable ){ 818 sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols); 819 }else{ 820 assert( pSelect==0 ); /* Otherwise useTempTable is true */ 821 sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols); 822 } 823 addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v); 824 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols); 825 sqlite3VdbeJumpHere(v, addr1); 826 sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v); 827 } 828 829 /* Cannot have triggers on a virtual table. If it were possible, 830 ** this block would have to account for hidden column. 831 */ 832 assert( !IsVirtual(pTab) ); 833 834 /* Create the new column data 835 */ 836 for(i=j=0; i<pTab->nCol; i++){ 837 if( pColumn ){ 838 for(j=0; j<pColumn->nId; j++){ 839 if( pColumn->a[j].idx==i ) break; 840 } 841 } 842 if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) 843 || (pColumn==0 && IsOrdinaryHiddenColumn(&pTab->aCol[i])) ){ 844 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1); 845 }else if( useTempTable ){ 846 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1); 847 }else{ 848 assert( pSelect==0 ); /* Otherwise useTempTable is true */ 849 sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1); 850 } 851 if( pColumn==0 && !IsOrdinaryHiddenColumn(&pTab->aCol[i]) ) j++; 852 } 853 854 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger, 855 ** do not attempt any conversions before assembling the record. 856 ** If this is a real table, attempt conversions as required by the 857 ** table column affinities. 858 */ 859 if( !isView ){ 860 sqlite3TableAffinity(v, pTab, regCols+1); 861 } 862 863 /* Fire BEFORE or INSTEAD OF triggers */ 864 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, 865 pTab, regCols-pTab->nCol-1, onError, endOfLoop); 866 867 sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1); 868 } 869 870 /* Compute the content of the next row to insert into a range of 871 ** registers beginning at regIns. 872 */ 873 if( !isView ){ 874 if( IsVirtual(pTab) ){ 875 /* The row that the VUpdate opcode will delete: none */ 876 sqlite3VdbeAddOp2(v, OP_Null, 0, regIns); 877 } 878 if( ipkColumn>=0 ){ 879 if( useTempTable ){ 880 sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid); 881 }else if( pSelect ){ 882 sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid); 883 }else{ 884 VdbeOp *pOp; 885 sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid); 886 pOp = sqlite3VdbeGetOp(v, -1); 887 if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){ 888 appendFlag = 1; 889 pOp->opcode = OP_NewRowid; 890 pOp->p1 = iDataCur; 891 pOp->p2 = regRowid; 892 pOp->p3 = regAutoinc; 893 } 894 } 895 /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid 896 ** to generate a unique primary key value. 897 */ 898 if( !appendFlag ){ 899 int addr1; 900 if( !IsVirtual(pTab) ){ 901 addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v); 902 sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc); 903 sqlite3VdbeJumpHere(v, addr1); 904 }else{ 905 addr1 = sqlite3VdbeCurrentAddr(v); 906 sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v); 907 } 908 sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v); 909 } 910 }else if( IsVirtual(pTab) || withoutRowid ){ 911 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid); 912 }else{ 913 sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc); 914 appendFlag = 1; 915 } 916 autoIncStep(pParse, regAutoinc, regRowid); 917 918 /* Compute data for all columns of the new entry, beginning 919 ** with the first column. 920 */ 921 nHidden = 0; 922 for(i=0; i<pTab->nCol; i++){ 923 int iRegStore = regRowid+1+i; 924 if( i==pTab->iPKey ){ 925 /* The value of the INTEGER PRIMARY KEY column is always a NULL. 926 ** Whenever this column is read, the rowid will be substituted 927 ** in its place. Hence, fill this column with a NULL to avoid 928 ** taking up data space with information that will never be used. 929 ** As there may be shallow copies of this value, make it a soft-NULL */ 930 sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore); 931 continue; 932 } 933 if( pColumn==0 ){ 934 if( IsHiddenColumn(&pTab->aCol[i]) ){ 935 j = -1; 936 nHidden++; 937 }else{ 938 j = i - nHidden; 939 } 940 }else{ 941 for(j=0; j<pColumn->nId; j++){ 942 if( pColumn->a[j].idx==i ) break; 943 } 944 } 945 if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){ 946 sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore); 947 }else if( useTempTable ){ 948 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); 949 }else if( pSelect ){ 950 if( regFromSelect!=regData ){ 951 sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore); 952 } 953 }else{ 954 sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore); 955 } 956 } 957 958 /* Generate code to check constraints and generate index keys and 959 ** do the insertion. 960 */ 961 #ifndef SQLITE_OMIT_VIRTUALTABLE 962 if( IsVirtual(pTab) ){ 963 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab); 964 sqlite3VtabMakeWritable(pParse, pTab); 965 sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB); 966 sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError); 967 sqlite3MayAbort(pParse); 968 }else 969 #endif 970 { 971 int isReplace; /* Set to true if constraints may cause a replace */ 972 sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur, 973 regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace 974 ); 975 sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0); 976 sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur, 977 regIns, aRegIdx, 0, appendFlag, isReplace==0); 978 } 979 } 980 981 /* Update the count of rows that are inserted 982 */ 983 if( (db->flags & SQLITE_CountRows)!=0 ){ 984 sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1); 985 } 986 987 if( pTrigger ){ 988 /* Code AFTER triggers */ 989 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, 990 pTab, regData-2-pTab->nCol, onError, endOfLoop); 991 } 992 993 /* The bottom of the main insertion loop, if the data source 994 ** is a SELECT statement. 995 */ 996 sqlite3VdbeResolveLabel(v, endOfLoop); 997 if( useTempTable ){ 998 sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v); 999 sqlite3VdbeJumpHere(v, addrInsTop); 1000 sqlite3VdbeAddOp1(v, OP_Close, srcTab); 1001 }else if( pSelect ){ 1002 sqlite3VdbeGoto(v, addrCont); 1003 sqlite3VdbeJumpHere(v, addrInsTop); 1004 } 1005 1006 if( !IsVirtual(pTab) && !isView ){ 1007 /* Close all tables opened */ 1008 if( iDataCur<iIdxCur ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur); 1009 for(idx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){ 1010 sqlite3VdbeAddOp1(v, OP_Close, idx+iIdxCur); 1011 } 1012 } 1013 1014 insert_end: 1015 /* Update the sqlite_sequence table by storing the content of the 1016 ** maximum rowid counter values recorded while inserting into 1017 ** autoincrement tables. 1018 */ 1019 if( pParse->nested==0 && pParse->pTriggerTab==0 ){ 1020 sqlite3AutoincrementEnd(pParse); 1021 } 1022 1023 /* 1024 ** Return the number of rows inserted. If this routine is 1025 ** generating code because of a call to sqlite3NestedParse(), do not 1026 ** invoke the callback function. 1027 */ 1028 if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){ 1029 sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1); 1030 sqlite3VdbeSetNumCols(v, 1); 1031 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC); 1032 } 1033 1034 insert_cleanup: 1035 sqlite3SrcListDelete(db, pTabList); 1036 sqlite3ExprListDelete(db, pList); 1037 sqlite3SelectDelete(db, pSelect); 1038 sqlite3IdListDelete(db, pColumn); 1039 sqlite3DbFree(db, aRegIdx); 1040 } 1041 1042 /* Make sure "isView" and other macros defined above are undefined. Otherwise 1043 ** they may interfere with compilation of other functions in this file 1044 ** (or in another file, if this file becomes part of the amalgamation). */ 1045 #ifdef isView 1046 #undef isView 1047 #endif 1048 #ifdef pTrigger 1049 #undef pTrigger 1050 #endif 1051 #ifdef tmask 1052 #undef tmask 1053 #endif 1054 1055 /* 1056 ** Generate code to do constraint checks prior to an INSERT or an UPDATE 1057 ** on table pTab. 1058 ** 1059 ** The regNewData parameter is the first register in a range that contains 1060 ** the data to be inserted or the data after the update. There will be 1061 ** pTab->nCol+1 registers in this range. The first register (the one 1062 ** that regNewData points to) will contain the new rowid, or NULL in the 1063 ** case of a WITHOUT ROWID table. The second register in the range will 1064 ** contain the content of the first table column. The third register will 1065 ** contain the content of the second table column. And so forth. 1066 ** 1067 ** The regOldData parameter is similar to regNewData except that it contains 1068 ** the data prior to an UPDATE rather than afterwards. regOldData is zero 1069 ** for an INSERT. This routine can distinguish between UPDATE and INSERT by 1070 ** checking regOldData for zero. 1071 ** 1072 ** For an UPDATE, the pkChng boolean is true if the true primary key (the 1073 ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table) 1074 ** might be modified by the UPDATE. If pkChng is false, then the key of 1075 ** the iDataCur content table is guaranteed to be unchanged by the UPDATE. 1076 ** 1077 ** For an INSERT, the pkChng boolean indicates whether or not the rowid 1078 ** was explicitly specified as part of the INSERT statement. If pkChng 1079 ** is zero, it means that the either rowid is computed automatically or 1080 ** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT, 1081 ** pkChng will only be true if the INSERT statement provides an integer 1082 ** value for either the rowid column or its INTEGER PRIMARY KEY alias. 1083 ** 1084 ** The code generated by this routine will store new index entries into 1085 ** registers identified by aRegIdx[]. No index entry is created for 1086 ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is 1087 ** the same as the order of indices on the linked list of indices 1088 ** at pTab->pIndex. 1089 ** 1090 ** The caller must have already opened writeable cursors on the main 1091 ** table and all applicable indices (that is to say, all indices for which 1092 ** aRegIdx[] is not zero). iDataCur is the cursor for the main table when 1093 ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY 1094 ** index when operating on a WITHOUT ROWID table. iIdxCur is the cursor 1095 ** for the first index in the pTab->pIndex list. Cursors for other indices 1096 ** are at iIdxCur+N for the N-th element of the pTab->pIndex list. 1097 ** 1098 ** This routine also generates code to check constraints. NOT NULL, 1099 ** CHECK, and UNIQUE constraints are all checked. If a constraint fails, 1100 ** then the appropriate action is performed. There are five possible 1101 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE. 1102 ** 1103 ** Constraint type Action What Happens 1104 ** --------------- ---------- ---------------------------------------- 1105 ** any ROLLBACK The current transaction is rolled back and 1106 ** sqlite3_step() returns immediately with a 1107 ** return code of SQLITE_CONSTRAINT. 1108 ** 1109 ** any ABORT Back out changes from the current command 1110 ** only (do not do a complete rollback) then 1111 ** cause sqlite3_step() to return immediately 1112 ** with SQLITE_CONSTRAINT. 1113 ** 1114 ** any FAIL Sqlite3_step() returns immediately with a 1115 ** return code of SQLITE_CONSTRAINT. The 1116 ** transaction is not rolled back and any 1117 ** changes to prior rows are retained. 1118 ** 1119 ** any IGNORE The attempt in insert or update the current 1120 ** row is skipped, without throwing an error. 1121 ** Processing continues with the next row. 1122 ** (There is an immediate jump to ignoreDest.) 1123 ** 1124 ** NOT NULL REPLACE The NULL value is replace by the default 1125 ** value for that column. If the default value 1126 ** is NULL, the action is the same as ABORT. 1127 ** 1128 ** UNIQUE REPLACE The other row that conflicts with the row 1129 ** being inserted is removed. 1130 ** 1131 ** CHECK REPLACE Illegal. The results in an exception. 1132 ** 1133 ** Which action to take is determined by the overrideError parameter. 1134 ** Or if overrideError==OE_Default, then the pParse->onError parameter 1135 ** is used. Or if pParse->onError==OE_Default then the onError value 1136 ** for the constraint is used. 1137 */ 1138 void sqlite3GenerateConstraintChecks( 1139 Parse *pParse, /* The parser context */ 1140 Table *pTab, /* The table being inserted or updated */ 1141 int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */ 1142 int iDataCur, /* Canonical data cursor (main table or PK index) */ 1143 int iIdxCur, /* First index cursor */ 1144 int regNewData, /* First register in a range holding values to insert */ 1145 int regOldData, /* Previous content. 0 for INSERTs */ 1146 u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */ 1147 u8 overrideError, /* Override onError to this if not OE_Default */ 1148 int ignoreDest, /* Jump to this label on an OE_Ignore resolution */ 1149 int *pbMayReplace /* OUT: Set to true if constraint may cause a replace */ 1150 ){ 1151 Vdbe *v; /* VDBE under constrution */ 1152 Index *pIdx; /* Pointer to one of the indices */ 1153 Index *pPk = 0; /* The PRIMARY KEY index */ 1154 sqlite3 *db; /* Database connection */ 1155 int i; /* loop counter */ 1156 int ix; /* Index loop counter */ 1157 int nCol; /* Number of columns */ 1158 int onError; /* Conflict resolution strategy */ 1159 int addr1; /* Address of jump instruction */ 1160 int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */ 1161 int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */ 1162 int ipkTop = 0; /* Top of the rowid change constraint check */ 1163 int ipkBottom = 0; /* Bottom of the rowid change constraint check */ 1164 u8 isUpdate; /* True if this is an UPDATE operation */ 1165 u8 bAffinityDone = 0; /* True if the OP_Affinity operation has been run */ 1166 int regRowid = -1; /* Register holding ROWID value */ 1167 1168 isUpdate = regOldData!=0; 1169 db = pParse->db; 1170 v = sqlite3GetVdbe(pParse); 1171 assert( v!=0 ); 1172 assert( pTab->pSelect==0 ); /* This table is not a VIEW */ 1173 nCol = pTab->nCol; 1174 1175 /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for 1176 ** normal rowid tables. nPkField is the number of key fields in the 1177 ** pPk index or 1 for a rowid table. In other words, nPkField is the 1178 ** number of fields in the true primary key of the table. */ 1179 if( HasRowid(pTab) ){ 1180 pPk = 0; 1181 nPkField = 1; 1182 }else{ 1183 pPk = sqlite3PrimaryKeyIndex(pTab); 1184 nPkField = pPk->nKeyCol; 1185 } 1186 1187 /* Record that this module has started */ 1188 VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)", 1189 iDataCur, iIdxCur, regNewData, regOldData, pkChng)); 1190 1191 /* Test all NOT NULL constraints. 1192 */ 1193 for(i=0; i<nCol; i++){ 1194 if( i==pTab->iPKey ){ 1195 continue; 1196 } 1197 onError = pTab->aCol[i].notNull; 1198 if( onError==OE_None ) continue; 1199 if( overrideError!=OE_Default ){ 1200 onError = overrideError; 1201 }else if( onError==OE_Default ){ 1202 onError = OE_Abort; 1203 } 1204 if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){ 1205 onError = OE_Abort; 1206 } 1207 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail 1208 || onError==OE_Ignore || onError==OE_Replace ); 1209 switch( onError ){ 1210 case OE_Abort: 1211 sqlite3MayAbort(pParse); 1212 /* Fall through */ 1213 case OE_Rollback: 1214 case OE_Fail: { 1215 char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName, 1216 pTab->aCol[i].zName); 1217 sqlite3VdbeAddOp4(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError, 1218 regNewData+1+i, zMsg, P4_DYNAMIC); 1219 sqlite3VdbeChangeP5(v, P5_ConstraintNotNull); 1220 VdbeCoverage(v); 1221 break; 1222 } 1223 case OE_Ignore: { 1224 sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest); 1225 VdbeCoverage(v); 1226 break; 1227 } 1228 default: { 1229 assert( onError==OE_Replace ); 1230 addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i); 1231 VdbeCoverage(v); 1232 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i); 1233 sqlite3VdbeJumpHere(v, addr1); 1234 break; 1235 } 1236 } 1237 } 1238 1239 /* Test all CHECK constraints 1240 */ 1241 #ifndef SQLITE_OMIT_CHECK 1242 if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){ 1243 ExprList *pCheck = pTab->pCheck; 1244 pParse->ckBase = regNewData+1; 1245 onError = overrideError!=OE_Default ? overrideError : OE_Abort; 1246 for(i=0; i<pCheck->nExpr; i++){ 1247 int allOk = sqlite3VdbeMakeLabel(v); 1248 sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL); 1249 if( onError==OE_Ignore ){ 1250 sqlite3VdbeGoto(v, ignoreDest); 1251 }else{ 1252 char *zName = pCheck->a[i].zName; 1253 if( zName==0 ) zName = pTab->zName; 1254 if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */ 1255 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK, 1256 onError, zName, P4_TRANSIENT, 1257 P5_ConstraintCheck); 1258 } 1259 sqlite3VdbeResolveLabel(v, allOk); 1260 } 1261 } 1262 #endif /* !defined(SQLITE_OMIT_CHECK) */ 1263 1264 /* If rowid is changing, make sure the new rowid does not previously 1265 ** exist in the table. 1266 */ 1267 if( pkChng && pPk==0 ){ 1268 int addrRowidOk = sqlite3VdbeMakeLabel(v); 1269 1270 /* Figure out what action to take in case of a rowid collision */ 1271 onError = pTab->keyConf; 1272 if( overrideError!=OE_Default ){ 1273 onError = overrideError; 1274 }else if( onError==OE_Default ){ 1275 onError = OE_Abort; 1276 } 1277 1278 if( isUpdate ){ 1279 /* pkChng!=0 does not mean that the rowid has change, only that 1280 ** it might have changed. Skip the conflict logic below if the rowid 1281 ** is unchanged. */ 1282 sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData); 1283 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); 1284 VdbeCoverage(v); 1285 } 1286 1287 /* If the response to a rowid conflict is REPLACE but the response 1288 ** to some other UNIQUE constraint is FAIL or IGNORE, then we need 1289 ** to defer the running of the rowid conflict checking until after 1290 ** the UNIQUE constraints have run. 1291 */ 1292 if( onError==OE_Replace && overrideError!=OE_Replace ){ 1293 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 1294 if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){ 1295 ipkTop = sqlite3VdbeAddOp0(v, OP_Goto); 1296 break; 1297 } 1298 } 1299 } 1300 1301 /* Check to see if the new rowid already exists in the table. Skip 1302 ** the following conflict logic if it does not. */ 1303 sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData); 1304 VdbeCoverage(v); 1305 1306 /* Generate code that deals with a rowid collision */ 1307 switch( onError ){ 1308 default: { 1309 onError = OE_Abort; 1310 /* Fall thru into the next case */ 1311 } 1312 case OE_Rollback: 1313 case OE_Abort: 1314 case OE_Fail: { 1315 sqlite3RowidConstraint(pParse, onError, pTab); 1316 break; 1317 } 1318 case OE_Replace: { 1319 /* If there are DELETE triggers on this table and the 1320 ** recursive-triggers flag is set, call GenerateRowDelete() to 1321 ** remove the conflicting row from the table. This will fire 1322 ** the triggers and remove both the table and index b-tree entries. 1323 ** 1324 ** Otherwise, if there are no triggers or the recursive-triggers 1325 ** flag is not set, but the table has one or more indexes, call 1326 ** GenerateRowIndexDelete(). This removes the index b-tree entries 1327 ** only. The table b-tree entry will be replaced by the new entry 1328 ** when it is inserted. 1329 ** 1330 ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called, 1331 ** also invoke MultiWrite() to indicate that this VDBE may require 1332 ** statement rollback (if the statement is aborted after the delete 1333 ** takes place). Earlier versions called sqlite3MultiWrite() regardless, 1334 ** but being more selective here allows statements like: 1335 ** 1336 ** REPLACE INTO t(rowid) VALUES($newrowid) 1337 ** 1338 ** to run without a statement journal if there are no indexes on the 1339 ** table. 1340 */ 1341 Trigger *pTrigger = 0; 1342 if( db->flags&SQLITE_RecTriggers ){ 1343 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0); 1344 } 1345 if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){ 1346 sqlite3MultiWrite(pParse); 1347 sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur, 1348 regNewData, 1, 0, OE_Replace, 1349 ONEPASS_SINGLE, -1); 1350 }else{ 1351 if( pTab->pIndex ){ 1352 sqlite3MultiWrite(pParse); 1353 sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1); 1354 } 1355 } 1356 seenReplace = 1; 1357 break; 1358 } 1359 case OE_Ignore: { 1360 /*assert( seenReplace==0 );*/ 1361 sqlite3VdbeGoto(v, ignoreDest); 1362 break; 1363 } 1364 } 1365 sqlite3VdbeResolveLabel(v, addrRowidOk); 1366 if( ipkTop ){ 1367 ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto); 1368 sqlite3VdbeJumpHere(v, ipkTop); 1369 } 1370 } 1371 1372 /* Test all UNIQUE constraints by creating entries for each UNIQUE 1373 ** index and making sure that duplicate entries do not already exist. 1374 ** Compute the revised record entries for indices as we go. 1375 ** 1376 ** This loop also handles the case of the PRIMARY KEY index for a 1377 ** WITHOUT ROWID table. 1378 */ 1379 for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){ 1380 int regIdx; /* Range of registers hold conent for pIdx */ 1381 int regR; /* Range of registers holding conflicting PK */ 1382 int iThisCur; /* Cursor for this UNIQUE index */ 1383 int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */ 1384 1385 if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */ 1386 if( bAffinityDone==0 ){ 1387 sqlite3TableAffinity(v, pTab, regNewData+1); 1388 bAffinityDone = 1; 1389 } 1390 iThisCur = iIdxCur+ix; 1391 addrUniqueOk = sqlite3VdbeMakeLabel(v); 1392 1393 /* Skip partial indices for which the WHERE clause is not true */ 1394 if( pIdx->pPartIdxWhere ){ 1395 sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]); 1396 pParse->ckBase = regNewData+1; 1397 sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk, 1398 SQLITE_JUMPIFNULL); 1399 pParse->ckBase = 0; 1400 } 1401 1402 /* Create a record for this index entry as it should appear after 1403 ** the insert or update. Store that record in the aRegIdx[ix] register 1404 */ 1405 regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn); 1406 for(i=0; i<pIdx->nColumn; i++){ 1407 int iField = pIdx->aiColumn[i]; 1408 int x; 1409 if( iField==XN_EXPR ){ 1410 pParse->ckBase = regNewData+1; 1411 sqlite3ExprCode(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i); 1412 pParse->ckBase = 0; 1413 VdbeComment((v, "%s column %d", pIdx->zName, i)); 1414 }else{ 1415 if( iField==XN_ROWID || iField==pTab->iPKey ){ 1416 if( regRowid==regIdx+i ) continue; /* ROWID already in regIdx+i */ 1417 x = regNewData; 1418 regRowid = pIdx->pPartIdxWhere ? -1 : regIdx+i; 1419 }else{ 1420 x = iField + regNewData + 1; 1421 } 1422 sqlite3VdbeAddOp2(v, iField<0 ? OP_IntCopy : OP_SCopy, x, regIdx+i); 1423 VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName)); 1424 } 1425 } 1426 sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]); 1427 VdbeComment((v, "for %s", pIdx->zName)); 1428 sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn); 1429 1430 /* In an UPDATE operation, if this index is the PRIMARY KEY index 1431 ** of a WITHOUT ROWID table and there has been no change the 1432 ** primary key, then no collision is possible. The collision detection 1433 ** logic below can all be skipped. */ 1434 if( isUpdate && pPk==pIdx && pkChng==0 ){ 1435 sqlite3VdbeResolveLabel(v, addrUniqueOk); 1436 continue; 1437 } 1438 1439 /* Find out what action to take in case there is a uniqueness conflict */ 1440 onError = pIdx->onError; 1441 if( onError==OE_None ){ 1442 sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn); 1443 sqlite3VdbeResolveLabel(v, addrUniqueOk); 1444 continue; /* pIdx is not a UNIQUE index */ 1445 } 1446 if( overrideError!=OE_Default ){ 1447 onError = overrideError; 1448 }else if( onError==OE_Default ){ 1449 onError = OE_Abort; 1450 } 1451 1452 /* Check to see if the new index entry will be unique */ 1453 sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk, 1454 regIdx, pIdx->nKeyCol); VdbeCoverage(v); 1455 1456 /* Generate code to handle collisions */ 1457 regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField); 1458 if( isUpdate || onError==OE_Replace ){ 1459 if( HasRowid(pTab) ){ 1460 sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR); 1461 /* Conflict only if the rowid of the existing index entry 1462 ** is different from old-rowid */ 1463 if( isUpdate ){ 1464 sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData); 1465 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); 1466 VdbeCoverage(v); 1467 } 1468 }else{ 1469 int x; 1470 /* Extract the PRIMARY KEY from the end of the index entry and 1471 ** store it in registers regR..regR+nPk-1 */ 1472 if( pIdx!=pPk ){ 1473 for(i=0; i<pPk->nKeyCol; i++){ 1474 assert( pPk->aiColumn[i]>=0 ); 1475 x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]); 1476 sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i); 1477 VdbeComment((v, "%s.%s", pTab->zName, 1478 pTab->aCol[pPk->aiColumn[i]].zName)); 1479 } 1480 } 1481 if( isUpdate ){ 1482 /* If currently processing the PRIMARY KEY of a WITHOUT ROWID 1483 ** table, only conflict if the new PRIMARY KEY values are actually 1484 ** different from the old. 1485 ** 1486 ** For a UNIQUE index, only conflict if the PRIMARY KEY values 1487 ** of the matched index row are different from the original PRIMARY 1488 ** KEY values of this row before the update. */ 1489 int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol; 1490 int op = OP_Ne; 1491 int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR); 1492 1493 for(i=0; i<pPk->nKeyCol; i++){ 1494 char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]); 1495 x = pPk->aiColumn[i]; 1496 assert( x>=0 ); 1497 if( i==(pPk->nKeyCol-1) ){ 1498 addrJump = addrUniqueOk; 1499 op = OP_Eq; 1500 } 1501 sqlite3VdbeAddOp4(v, op, 1502 regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ 1503 ); 1504 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); 1505 VdbeCoverageIf(v, op==OP_Eq); 1506 VdbeCoverageIf(v, op==OP_Ne); 1507 } 1508 } 1509 } 1510 } 1511 1512 /* Generate code that executes if the new index entry is not unique */ 1513 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail 1514 || onError==OE_Ignore || onError==OE_Replace ); 1515 switch( onError ){ 1516 case OE_Rollback: 1517 case OE_Abort: 1518 case OE_Fail: { 1519 sqlite3UniqueConstraint(pParse, onError, pIdx); 1520 break; 1521 } 1522 case OE_Ignore: { 1523 sqlite3VdbeGoto(v, ignoreDest); 1524 break; 1525 } 1526 default: { 1527 Trigger *pTrigger = 0; 1528 assert( onError==OE_Replace ); 1529 sqlite3MultiWrite(pParse); 1530 if( db->flags&SQLITE_RecTriggers ){ 1531 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0); 1532 } 1533 sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur, 1534 regR, nPkField, 0, OE_Replace, 1535 (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), -1); 1536 seenReplace = 1; 1537 break; 1538 } 1539 } 1540 sqlite3VdbeResolveLabel(v, addrUniqueOk); 1541 sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn); 1542 if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField); 1543 } 1544 if( ipkTop ){ 1545 sqlite3VdbeGoto(v, ipkTop+1); 1546 sqlite3VdbeJumpHere(v, ipkBottom); 1547 } 1548 1549 *pbMayReplace = seenReplace; 1550 VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace)); 1551 } 1552 1553 /* 1554 ** This routine generates code to finish the INSERT or UPDATE operation 1555 ** that was started by a prior call to sqlite3GenerateConstraintChecks. 1556 ** A consecutive range of registers starting at regNewData contains the 1557 ** rowid and the content to be inserted. 1558 ** 1559 ** The arguments to this routine should be the same as the first six 1560 ** arguments to sqlite3GenerateConstraintChecks. 1561 */ 1562 void sqlite3CompleteInsertion( 1563 Parse *pParse, /* The parser context */ 1564 Table *pTab, /* the table into which we are inserting */ 1565 int iDataCur, /* Cursor of the canonical data source */ 1566 int iIdxCur, /* First index cursor */ 1567 int regNewData, /* Range of content */ 1568 int *aRegIdx, /* Register used by each index. 0 for unused indices */ 1569 int isUpdate, /* True for UPDATE, False for INSERT */ 1570 int appendBias, /* True if this is likely to be an append */ 1571 int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */ 1572 ){ 1573 Vdbe *v; /* Prepared statements under construction */ 1574 Index *pIdx; /* An index being inserted or updated */ 1575 u8 pik_flags; /* flag values passed to the btree insert */ 1576 int regData; /* Content registers (after the rowid) */ 1577 int regRec; /* Register holding assembled record for the table */ 1578 int i; /* Loop counter */ 1579 u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */ 1580 1581 v = sqlite3GetVdbe(pParse); 1582 assert( v!=0 ); 1583 assert( pTab->pSelect==0 ); /* This table is not a VIEW */ 1584 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ 1585 if( aRegIdx[i]==0 ) continue; 1586 bAffinityDone = 1; 1587 if( pIdx->pPartIdxWhere ){ 1588 sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2); 1589 VdbeCoverage(v); 1590 } 1591 sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i]); 1592 pik_flags = 0; 1593 if( useSeekResult ) pik_flags = OPFLAG_USESEEKRESULT; 1594 if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){ 1595 assert( pParse->nested==0 ); 1596 pik_flags |= OPFLAG_NCHANGE; 1597 } 1598 if( pik_flags ) sqlite3VdbeChangeP5(v, pik_flags); 1599 } 1600 if( !HasRowid(pTab) ) return; 1601 regData = regNewData + 1; 1602 regRec = sqlite3GetTempReg(pParse); 1603 sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec); 1604 if( !bAffinityDone ) sqlite3TableAffinity(v, pTab, 0); 1605 sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol); 1606 if( pParse->nested ){ 1607 pik_flags = 0; 1608 }else{ 1609 pik_flags = OPFLAG_NCHANGE; 1610 pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID); 1611 } 1612 if( appendBias ){ 1613 pik_flags |= OPFLAG_APPEND; 1614 } 1615 if( useSeekResult ){ 1616 pik_flags |= OPFLAG_USESEEKRESULT; 1617 } 1618 sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData); 1619 if( !pParse->nested ){ 1620 sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT); 1621 } 1622 sqlite3VdbeChangeP5(v, pik_flags); 1623 } 1624 1625 /* 1626 ** Allocate cursors for the pTab table and all its indices and generate 1627 ** code to open and initialized those cursors. 1628 ** 1629 ** The cursor for the object that contains the complete data (normally 1630 ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT 1631 ** ROWID table) is returned in *piDataCur. The first index cursor is 1632 ** returned in *piIdxCur. The number of indices is returned. 1633 ** 1634 ** Use iBase as the first cursor (either the *piDataCur for rowid tables 1635 ** or the first index for WITHOUT ROWID tables) if it is non-negative. 1636 ** If iBase is negative, then allocate the next available cursor. 1637 ** 1638 ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur. 1639 ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range 1640 ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the 1641 ** pTab->pIndex list. 1642 ** 1643 ** If pTab is a virtual table, then this routine is a no-op and the 1644 ** *piDataCur and *piIdxCur values are left uninitialized. 1645 */ 1646 int sqlite3OpenTableAndIndices( 1647 Parse *pParse, /* Parsing context */ 1648 Table *pTab, /* Table to be opened */ 1649 int op, /* OP_OpenRead or OP_OpenWrite */ 1650 u8 p5, /* P5 value for OP_Open* instructions */ 1651 int iBase, /* Use this for the table cursor, if there is one */ 1652 u8 *aToOpen, /* If not NULL: boolean for each table and index */ 1653 int *piDataCur, /* Write the database source cursor number here */ 1654 int *piIdxCur /* Write the first index cursor number here */ 1655 ){ 1656 int i; 1657 int iDb; 1658 int iDataCur; 1659 Index *pIdx; 1660 Vdbe *v; 1661 1662 assert( op==OP_OpenRead || op==OP_OpenWrite ); 1663 assert( op==OP_OpenWrite || p5==0 ); 1664 if( IsVirtual(pTab) ){ 1665 /* This routine is a no-op for virtual tables. Leave the output 1666 ** variables *piDataCur and *piIdxCur uninitialized so that valgrind 1667 ** can detect if they are used by mistake in the caller. */ 1668 return 0; 1669 } 1670 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 1671 v = sqlite3GetVdbe(pParse); 1672 assert( v!=0 ); 1673 if( iBase<0 ) iBase = pParse->nTab; 1674 iDataCur = iBase++; 1675 if( piDataCur ) *piDataCur = iDataCur; 1676 if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){ 1677 sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op); 1678 }else{ 1679 sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName); 1680 } 1681 if( piIdxCur ) *piIdxCur = iBase; 1682 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ 1683 int iIdxCur = iBase++; 1684 assert( pIdx->pSchema==pTab->pSchema ); 1685 if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) && piDataCur ){ 1686 *piDataCur = iIdxCur; 1687 } 1688 if( aToOpen==0 || aToOpen[i+1] ){ 1689 sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb); 1690 sqlite3VdbeSetP4KeyInfo(pParse, pIdx); 1691 sqlite3VdbeChangeP5(v, p5); 1692 VdbeComment((v, "%s", pIdx->zName)); 1693 } 1694 } 1695 if( iBase>pParse->nTab ) pParse->nTab = iBase; 1696 return i; 1697 } 1698 1699 1700 #ifdef SQLITE_TEST 1701 /* 1702 ** The following global variable is incremented whenever the 1703 ** transfer optimization is used. This is used for testing 1704 ** purposes only - to make sure the transfer optimization really 1705 ** is happening when it is supposed to. 1706 */ 1707 int sqlite3_xferopt_count; 1708 #endif /* SQLITE_TEST */ 1709 1710 1711 #ifndef SQLITE_OMIT_XFER_OPT 1712 /* 1713 ** Check to collation names to see if they are compatible. 1714 */ 1715 static int xferCompatibleCollation(const char *z1, const char *z2){ 1716 if( z1==0 ){ 1717 return z2==0; 1718 } 1719 if( z2==0 ){ 1720 return 0; 1721 } 1722 return sqlite3StrICmp(z1, z2)==0; 1723 } 1724 1725 1726 /* 1727 ** Check to see if index pSrc is compatible as a source of data 1728 ** for index pDest in an insert transfer optimization. The rules 1729 ** for a compatible index: 1730 ** 1731 ** * The index is over the same set of columns 1732 ** * The same DESC and ASC markings occurs on all columns 1733 ** * The same onError processing (OE_Abort, OE_Ignore, etc) 1734 ** * The same collating sequence on each column 1735 ** * The index has the exact same WHERE clause 1736 */ 1737 static int xferCompatibleIndex(Index *pDest, Index *pSrc){ 1738 int i; 1739 assert( pDest && pSrc ); 1740 assert( pDest->pTable!=pSrc->pTable ); 1741 if( pDest->nKeyCol!=pSrc->nKeyCol ){ 1742 return 0; /* Different number of columns */ 1743 } 1744 if( pDest->onError!=pSrc->onError ){ 1745 return 0; /* Different conflict resolution strategies */ 1746 } 1747 for(i=0; i<pSrc->nKeyCol; i++){ 1748 if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){ 1749 return 0; /* Different columns indexed */ 1750 } 1751 if( pSrc->aiColumn[i]==XN_EXPR ){ 1752 assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 ); 1753 if( sqlite3ExprCompare(pSrc->aColExpr->a[i].pExpr, 1754 pDest->aColExpr->a[i].pExpr, -1)!=0 ){ 1755 return 0; /* Different expressions in the index */ 1756 } 1757 } 1758 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){ 1759 return 0; /* Different sort orders */ 1760 } 1761 if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){ 1762 return 0; /* Different collating sequences */ 1763 } 1764 } 1765 if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){ 1766 return 0; /* Different WHERE clauses */ 1767 } 1768 1769 /* If no test above fails then the indices must be compatible */ 1770 return 1; 1771 } 1772 1773 /* 1774 ** Attempt the transfer optimization on INSERTs of the form 1775 ** 1776 ** INSERT INTO tab1 SELECT * FROM tab2; 1777 ** 1778 ** The xfer optimization transfers raw records from tab2 over to tab1. 1779 ** Columns are not decoded and reassembled, which greatly improves 1780 ** performance. Raw index records are transferred in the same way. 1781 ** 1782 ** The xfer optimization is only attempted if tab1 and tab2 are compatible. 1783 ** There are lots of rules for determining compatibility - see comments 1784 ** embedded in the code for details. 1785 ** 1786 ** This routine returns TRUE if the optimization is guaranteed to be used. 1787 ** Sometimes the xfer optimization will only work if the destination table 1788 ** is empty - a factor that can only be determined at run-time. In that 1789 ** case, this routine generates code for the xfer optimization but also 1790 ** does a test to see if the destination table is empty and jumps over the 1791 ** xfer optimization code if the test fails. In that case, this routine 1792 ** returns FALSE so that the caller will know to go ahead and generate 1793 ** an unoptimized transfer. This routine also returns FALSE if there 1794 ** is no chance that the xfer optimization can be applied. 1795 ** 1796 ** This optimization is particularly useful at making VACUUM run faster. 1797 */ 1798 static int xferOptimization( 1799 Parse *pParse, /* Parser context */ 1800 Table *pDest, /* The table we are inserting into */ 1801 Select *pSelect, /* A SELECT statement to use as the data source */ 1802 int onError, /* How to handle constraint errors */ 1803 int iDbDest /* The database of pDest */ 1804 ){ 1805 sqlite3 *db = pParse->db; 1806 ExprList *pEList; /* The result set of the SELECT */ 1807 Table *pSrc; /* The table in the FROM clause of SELECT */ 1808 Index *pSrcIdx, *pDestIdx; /* Source and destination indices */ 1809 struct SrcList_item *pItem; /* An element of pSelect->pSrc */ 1810 int i; /* Loop counter */ 1811 int iDbSrc; /* The database of pSrc */ 1812 int iSrc, iDest; /* Cursors from source and destination */ 1813 int addr1, addr2; /* Loop addresses */ 1814 int emptyDestTest = 0; /* Address of test for empty pDest */ 1815 int emptySrcTest = 0; /* Address of test for empty pSrc */ 1816 Vdbe *v; /* The VDBE we are building */ 1817 int regAutoinc; /* Memory register used by AUTOINC */ 1818 int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */ 1819 int regData, regRowid; /* Registers holding data and rowid */ 1820 1821 if( pSelect==0 ){ 1822 return 0; /* Must be of the form INSERT INTO ... SELECT ... */ 1823 } 1824 if( pParse->pWith || pSelect->pWith ){ 1825 /* Do not attempt to process this query if there are an WITH clauses 1826 ** attached to it. Proceeding may generate a false "no such table: xxx" 1827 ** error if pSelect reads from a CTE named "xxx". */ 1828 return 0; 1829 } 1830 if( sqlite3TriggerList(pParse, pDest) ){ 1831 return 0; /* tab1 must not have triggers */ 1832 } 1833 #ifndef SQLITE_OMIT_VIRTUALTABLE 1834 if( pDest->tabFlags & TF_Virtual ){ 1835 return 0; /* tab1 must not be a virtual table */ 1836 } 1837 #endif 1838 if( onError==OE_Default ){ 1839 if( pDest->iPKey>=0 ) onError = pDest->keyConf; 1840 if( onError==OE_Default ) onError = OE_Abort; 1841 } 1842 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */ 1843 if( pSelect->pSrc->nSrc!=1 ){ 1844 return 0; /* FROM clause must have exactly one term */ 1845 } 1846 if( pSelect->pSrc->a[0].pSelect ){ 1847 return 0; /* FROM clause cannot contain a subquery */ 1848 } 1849 if( pSelect->pWhere ){ 1850 return 0; /* SELECT may not have a WHERE clause */ 1851 } 1852 if( pSelect->pOrderBy ){ 1853 return 0; /* SELECT may not have an ORDER BY clause */ 1854 } 1855 /* Do not need to test for a HAVING clause. If HAVING is present but 1856 ** there is no ORDER BY, we will get an error. */ 1857 if( pSelect->pGroupBy ){ 1858 return 0; /* SELECT may not have a GROUP BY clause */ 1859 } 1860 if( pSelect->pLimit ){ 1861 return 0; /* SELECT may not have a LIMIT clause */ 1862 } 1863 assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */ 1864 if( pSelect->pPrior ){ 1865 return 0; /* SELECT may not be a compound query */ 1866 } 1867 if( pSelect->selFlags & SF_Distinct ){ 1868 return 0; /* SELECT may not be DISTINCT */ 1869 } 1870 pEList = pSelect->pEList; 1871 assert( pEList!=0 ); 1872 if( pEList->nExpr!=1 ){ 1873 return 0; /* The result set must have exactly one column */ 1874 } 1875 assert( pEList->a[0].pExpr ); 1876 if( pEList->a[0].pExpr->op!=TK_ASTERISK ){ 1877 return 0; /* The result set must be the special operator "*" */ 1878 } 1879 1880 /* At this point we have established that the statement is of the 1881 ** correct syntactic form to participate in this optimization. Now 1882 ** we have to check the semantics. 1883 */ 1884 pItem = pSelect->pSrc->a; 1885 pSrc = sqlite3LocateTableItem(pParse, 0, pItem); 1886 if( pSrc==0 ){ 1887 return 0; /* FROM clause does not contain a real table */ 1888 } 1889 if( pSrc==pDest ){ 1890 return 0; /* tab1 and tab2 may not be the same table */ 1891 } 1892 if( HasRowid(pDest)!=HasRowid(pSrc) ){ 1893 return 0; /* source and destination must both be WITHOUT ROWID or not */ 1894 } 1895 #ifndef SQLITE_OMIT_VIRTUALTABLE 1896 if( pSrc->tabFlags & TF_Virtual ){ 1897 return 0; /* tab2 must not be a virtual table */ 1898 } 1899 #endif 1900 if( pSrc->pSelect ){ 1901 return 0; /* tab2 may not be a view */ 1902 } 1903 if( pDest->nCol!=pSrc->nCol ){ 1904 return 0; /* Number of columns must be the same in tab1 and tab2 */ 1905 } 1906 if( pDest->iPKey!=pSrc->iPKey ){ 1907 return 0; /* Both tables must have the same INTEGER PRIMARY KEY */ 1908 } 1909 for(i=0; i<pDest->nCol; i++){ 1910 Column *pDestCol = &pDest->aCol[i]; 1911 Column *pSrcCol = &pSrc->aCol[i]; 1912 #ifdef SQLITE_ENABLE_HIDDEN_COLUMNS 1913 if( (db->flags & SQLITE_Vacuum)==0 1914 && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN 1915 ){ 1916 return 0; /* Neither table may have __hidden__ columns */ 1917 } 1918 #endif 1919 if( pDestCol->affinity!=pSrcCol->affinity ){ 1920 return 0; /* Affinity must be the same on all columns */ 1921 } 1922 if( !xferCompatibleCollation(pDestCol->zColl, pSrcCol->zColl) ){ 1923 return 0; /* Collating sequence must be the same on all columns */ 1924 } 1925 if( pDestCol->notNull && !pSrcCol->notNull ){ 1926 return 0; /* tab2 must be NOT NULL if tab1 is */ 1927 } 1928 /* Default values for second and subsequent columns need to match. */ 1929 if( i>0 1930 && ((pDestCol->zDflt==0)!=(pSrcCol->zDflt==0) 1931 || (pDestCol->zDflt && strcmp(pDestCol->zDflt, pSrcCol->zDflt)!=0)) 1932 ){ 1933 return 0; /* Default values must be the same for all columns */ 1934 } 1935 } 1936 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ 1937 if( IsUniqueIndex(pDestIdx) ){ 1938 destHasUniqueIdx = 1; 1939 } 1940 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){ 1941 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; 1942 } 1943 if( pSrcIdx==0 ){ 1944 return 0; /* pDestIdx has no corresponding index in pSrc */ 1945 } 1946 } 1947 #ifndef SQLITE_OMIT_CHECK 1948 if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){ 1949 return 0; /* Tables have different CHECK constraints. Ticket #2252 */ 1950 } 1951 #endif 1952 #ifndef SQLITE_OMIT_FOREIGN_KEY 1953 /* Disallow the transfer optimization if the destination table constains 1954 ** any foreign key constraints. This is more restrictive than necessary. 1955 ** But the main beneficiary of the transfer optimization is the VACUUM 1956 ** command, and the VACUUM command disables foreign key constraints. So 1957 ** the extra complication to make this rule less restrictive is probably 1958 ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e] 1959 */ 1960 if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){ 1961 return 0; 1962 } 1963 #endif 1964 if( (db->flags & SQLITE_CountRows)!=0 ){ 1965 return 0; /* xfer opt does not play well with PRAGMA count_changes */ 1966 } 1967 1968 /* If we get this far, it means that the xfer optimization is at 1969 ** least a possibility, though it might only work if the destination 1970 ** table (tab1) is initially empty. 1971 */ 1972 #ifdef SQLITE_TEST 1973 sqlite3_xferopt_count++; 1974 #endif 1975 iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema); 1976 v = sqlite3GetVdbe(pParse); 1977 sqlite3CodeVerifySchema(pParse, iDbSrc); 1978 iSrc = pParse->nTab++; 1979 iDest = pParse->nTab++; 1980 regAutoinc = autoIncBegin(pParse, iDbDest, pDest); 1981 regData = sqlite3GetTempReg(pParse); 1982 regRowid = sqlite3GetTempReg(pParse); 1983 sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite); 1984 assert( HasRowid(pDest) || destHasUniqueIdx ); 1985 if( (db->flags & SQLITE_Vacuum)==0 && ( 1986 (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */ 1987 || destHasUniqueIdx /* (2) */ 1988 || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */ 1989 )){ 1990 /* In some circumstances, we are able to run the xfer optimization 1991 ** only if the destination table is initially empty. Unless the 1992 ** SQLITE_Vacuum flag is set, this block generates code to make 1993 ** that determination. If SQLITE_Vacuum is set, then the destination 1994 ** table is always empty. 1995 ** 1996 ** Conditions under which the destination must be empty: 1997 ** 1998 ** (1) There is no INTEGER PRIMARY KEY but there are indices. 1999 ** (If the destination is not initially empty, the rowid fields 2000 ** of index entries might need to change.) 2001 ** 2002 ** (2) The destination has a unique index. (The xfer optimization 2003 ** is unable to test uniqueness.) 2004 ** 2005 ** (3) onError is something other than OE_Abort and OE_Rollback. 2006 */ 2007 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v); 2008 emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto); 2009 sqlite3VdbeJumpHere(v, addr1); 2010 } 2011 if( HasRowid(pSrc) ){ 2012 sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead); 2013 emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v); 2014 if( pDest->iPKey>=0 ){ 2015 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); 2016 addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid); 2017 VdbeCoverage(v); 2018 sqlite3RowidConstraint(pParse, onError, pDest); 2019 sqlite3VdbeJumpHere(v, addr2); 2020 autoIncStep(pParse, regAutoinc, regRowid); 2021 }else if( pDest->pIndex==0 ){ 2022 addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid); 2023 }else{ 2024 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); 2025 assert( (pDest->tabFlags & TF_Autoincrement)==0 ); 2026 } 2027 sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData); 2028 sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid); 2029 sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND); 2030 sqlite3VdbeChangeP4(v, -1, pDest->zName, 0); 2031 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v); 2032 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); 2033 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); 2034 }else{ 2035 sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName); 2036 sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName); 2037 } 2038 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ 2039 u8 idxInsFlags = 0; 2040 for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){ 2041 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; 2042 } 2043 assert( pSrcIdx ); 2044 sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc); 2045 sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx); 2046 VdbeComment((v, "%s", pSrcIdx->zName)); 2047 sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest); 2048 sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx); 2049 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR); 2050 VdbeComment((v, "%s", pDestIdx->zName)); 2051 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v); 2052 sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData); 2053 if( db->flags & SQLITE_Vacuum ){ 2054 /* This INSERT command is part of a VACUUM operation, which guarantees 2055 ** that the destination table is empty. If all indexed columns use 2056 ** collation sequence BINARY, then it can also be assumed that the 2057 ** index will be populated by inserting keys in strictly sorted 2058 ** order. In this case, instead of seeking within the b-tree as part 2059 ** of every OP_IdxInsert opcode, an OP_Last is added before the 2060 ** OP_IdxInsert to seek to the point within the b-tree where each key 2061 ** should be inserted. This is faster. 2062 ** 2063 ** If any of the indexed columns use a collation sequence other than 2064 ** BINARY, this optimization is disabled. This is because the user 2065 ** might change the definition of a collation sequence and then run 2066 ** a VACUUM command. In that case keys may not be written in strictly 2067 ** sorted order. */ 2068 for(i=0; i<pSrcIdx->nColumn; i++){ 2069 char *zColl = pSrcIdx->azColl[i]; 2070 assert( zColl!=0 ); 2071 if( sqlite3_stricmp("BINARY", zColl) ) break; 2072 } 2073 if( i==pSrcIdx->nColumn ){ 2074 idxInsFlags = OPFLAG_USESEEKRESULT; 2075 sqlite3VdbeAddOp3(v, OP_Last, iDest, 0, -1); 2076 } 2077 } 2078 if( !HasRowid(pSrc) && pDestIdx->idxType==2 ){ 2079 idxInsFlags |= OPFLAG_NCHANGE; 2080 } 2081 sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1); 2082 sqlite3VdbeChangeP5(v, idxInsFlags); 2083 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v); 2084 sqlite3VdbeJumpHere(v, addr1); 2085 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); 2086 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); 2087 } 2088 if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest); 2089 sqlite3ReleaseTempReg(pParse, regRowid); 2090 sqlite3ReleaseTempReg(pParse, regData); 2091 if( emptyDestTest ){ 2092 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0); 2093 sqlite3VdbeJumpHere(v, emptyDestTest); 2094 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); 2095 return 0; 2096 }else{ 2097 return 1; 2098 } 2099 } 2100 #endif /* SQLITE_OMIT_XFER_OPT */ 2101