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 j1; 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 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1); VdbeCoverage(v); 324 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1); 325 sqlite3VdbeJumpHere(v, j1); 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 if( IsVirtual(pTab) ){ 740 for(i=0; i<pTab->nCol; i++){ 741 nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0); 742 } 743 } 744 if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){ 745 sqlite3ErrorMsg(pParse, 746 "table %S has %d columns but %d values were supplied", 747 pTabList, 0, pTab->nCol-nHidden, nColumn); 748 goto insert_cleanup; 749 } 750 if( pColumn!=0 && nColumn!=pColumn->nId ){ 751 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId); 752 goto insert_cleanup; 753 } 754 755 /* Initialize the count of rows to be inserted 756 */ 757 if( db->flags & SQLITE_CountRows ){ 758 regRowCount = ++pParse->nMem; 759 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount); 760 } 761 762 /* If this is not a view, open the table and and all indices */ 763 if( !isView ){ 764 int nIdx; 765 nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, -1, 0, 766 &iDataCur, &iIdxCur); 767 aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1)); 768 if( aRegIdx==0 ){ 769 goto insert_cleanup; 770 } 771 for(i=0; i<nIdx; i++){ 772 aRegIdx[i] = ++pParse->nMem; 773 } 774 } 775 776 /* This is the top of the main insertion loop */ 777 if( useTempTable ){ 778 /* This block codes the top of loop only. The complete loop is the 779 ** following pseudocode (template 4): 780 ** 781 ** rewind temp table, if empty goto D 782 ** C: loop over rows of intermediate table 783 ** transfer values form intermediate table into <table> 784 ** end loop 785 ** D: ... 786 */ 787 addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v); 788 addrCont = sqlite3VdbeCurrentAddr(v); 789 }else if( pSelect ){ 790 /* This block codes the top of loop only. The complete loop is the 791 ** following pseudocode (template 3): 792 ** 793 ** C: yield X, at EOF goto D 794 ** insert the select result into <table> from R..R+n 795 ** goto C 796 ** D: ... 797 */ 798 addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); 799 VdbeCoverage(v); 800 } 801 802 /* Run the BEFORE and INSTEAD OF triggers, if there are any 803 */ 804 endOfLoop = sqlite3VdbeMakeLabel(v); 805 if( tmask & TRIGGER_BEFORE ){ 806 int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1); 807 808 /* build the NEW.* reference row. Note that if there is an INTEGER 809 ** PRIMARY KEY into which a NULL is being inserted, that NULL will be 810 ** translated into a unique ID for the row. But on a BEFORE trigger, 811 ** we do not know what the unique ID will be (because the insert has 812 ** not happened yet) so we substitute a rowid of -1 813 */ 814 if( ipkColumn<0 ){ 815 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols); 816 }else{ 817 int j1; 818 assert( !withoutRowid ); 819 if( useTempTable ){ 820 sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols); 821 }else{ 822 assert( pSelect==0 ); /* Otherwise useTempTable is true */ 823 sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols); 824 } 825 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v); 826 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols); 827 sqlite3VdbeJumpHere(v, j1); 828 sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v); 829 } 830 831 /* Cannot have triggers on a virtual table. If it were possible, 832 ** this block would have to account for hidden column. 833 */ 834 assert( !IsVirtual(pTab) ); 835 836 /* Create the new column data 837 */ 838 for(i=0; i<pTab->nCol; i++){ 839 if( pColumn==0 ){ 840 j = i; 841 }else{ 842 for(j=0; j<pColumn->nId; j++){ 843 if( pColumn->a[j].idx==i ) break; 844 } 845 } 846 if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){ 847 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1); 848 }else if( useTempTable ){ 849 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1); 850 }else{ 851 assert( pSelect==0 ); /* Otherwise useTempTable is true */ 852 sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1); 853 } 854 } 855 856 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger, 857 ** do not attempt any conversions before assembling the record. 858 ** If this is a real table, attempt conversions as required by the 859 ** table column affinities. 860 */ 861 if( !isView ){ 862 sqlite3TableAffinity(v, pTab, regCols+1); 863 } 864 865 /* Fire BEFORE or INSTEAD OF triggers */ 866 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, 867 pTab, regCols-pTab->nCol-1, onError, endOfLoop); 868 869 sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1); 870 } 871 872 /* Compute the content of the next row to insert into a range of 873 ** registers beginning at regIns. 874 */ 875 if( !isView ){ 876 if( IsVirtual(pTab) ){ 877 /* The row that the VUpdate opcode will delete: none */ 878 sqlite3VdbeAddOp2(v, OP_Null, 0, regIns); 879 } 880 if( ipkColumn>=0 ){ 881 if( useTempTable ){ 882 sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid); 883 }else if( pSelect ){ 884 sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid); 885 }else{ 886 VdbeOp *pOp; 887 sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid); 888 pOp = sqlite3VdbeGetOp(v, -1); 889 if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){ 890 appendFlag = 1; 891 pOp->opcode = OP_NewRowid; 892 pOp->p1 = iDataCur; 893 pOp->p2 = regRowid; 894 pOp->p3 = regAutoinc; 895 } 896 } 897 /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid 898 ** to generate a unique primary key value. 899 */ 900 if( !appendFlag ){ 901 int j1; 902 if( !IsVirtual(pTab) ){ 903 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v); 904 sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc); 905 sqlite3VdbeJumpHere(v, j1); 906 }else{ 907 j1 = sqlite3VdbeCurrentAddr(v); 908 sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2); VdbeCoverage(v); 909 } 910 sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v); 911 } 912 }else if( IsVirtual(pTab) || withoutRowid ){ 913 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid); 914 }else{ 915 sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc); 916 appendFlag = 1; 917 } 918 autoIncStep(pParse, regAutoinc, regRowid); 919 920 /* Compute data for all columns of the new entry, beginning 921 ** with the first column. 922 */ 923 nHidden = 0; 924 for(i=0; i<pTab->nCol; i++){ 925 int iRegStore = regRowid+1+i; 926 if( i==pTab->iPKey ){ 927 /* The value of the INTEGER PRIMARY KEY column is always a NULL. 928 ** Whenever this column is read, the rowid will be substituted 929 ** in its place. Hence, fill this column with a NULL to avoid 930 ** taking up data space with information that will never be used. 931 ** As there may be shallow copies of this value, make it a soft-NULL */ 932 sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore); 933 continue; 934 } 935 if( pColumn==0 ){ 936 if( IsHiddenColumn(&pTab->aCol[i]) ){ 937 assert( IsVirtual(pTab) ); 938 j = -1; 939 nHidden++; 940 }else{ 941 j = i - nHidden; 942 } 943 }else{ 944 for(j=0; j<pColumn->nId; j++){ 945 if( pColumn->a[j].idx==i ) break; 946 } 947 } 948 if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){ 949 sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore); 950 }else if( useTempTable ){ 951 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); 952 }else if( pSelect ){ 953 if( regFromSelect!=regData ){ 954 sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore); 955 } 956 }else{ 957 sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore); 958 } 959 } 960 961 /* Generate code to check constraints and generate index keys and 962 ** do the insertion. 963 */ 964 #ifndef SQLITE_OMIT_VIRTUALTABLE 965 if( IsVirtual(pTab) ){ 966 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab); 967 sqlite3VtabMakeWritable(pParse, pTab); 968 sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB); 969 sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError); 970 sqlite3MayAbort(pParse); 971 }else 972 #endif 973 { 974 int isReplace; /* Set to true if constraints may cause a replace */ 975 sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur, 976 regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace 977 ); 978 sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0); 979 sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur, 980 regIns, aRegIdx, 0, appendFlag, isReplace==0); 981 } 982 } 983 984 /* Update the count of rows that are inserted 985 */ 986 if( (db->flags & SQLITE_CountRows)!=0 ){ 987 sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1); 988 } 989 990 if( pTrigger ){ 991 /* Code AFTER triggers */ 992 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, 993 pTab, regData-2-pTab->nCol, onError, endOfLoop); 994 } 995 996 /* The bottom of the main insertion loop, if the data source 997 ** is a SELECT statement. 998 */ 999 sqlite3VdbeResolveLabel(v, endOfLoop); 1000 if( useTempTable ){ 1001 sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v); 1002 sqlite3VdbeJumpHere(v, addrInsTop); 1003 sqlite3VdbeAddOp1(v, OP_Close, srcTab); 1004 }else if( pSelect ){ 1005 sqlite3VdbeGoto(v, addrCont); 1006 sqlite3VdbeJumpHere(v, addrInsTop); 1007 } 1008 1009 if( !IsVirtual(pTab) && !isView ){ 1010 /* Close all tables opened */ 1011 if( iDataCur<iIdxCur ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur); 1012 for(idx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){ 1013 sqlite3VdbeAddOp1(v, OP_Close, idx+iIdxCur); 1014 } 1015 } 1016 1017 insert_end: 1018 /* Update the sqlite_sequence table by storing the content of the 1019 ** maximum rowid counter values recorded while inserting into 1020 ** autoincrement tables. 1021 */ 1022 if( pParse->nested==0 && pParse->pTriggerTab==0 ){ 1023 sqlite3AutoincrementEnd(pParse); 1024 } 1025 1026 /* 1027 ** Return the number of rows inserted. If this routine is 1028 ** generating code because of a call to sqlite3NestedParse(), do not 1029 ** invoke the callback function. 1030 */ 1031 if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){ 1032 sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1); 1033 sqlite3VdbeSetNumCols(v, 1); 1034 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC); 1035 } 1036 1037 insert_cleanup: 1038 sqlite3SrcListDelete(db, pTabList); 1039 sqlite3ExprListDelete(db, pList); 1040 sqlite3SelectDelete(db, pSelect); 1041 sqlite3IdListDelete(db, pColumn); 1042 sqlite3DbFree(db, aRegIdx); 1043 } 1044 1045 /* Make sure "isView" and other macros defined above are undefined. Otherwise 1046 ** they may interfere with compilation of other functions in this file 1047 ** (or in another file, if this file becomes part of the amalgamation). */ 1048 #ifdef isView 1049 #undef isView 1050 #endif 1051 #ifdef pTrigger 1052 #undef pTrigger 1053 #endif 1054 #ifdef tmask 1055 #undef tmask 1056 #endif 1057 1058 /* 1059 ** Generate code to do constraint checks prior to an INSERT or an UPDATE 1060 ** on table pTab. 1061 ** 1062 ** The regNewData parameter is the first register in a range that contains 1063 ** the data to be inserted or the data after the update. There will be 1064 ** pTab->nCol+1 registers in this range. The first register (the one 1065 ** that regNewData points to) will contain the new rowid, or NULL in the 1066 ** case of a WITHOUT ROWID table. The second register in the range will 1067 ** contain the content of the first table column. The third register will 1068 ** contain the content of the second table column. And so forth. 1069 ** 1070 ** The regOldData parameter is similar to regNewData except that it contains 1071 ** the data prior to an UPDATE rather than afterwards. regOldData is zero 1072 ** for an INSERT. This routine can distinguish between UPDATE and INSERT by 1073 ** checking regOldData for zero. 1074 ** 1075 ** For an UPDATE, the pkChng boolean is true if the true primary key (the 1076 ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table) 1077 ** might be modified by the UPDATE. If pkChng is false, then the key of 1078 ** the iDataCur content table is guaranteed to be unchanged by the UPDATE. 1079 ** 1080 ** For an INSERT, the pkChng boolean indicates whether or not the rowid 1081 ** was explicitly specified as part of the INSERT statement. If pkChng 1082 ** is zero, it means that the either rowid is computed automatically or 1083 ** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT, 1084 ** pkChng will only be true if the INSERT statement provides an integer 1085 ** value for either the rowid column or its INTEGER PRIMARY KEY alias. 1086 ** 1087 ** The code generated by this routine will store new index entries into 1088 ** registers identified by aRegIdx[]. No index entry is created for 1089 ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is 1090 ** the same as the order of indices on the linked list of indices 1091 ** at pTab->pIndex. 1092 ** 1093 ** The caller must have already opened writeable cursors on the main 1094 ** table and all applicable indices (that is to say, all indices for which 1095 ** aRegIdx[] is not zero). iDataCur is the cursor for the main table when 1096 ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY 1097 ** index when operating on a WITHOUT ROWID table. iIdxCur is the cursor 1098 ** for the first index in the pTab->pIndex list. Cursors for other indices 1099 ** are at iIdxCur+N for the N-th element of the pTab->pIndex list. 1100 ** 1101 ** This routine also generates code to check constraints. NOT NULL, 1102 ** CHECK, and UNIQUE constraints are all checked. If a constraint fails, 1103 ** then the appropriate action is performed. There are five possible 1104 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE. 1105 ** 1106 ** Constraint type Action What Happens 1107 ** --------------- ---------- ---------------------------------------- 1108 ** any ROLLBACK The current transaction is rolled back and 1109 ** sqlite3_step() returns immediately with a 1110 ** return code of SQLITE_CONSTRAINT. 1111 ** 1112 ** any ABORT Back out changes from the current command 1113 ** only (do not do a complete rollback) then 1114 ** cause sqlite3_step() to return immediately 1115 ** with SQLITE_CONSTRAINT. 1116 ** 1117 ** any FAIL Sqlite3_step() returns immediately with a 1118 ** return code of SQLITE_CONSTRAINT. The 1119 ** transaction is not rolled back and any 1120 ** changes to prior rows are retained. 1121 ** 1122 ** any IGNORE The attempt in insert or update the current 1123 ** row is skipped, without throwing an error. 1124 ** Processing continues with the next row. 1125 ** (There is an immediate jump to ignoreDest.) 1126 ** 1127 ** NOT NULL REPLACE The NULL value is replace by the default 1128 ** value for that column. If the default value 1129 ** is NULL, the action is the same as ABORT. 1130 ** 1131 ** UNIQUE REPLACE The other row that conflicts with the row 1132 ** being inserted is removed. 1133 ** 1134 ** CHECK REPLACE Illegal. The results in an exception. 1135 ** 1136 ** Which action to take is determined by the overrideError parameter. 1137 ** Or if overrideError==OE_Default, then the pParse->onError parameter 1138 ** is used. Or if pParse->onError==OE_Default then the onError value 1139 ** for the constraint is used. 1140 */ 1141 void sqlite3GenerateConstraintChecks( 1142 Parse *pParse, /* The parser context */ 1143 Table *pTab, /* The table being inserted or updated */ 1144 int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */ 1145 int iDataCur, /* Canonical data cursor (main table or PK index) */ 1146 int iIdxCur, /* First index cursor */ 1147 int regNewData, /* First register in a range holding values to insert */ 1148 int regOldData, /* Previous content. 0 for INSERTs */ 1149 u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */ 1150 u8 overrideError, /* Override onError to this if not OE_Default */ 1151 int ignoreDest, /* Jump to this label on an OE_Ignore resolution */ 1152 int *pbMayReplace /* OUT: Set to true if constraint may cause a replace */ 1153 ){ 1154 Vdbe *v; /* VDBE under constrution */ 1155 Index *pIdx; /* Pointer to one of the indices */ 1156 Index *pPk = 0; /* The PRIMARY KEY index */ 1157 sqlite3 *db; /* Database connection */ 1158 int i; /* loop counter */ 1159 int ix; /* Index loop counter */ 1160 int nCol; /* Number of columns */ 1161 int onError; /* Conflict resolution strategy */ 1162 int j1; /* Address of jump instruction */ 1163 int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */ 1164 int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */ 1165 int ipkTop = 0; /* Top of the rowid change constraint check */ 1166 int ipkBottom = 0; /* Bottom of the rowid change constraint check */ 1167 u8 isUpdate; /* True if this is an UPDATE operation */ 1168 u8 bAffinityDone = 0; /* True if the OP_Affinity operation has been run */ 1169 int regRowid = -1; /* Register holding ROWID value */ 1170 1171 isUpdate = regOldData!=0; 1172 db = pParse->db; 1173 v = sqlite3GetVdbe(pParse); 1174 assert( v!=0 ); 1175 assert( pTab->pSelect==0 ); /* This table is not a VIEW */ 1176 nCol = pTab->nCol; 1177 1178 /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for 1179 ** normal rowid tables. nPkField is the number of key fields in the 1180 ** pPk index or 1 for a rowid table. In other words, nPkField is the 1181 ** number of fields in the true primary key of the table. */ 1182 if( HasRowid(pTab) ){ 1183 pPk = 0; 1184 nPkField = 1; 1185 }else{ 1186 pPk = sqlite3PrimaryKeyIndex(pTab); 1187 nPkField = pPk->nKeyCol; 1188 } 1189 1190 /* Record that this module has started */ 1191 VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)", 1192 iDataCur, iIdxCur, regNewData, regOldData, pkChng)); 1193 1194 /* Test all NOT NULL constraints. 1195 */ 1196 for(i=0; i<nCol; i++){ 1197 if( i==pTab->iPKey ){ 1198 continue; 1199 } 1200 onError = pTab->aCol[i].notNull; 1201 if( onError==OE_None ) continue; 1202 if( overrideError!=OE_Default ){ 1203 onError = overrideError; 1204 }else if( onError==OE_Default ){ 1205 onError = OE_Abort; 1206 } 1207 if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){ 1208 onError = OE_Abort; 1209 } 1210 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail 1211 || onError==OE_Ignore || onError==OE_Replace ); 1212 switch( onError ){ 1213 case OE_Abort: 1214 sqlite3MayAbort(pParse); 1215 /* Fall through */ 1216 case OE_Rollback: 1217 case OE_Fail: { 1218 char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName, 1219 pTab->aCol[i].zName); 1220 sqlite3VdbeAddOp4(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError, 1221 regNewData+1+i, zMsg, P4_DYNAMIC); 1222 sqlite3VdbeChangeP5(v, P5_ConstraintNotNull); 1223 VdbeCoverage(v); 1224 break; 1225 } 1226 case OE_Ignore: { 1227 sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest); 1228 VdbeCoverage(v); 1229 break; 1230 } 1231 default: { 1232 assert( onError==OE_Replace ); 1233 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i); VdbeCoverage(v); 1234 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i); 1235 sqlite3VdbeJumpHere(v, j1); 1236 break; 1237 } 1238 } 1239 } 1240 1241 /* Test all CHECK constraints 1242 */ 1243 #ifndef SQLITE_OMIT_CHECK 1244 if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){ 1245 ExprList *pCheck = pTab->pCheck; 1246 pParse->ckBase = regNewData+1; 1247 onError = overrideError!=OE_Default ? overrideError : OE_Abort; 1248 for(i=0; i<pCheck->nExpr; i++){ 1249 int allOk = sqlite3VdbeMakeLabel(v); 1250 sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL); 1251 if( onError==OE_Ignore ){ 1252 sqlite3VdbeGoto(v, ignoreDest); 1253 }else{ 1254 char *zName = pCheck->a[i].zName; 1255 if( zName==0 ) zName = pTab->zName; 1256 if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */ 1257 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK, 1258 onError, zName, P4_TRANSIENT, 1259 P5_ConstraintCheck); 1260 } 1261 sqlite3VdbeResolveLabel(v, allOk); 1262 } 1263 } 1264 #endif /* !defined(SQLITE_OMIT_CHECK) */ 1265 1266 /* If rowid is changing, make sure the new rowid does not previously 1267 ** exist in the table. 1268 */ 1269 if( pkChng && pPk==0 ){ 1270 int addrRowidOk = sqlite3VdbeMakeLabel(v); 1271 1272 /* Figure out what action to take in case of a rowid collision */ 1273 onError = pTab->keyConf; 1274 if( overrideError!=OE_Default ){ 1275 onError = overrideError; 1276 }else if( onError==OE_Default ){ 1277 onError = OE_Abort; 1278 } 1279 1280 if( isUpdate ){ 1281 /* pkChng!=0 does not mean that the rowid has change, only that 1282 ** it might have changed. Skip the conflict logic below if the rowid 1283 ** is unchanged. */ 1284 sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData); 1285 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); 1286 VdbeCoverage(v); 1287 } 1288 1289 /* If the response to a rowid conflict is REPLACE but the response 1290 ** to some other UNIQUE constraint is FAIL or IGNORE, then we need 1291 ** to defer the running of the rowid conflict checking until after 1292 ** the UNIQUE constraints have run. 1293 */ 1294 if( onError==OE_Replace && overrideError!=OE_Replace ){ 1295 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 1296 if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){ 1297 ipkTop = sqlite3VdbeAddOp0(v, OP_Goto); 1298 break; 1299 } 1300 } 1301 } 1302 1303 /* Check to see if the new rowid already exists in the table. Skip 1304 ** the following conflict logic if it does not. */ 1305 sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData); 1306 VdbeCoverage(v); 1307 1308 /* Generate code that deals with a rowid collision */ 1309 switch( onError ){ 1310 default: { 1311 onError = OE_Abort; 1312 /* Fall thru into the next case */ 1313 } 1314 case OE_Rollback: 1315 case OE_Abort: 1316 case OE_Fail: { 1317 sqlite3RowidConstraint(pParse, onError, pTab); 1318 break; 1319 } 1320 case OE_Replace: { 1321 /* If there are DELETE triggers on this table and the 1322 ** recursive-triggers flag is set, call GenerateRowDelete() to 1323 ** remove the conflicting row from the table. This will fire 1324 ** the triggers and remove both the table and index b-tree entries. 1325 ** 1326 ** Otherwise, if there are no triggers or the recursive-triggers 1327 ** flag is not set, but the table has one or more indexes, call 1328 ** GenerateRowIndexDelete(). This removes the index b-tree entries 1329 ** only. The table b-tree entry will be replaced by the new entry 1330 ** when it is inserted. 1331 ** 1332 ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called, 1333 ** also invoke MultiWrite() to indicate that this VDBE may require 1334 ** statement rollback (if the statement is aborted after the delete 1335 ** takes place). Earlier versions called sqlite3MultiWrite() regardless, 1336 ** but being more selective here allows statements like: 1337 ** 1338 ** REPLACE INTO t(rowid) VALUES($newrowid) 1339 ** 1340 ** to run without a statement journal if there are no indexes on the 1341 ** table. 1342 */ 1343 Trigger *pTrigger = 0; 1344 if( db->flags&SQLITE_RecTriggers ){ 1345 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0); 1346 } 1347 if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){ 1348 sqlite3MultiWrite(pParse); 1349 sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur, 1350 regNewData, 1, 0, OE_Replace, 1351 ONEPASS_SINGLE, -1); 1352 }else{ 1353 if( pTab->pIndex ){ 1354 sqlite3MultiWrite(pParse); 1355 sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1); 1356 } 1357 } 1358 seenReplace = 1; 1359 break; 1360 } 1361 case OE_Ignore: { 1362 /*assert( seenReplace==0 );*/ 1363 sqlite3VdbeGoto(v, ignoreDest); 1364 break; 1365 } 1366 } 1367 sqlite3VdbeResolveLabel(v, addrRowidOk); 1368 if( ipkTop ){ 1369 ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto); 1370 sqlite3VdbeJumpHere(v, ipkTop); 1371 } 1372 } 1373 1374 /* Test all UNIQUE constraints by creating entries for each UNIQUE 1375 ** index and making sure that duplicate entries do not already exist. 1376 ** Compute the revised record entries for indices as we go. 1377 ** 1378 ** This loop also handles the case of the PRIMARY KEY index for a 1379 ** WITHOUT ROWID table. 1380 */ 1381 for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){ 1382 int regIdx; /* Range of registers hold conent for pIdx */ 1383 int regR; /* Range of registers holding conflicting PK */ 1384 int iThisCur; /* Cursor for this UNIQUE index */ 1385 int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */ 1386 1387 if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */ 1388 if( bAffinityDone==0 ){ 1389 sqlite3TableAffinity(v, pTab, regNewData+1); 1390 bAffinityDone = 1; 1391 } 1392 iThisCur = iIdxCur+ix; 1393 addrUniqueOk = sqlite3VdbeMakeLabel(v); 1394 1395 /* Skip partial indices for which the WHERE clause is not true */ 1396 if( pIdx->pPartIdxWhere ){ 1397 sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]); 1398 pParse->ckBase = regNewData+1; 1399 sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk, 1400 SQLITE_JUMPIFNULL); 1401 pParse->ckBase = 0; 1402 } 1403 1404 /* Create a record for this index entry as it should appear after 1405 ** the insert or update. Store that record in the aRegIdx[ix] register 1406 */ 1407 regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn); 1408 for(i=0; i<pIdx->nColumn; i++){ 1409 int iField = pIdx->aiColumn[i]; 1410 int x; 1411 if( iField==XN_EXPR ){ 1412 pParse->ckBase = regNewData+1; 1413 sqlite3ExprCode(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i); 1414 pParse->ckBase = 0; 1415 VdbeComment((v, "%s column %d", pIdx->zName, i)); 1416 }else{ 1417 if( iField==XN_ROWID || iField==pTab->iPKey ){ 1418 if( regRowid==regIdx+i ) continue; /* ROWID already in regIdx+i */ 1419 x = regNewData; 1420 regRowid = pIdx->pPartIdxWhere ? -1 : regIdx+i; 1421 }else{ 1422 x = iField + regNewData + 1; 1423 } 1424 sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i); 1425 VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName)); 1426 } 1427 } 1428 sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]); 1429 VdbeComment((v, "for %s", pIdx->zName)); 1430 sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn); 1431 1432 /* In an UPDATE operation, if this index is the PRIMARY KEY index 1433 ** of a WITHOUT ROWID table and there has been no change the 1434 ** primary key, then no collision is possible. The collision detection 1435 ** logic below can all be skipped. */ 1436 if( isUpdate && pPk==pIdx && pkChng==0 ){ 1437 sqlite3VdbeResolveLabel(v, addrUniqueOk); 1438 continue; 1439 } 1440 1441 /* Find out what action to take in case there is a uniqueness conflict */ 1442 onError = pIdx->onError; 1443 if( onError==OE_None ){ 1444 sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn); 1445 sqlite3VdbeResolveLabel(v, addrUniqueOk); 1446 continue; /* pIdx is not a UNIQUE index */ 1447 } 1448 if( overrideError!=OE_Default ){ 1449 onError = overrideError; 1450 }else if( onError==OE_Default ){ 1451 onError = OE_Abort; 1452 } 1453 1454 /* Check to see if the new index entry will be unique */ 1455 sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk, 1456 regIdx, pIdx->nKeyCol); VdbeCoverage(v); 1457 1458 /* Generate code to handle collisions */ 1459 regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField); 1460 if( isUpdate || onError==OE_Replace ){ 1461 if( HasRowid(pTab) ){ 1462 sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR); 1463 /* Conflict only if the rowid of the existing index entry 1464 ** is different from old-rowid */ 1465 if( isUpdate ){ 1466 sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData); 1467 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); 1468 VdbeCoverage(v); 1469 } 1470 }else{ 1471 int x; 1472 /* Extract the PRIMARY KEY from the end of the index entry and 1473 ** store it in registers regR..regR+nPk-1 */ 1474 if( pIdx!=pPk ){ 1475 for(i=0; i<pPk->nKeyCol; i++){ 1476 assert( pPk->aiColumn[i]>=0 ); 1477 x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]); 1478 sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i); 1479 VdbeComment((v, "%s.%s", pTab->zName, 1480 pTab->aCol[pPk->aiColumn[i]].zName)); 1481 } 1482 } 1483 if( isUpdate ){ 1484 /* If currently processing the PRIMARY KEY of a WITHOUT ROWID 1485 ** table, only conflict if the new PRIMARY KEY values are actually 1486 ** different from the old. 1487 ** 1488 ** For a UNIQUE index, only conflict if the PRIMARY KEY values 1489 ** of the matched index row are different from the original PRIMARY 1490 ** KEY values of this row before the update. */ 1491 int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol; 1492 int op = OP_Ne; 1493 int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR); 1494 1495 for(i=0; i<pPk->nKeyCol; i++){ 1496 char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]); 1497 x = pPk->aiColumn[i]; 1498 assert( x>=0 ); 1499 if( i==(pPk->nKeyCol-1) ){ 1500 addrJump = addrUniqueOk; 1501 op = OP_Eq; 1502 } 1503 sqlite3VdbeAddOp4(v, op, 1504 regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ 1505 ); 1506 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); 1507 VdbeCoverageIf(v, op==OP_Eq); 1508 VdbeCoverageIf(v, op==OP_Ne); 1509 } 1510 } 1511 } 1512 } 1513 1514 /* Generate code that executes if the new index entry is not unique */ 1515 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail 1516 || onError==OE_Ignore || onError==OE_Replace ); 1517 switch( onError ){ 1518 case OE_Rollback: 1519 case OE_Abort: 1520 case OE_Fail: { 1521 sqlite3UniqueConstraint(pParse, onError, pIdx); 1522 break; 1523 } 1524 case OE_Ignore: { 1525 sqlite3VdbeGoto(v, ignoreDest); 1526 break; 1527 } 1528 default: { 1529 Trigger *pTrigger = 0; 1530 assert( onError==OE_Replace ); 1531 sqlite3MultiWrite(pParse); 1532 if( db->flags&SQLITE_RecTriggers ){ 1533 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0); 1534 } 1535 sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur, 1536 regR, nPkField, 0, OE_Replace, 1537 (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), -1); 1538 seenReplace = 1; 1539 break; 1540 } 1541 } 1542 sqlite3VdbeResolveLabel(v, addrUniqueOk); 1543 sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn); 1544 if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField); 1545 } 1546 if( ipkTop ){ 1547 sqlite3VdbeGoto(v, ipkTop+1); 1548 sqlite3VdbeJumpHere(v, ipkBottom); 1549 } 1550 1551 *pbMayReplace = seenReplace; 1552 VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace)); 1553 } 1554 1555 /* 1556 ** This routine generates code to finish the INSERT or UPDATE operation 1557 ** that was started by a prior call to sqlite3GenerateConstraintChecks. 1558 ** A consecutive range of registers starting at regNewData contains the 1559 ** rowid and the content to be inserted. 1560 ** 1561 ** The arguments to this routine should be the same as the first six 1562 ** arguments to sqlite3GenerateConstraintChecks. 1563 */ 1564 void sqlite3CompleteInsertion( 1565 Parse *pParse, /* The parser context */ 1566 Table *pTab, /* the table into which we are inserting */ 1567 int iDataCur, /* Cursor of the canonical data source */ 1568 int iIdxCur, /* First index cursor */ 1569 int regNewData, /* Range of content */ 1570 int *aRegIdx, /* Register used by each index. 0 for unused indices */ 1571 int isUpdate, /* True for UPDATE, False for INSERT */ 1572 int appendBias, /* True if this is likely to be an append */ 1573 int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */ 1574 ){ 1575 Vdbe *v; /* Prepared statements under construction */ 1576 Index *pIdx; /* An index being inserted or updated */ 1577 u8 pik_flags; /* flag values passed to the btree insert */ 1578 int regData; /* Content registers (after the rowid) */ 1579 int regRec; /* Register holding assembled record for the table */ 1580 int i; /* Loop counter */ 1581 u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */ 1582 1583 v = sqlite3GetVdbe(pParse); 1584 assert( v!=0 ); 1585 assert( pTab->pSelect==0 ); /* This table is not a VIEW */ 1586 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ 1587 if( aRegIdx[i]==0 ) continue; 1588 bAffinityDone = 1; 1589 if( pIdx->pPartIdxWhere ){ 1590 sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2); 1591 VdbeCoverage(v); 1592 } 1593 sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i]); 1594 pik_flags = 0; 1595 if( useSeekResult ) pik_flags = OPFLAG_USESEEKRESULT; 1596 if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){ 1597 assert( pParse->nested==0 ); 1598 pik_flags |= OPFLAG_NCHANGE; 1599 } 1600 if( pik_flags ) sqlite3VdbeChangeP5(v, pik_flags); 1601 } 1602 if( !HasRowid(pTab) ) return; 1603 regData = regNewData + 1; 1604 regRec = sqlite3GetTempReg(pParse); 1605 sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec); 1606 if( !bAffinityDone ) sqlite3TableAffinity(v, pTab, 0); 1607 sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol); 1608 if( pParse->nested ){ 1609 pik_flags = 0; 1610 }else{ 1611 pik_flags = OPFLAG_NCHANGE; 1612 pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID); 1613 } 1614 if( appendBias ){ 1615 pik_flags |= OPFLAG_APPEND; 1616 } 1617 if( useSeekResult ){ 1618 pik_flags |= OPFLAG_USESEEKRESULT; 1619 } 1620 sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData); 1621 if( !pParse->nested ){ 1622 sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT); 1623 } 1624 sqlite3VdbeChangeP5(v, pik_flags); 1625 } 1626 1627 /* 1628 ** Allocate cursors for the pTab table and all its indices and generate 1629 ** code to open and initialized those cursors. 1630 ** 1631 ** The cursor for the object that contains the complete data (normally 1632 ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT 1633 ** ROWID table) is returned in *piDataCur. The first index cursor is 1634 ** returned in *piIdxCur. The number of indices is returned. 1635 ** 1636 ** Use iBase as the first cursor (either the *piDataCur for rowid tables 1637 ** or the first index for WITHOUT ROWID tables) if it is non-negative. 1638 ** If iBase is negative, then allocate the next available cursor. 1639 ** 1640 ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur. 1641 ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range 1642 ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the 1643 ** pTab->pIndex list. 1644 ** 1645 ** If pTab is a virtual table, then this routine is a no-op and the 1646 ** *piDataCur and *piIdxCur values are left uninitialized. 1647 */ 1648 int sqlite3OpenTableAndIndices( 1649 Parse *pParse, /* Parsing context */ 1650 Table *pTab, /* Table to be opened */ 1651 int op, /* OP_OpenRead or OP_OpenWrite */ 1652 int iBase, /* Use this for the table cursor, if there is one */ 1653 u8 *aToOpen, /* If not NULL: boolean for each table and index */ 1654 int *piDataCur, /* Write the database source cursor number here */ 1655 int *piIdxCur /* Write the first index cursor number here */ 1656 ){ 1657 int i; 1658 int iDb; 1659 int iDataCur; 1660 Index *pIdx; 1661 Vdbe *v; 1662 1663 assert( op==OP_OpenRead || op==OP_OpenWrite ); 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 VdbeComment((v, "%s", pIdx->zName)); 1692 } 1693 } 1694 if( iBase>pParse->nTab ) pParse->nTab = iBase; 1695 return i; 1696 } 1697 1698 1699 #ifdef SQLITE_TEST 1700 /* 1701 ** The following global variable is incremented whenever the 1702 ** transfer optimization is used. This is used for testing 1703 ** purposes only - to make sure the transfer optimization really 1704 ** is happening when it is supposed to. 1705 */ 1706 int sqlite3_xferopt_count; 1707 #endif /* SQLITE_TEST */ 1708 1709 1710 #ifndef SQLITE_OMIT_XFER_OPT 1711 /* 1712 ** Check to collation names to see if they are compatible. 1713 */ 1714 static int xferCompatibleCollation(const char *z1, const char *z2){ 1715 if( z1==0 ){ 1716 return z2==0; 1717 } 1718 if( z2==0 ){ 1719 return 0; 1720 } 1721 return sqlite3StrICmp(z1, z2)==0; 1722 } 1723 1724 1725 /* 1726 ** Check to see if index pSrc is compatible as a source of data 1727 ** for index pDest in an insert transfer optimization. The rules 1728 ** for a compatible index: 1729 ** 1730 ** * The index is over the same set of columns 1731 ** * The same DESC and ASC markings occurs on all columns 1732 ** * The same onError processing (OE_Abort, OE_Ignore, etc) 1733 ** * The same collating sequence on each column 1734 ** * The index has the exact same WHERE clause 1735 */ 1736 static int xferCompatibleIndex(Index *pDest, Index *pSrc){ 1737 int i; 1738 assert( pDest && pSrc ); 1739 assert( pDest->pTable!=pSrc->pTable ); 1740 if( pDest->nKeyCol!=pSrc->nKeyCol ){ 1741 return 0; /* Different number of columns */ 1742 } 1743 if( pDest->onError!=pSrc->onError ){ 1744 return 0; /* Different conflict resolution strategies */ 1745 } 1746 for(i=0; i<pSrc->nKeyCol; i++){ 1747 if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){ 1748 return 0; /* Different columns indexed */ 1749 } 1750 if( pSrc->aiColumn[i]==XN_EXPR ){ 1751 assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 ); 1752 if( sqlite3ExprCompare(pSrc->aColExpr->a[i].pExpr, 1753 pDest->aColExpr->a[i].pExpr, -1)!=0 ){ 1754 return 0; /* Different expressions in the index */ 1755 } 1756 } 1757 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){ 1758 return 0; /* Different sort orders */ 1759 } 1760 if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){ 1761 return 0; /* Different collating sequences */ 1762 } 1763 } 1764 if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){ 1765 return 0; /* Different WHERE clauses */ 1766 } 1767 1768 /* If no test above fails then the indices must be compatible */ 1769 return 1; 1770 } 1771 1772 /* 1773 ** Attempt the transfer optimization on INSERTs of the form 1774 ** 1775 ** INSERT INTO tab1 SELECT * FROM tab2; 1776 ** 1777 ** The xfer optimization transfers raw records from tab2 over to tab1. 1778 ** Columns are not decoded and reassembled, which greatly improves 1779 ** performance. Raw index records are transferred in the same way. 1780 ** 1781 ** The xfer optimization is only attempted if tab1 and tab2 are compatible. 1782 ** There are lots of rules for determining compatibility - see comments 1783 ** embedded in the code for details. 1784 ** 1785 ** This routine returns TRUE if the optimization is guaranteed to be used. 1786 ** Sometimes the xfer optimization will only work if the destination table 1787 ** is empty - a factor that can only be determined at run-time. In that 1788 ** case, this routine generates code for the xfer optimization but also 1789 ** does a test to see if the destination table is empty and jumps over the 1790 ** xfer optimization code if the test fails. In that case, this routine 1791 ** returns FALSE so that the caller will know to go ahead and generate 1792 ** an unoptimized transfer. This routine also returns FALSE if there 1793 ** is no chance that the xfer optimization can be applied. 1794 ** 1795 ** This optimization is particularly useful at making VACUUM run faster. 1796 */ 1797 static int xferOptimization( 1798 Parse *pParse, /* Parser context */ 1799 Table *pDest, /* The table we are inserting into */ 1800 Select *pSelect, /* A SELECT statement to use as the data source */ 1801 int onError, /* How to handle constraint errors */ 1802 int iDbDest /* The database of pDest */ 1803 ){ 1804 sqlite3 *db = pParse->db; 1805 ExprList *pEList; /* The result set of the SELECT */ 1806 Table *pSrc; /* The table in the FROM clause of SELECT */ 1807 Index *pSrcIdx, *pDestIdx; /* Source and destination indices */ 1808 struct SrcList_item *pItem; /* An element of pSelect->pSrc */ 1809 int i; /* Loop counter */ 1810 int iDbSrc; /* The database of pSrc */ 1811 int iSrc, iDest; /* Cursors from source and destination */ 1812 int addr1, addr2; /* Loop addresses */ 1813 int emptyDestTest = 0; /* Address of test for empty pDest */ 1814 int emptySrcTest = 0; /* Address of test for empty pSrc */ 1815 Vdbe *v; /* The VDBE we are building */ 1816 int regAutoinc; /* Memory register used by AUTOINC */ 1817 int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */ 1818 int regData, regRowid; /* Registers holding data and rowid */ 1819 1820 if( pSelect==0 ){ 1821 return 0; /* Must be of the form INSERT INTO ... SELECT ... */ 1822 } 1823 if( pParse->pWith || pSelect->pWith ){ 1824 /* Do not attempt to process this query if there are an WITH clauses 1825 ** attached to it. Proceeding may generate a false "no such table: xxx" 1826 ** error if pSelect reads from a CTE named "xxx". */ 1827 return 0; 1828 } 1829 if( sqlite3TriggerList(pParse, pDest) ){ 1830 return 0; /* tab1 must not have triggers */ 1831 } 1832 #ifndef SQLITE_OMIT_VIRTUALTABLE 1833 if( pDest->tabFlags & TF_Virtual ){ 1834 return 0; /* tab1 must not be a virtual table */ 1835 } 1836 #endif 1837 if( onError==OE_Default ){ 1838 if( pDest->iPKey>=0 ) onError = pDest->keyConf; 1839 if( onError==OE_Default ) onError = OE_Abort; 1840 } 1841 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */ 1842 if( pSelect->pSrc->nSrc!=1 ){ 1843 return 0; /* FROM clause must have exactly one term */ 1844 } 1845 if( pSelect->pSrc->a[0].pSelect ){ 1846 return 0; /* FROM clause cannot contain a subquery */ 1847 } 1848 if( pSelect->pWhere ){ 1849 return 0; /* SELECT may not have a WHERE clause */ 1850 } 1851 if( pSelect->pOrderBy ){ 1852 return 0; /* SELECT may not have an ORDER BY clause */ 1853 } 1854 /* Do not need to test for a HAVING clause. If HAVING is present but 1855 ** there is no ORDER BY, we will get an error. */ 1856 if( pSelect->pGroupBy ){ 1857 return 0; /* SELECT may not have a GROUP BY clause */ 1858 } 1859 if( pSelect->pLimit ){ 1860 return 0; /* SELECT may not have a LIMIT clause */ 1861 } 1862 assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */ 1863 if( pSelect->pPrior ){ 1864 return 0; /* SELECT may not be a compound query */ 1865 } 1866 if( pSelect->selFlags & SF_Distinct ){ 1867 return 0; /* SELECT may not be DISTINCT */ 1868 } 1869 pEList = pSelect->pEList; 1870 assert( pEList!=0 ); 1871 if( pEList->nExpr!=1 ){ 1872 return 0; /* The result set must have exactly one column */ 1873 } 1874 assert( pEList->a[0].pExpr ); 1875 if( pEList->a[0].pExpr->op!=TK_ALL ){ 1876 return 0; /* The result set must be the special operator "*" */ 1877 } 1878 1879 /* At this point we have established that the statement is of the 1880 ** correct syntactic form to participate in this optimization. Now 1881 ** we have to check the semantics. 1882 */ 1883 pItem = pSelect->pSrc->a; 1884 pSrc = sqlite3LocateTableItem(pParse, 0, pItem); 1885 if( pSrc==0 ){ 1886 return 0; /* FROM clause does not contain a real table */ 1887 } 1888 if( pSrc==pDest ){ 1889 return 0; /* tab1 and tab2 may not be the same table */ 1890 } 1891 if( HasRowid(pDest)!=HasRowid(pSrc) ){ 1892 return 0; /* source and destination must both be WITHOUT ROWID or not */ 1893 } 1894 #ifndef SQLITE_OMIT_VIRTUALTABLE 1895 if( pSrc->tabFlags & TF_Virtual ){ 1896 return 0; /* tab2 must not be a virtual table */ 1897 } 1898 #endif 1899 if( pSrc->pSelect ){ 1900 return 0; /* tab2 may not be a view */ 1901 } 1902 if( pDest->nCol!=pSrc->nCol ){ 1903 return 0; /* Number of columns must be the same in tab1 and tab2 */ 1904 } 1905 if( pDest->iPKey!=pSrc->iPKey ){ 1906 return 0; /* Both tables must have the same INTEGER PRIMARY KEY */ 1907 } 1908 for(i=0; i<pDest->nCol; i++){ 1909 Column *pDestCol = &pDest->aCol[i]; 1910 Column *pSrcCol = &pSrc->aCol[i]; 1911 if( pDestCol->affinity!=pSrcCol->affinity ){ 1912 return 0; /* Affinity must be the same on all columns */ 1913 } 1914 if( !xferCompatibleCollation(pDestCol->zColl, pSrcCol->zColl) ){ 1915 return 0; /* Collating sequence must be the same on all columns */ 1916 } 1917 if( pDestCol->notNull && !pSrcCol->notNull ){ 1918 return 0; /* tab2 must be NOT NULL if tab1 is */ 1919 } 1920 /* Default values for second and subsequent columns need to match. */ 1921 if( i>0 1922 && ((pDestCol->zDflt==0)!=(pSrcCol->zDflt==0) 1923 || (pDestCol->zDflt && strcmp(pDestCol->zDflt, pSrcCol->zDflt)!=0)) 1924 ){ 1925 return 0; /* Default values must be the same for all columns */ 1926 } 1927 } 1928 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ 1929 if( IsUniqueIndex(pDestIdx) ){ 1930 destHasUniqueIdx = 1; 1931 } 1932 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){ 1933 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; 1934 } 1935 if( pSrcIdx==0 ){ 1936 return 0; /* pDestIdx has no corresponding index in pSrc */ 1937 } 1938 } 1939 #ifndef SQLITE_OMIT_CHECK 1940 if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){ 1941 return 0; /* Tables have different CHECK constraints. Ticket #2252 */ 1942 } 1943 #endif 1944 #ifndef SQLITE_OMIT_FOREIGN_KEY 1945 /* Disallow the transfer optimization if the destination table constains 1946 ** any foreign key constraints. This is more restrictive than necessary. 1947 ** But the main beneficiary of the transfer optimization is the VACUUM 1948 ** command, and the VACUUM command disables foreign key constraints. So 1949 ** the extra complication to make this rule less restrictive is probably 1950 ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e] 1951 */ 1952 if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){ 1953 return 0; 1954 } 1955 #endif 1956 if( (db->flags & SQLITE_CountRows)!=0 ){ 1957 return 0; /* xfer opt does not play well with PRAGMA count_changes */ 1958 } 1959 1960 /* If we get this far, it means that the xfer optimization is at 1961 ** least a possibility, though it might only work if the destination 1962 ** table (tab1) is initially empty. 1963 */ 1964 #ifdef SQLITE_TEST 1965 sqlite3_xferopt_count++; 1966 #endif 1967 iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema); 1968 v = sqlite3GetVdbe(pParse); 1969 sqlite3CodeVerifySchema(pParse, iDbSrc); 1970 iSrc = pParse->nTab++; 1971 iDest = pParse->nTab++; 1972 regAutoinc = autoIncBegin(pParse, iDbDest, pDest); 1973 regData = sqlite3GetTempReg(pParse); 1974 regRowid = sqlite3GetTempReg(pParse); 1975 sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite); 1976 assert( HasRowid(pDest) || destHasUniqueIdx ); 1977 if( (db->flags & SQLITE_Vacuum)==0 && ( 1978 (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */ 1979 || destHasUniqueIdx /* (2) */ 1980 || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */ 1981 )){ 1982 /* In some circumstances, we are able to run the xfer optimization 1983 ** only if the destination table is initially empty. Unless the 1984 ** SQLITE_Vacuum flag is set, this block generates code to make 1985 ** that determination. If SQLITE_Vacuum is set, then the destination 1986 ** table is always empty. 1987 ** 1988 ** Conditions under which the destination must be empty: 1989 ** 1990 ** (1) There is no INTEGER PRIMARY KEY but there are indices. 1991 ** (If the destination is not initially empty, the rowid fields 1992 ** of index entries might need to change.) 1993 ** 1994 ** (2) The destination has a unique index. (The xfer optimization 1995 ** is unable to test uniqueness.) 1996 ** 1997 ** (3) onError is something other than OE_Abort and OE_Rollback. 1998 */ 1999 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v); 2000 emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto); 2001 sqlite3VdbeJumpHere(v, addr1); 2002 } 2003 if( HasRowid(pSrc) ){ 2004 sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead); 2005 emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v); 2006 if( pDest->iPKey>=0 ){ 2007 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); 2008 addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid); 2009 VdbeCoverage(v); 2010 sqlite3RowidConstraint(pParse, onError, pDest); 2011 sqlite3VdbeJumpHere(v, addr2); 2012 autoIncStep(pParse, regAutoinc, regRowid); 2013 }else if( pDest->pIndex==0 ){ 2014 addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid); 2015 }else{ 2016 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); 2017 assert( (pDest->tabFlags & TF_Autoincrement)==0 ); 2018 } 2019 sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData); 2020 sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid); 2021 sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND); 2022 sqlite3VdbeChangeP4(v, -1, pDest->zName, 0); 2023 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v); 2024 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); 2025 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); 2026 }else{ 2027 sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName); 2028 sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName); 2029 } 2030 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ 2031 u8 idxInsFlags = 0; 2032 for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){ 2033 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; 2034 } 2035 assert( pSrcIdx ); 2036 sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc); 2037 sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx); 2038 VdbeComment((v, "%s", pSrcIdx->zName)); 2039 sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest); 2040 sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx); 2041 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR); 2042 VdbeComment((v, "%s", pDestIdx->zName)); 2043 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v); 2044 sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData); 2045 if( db->flags & SQLITE_Vacuum ){ 2046 /* This INSERT command is part of a VACUUM operation, which guarantees 2047 ** that the destination table is empty. If all indexed columns use 2048 ** collation sequence BINARY, then it can also be assumed that the 2049 ** index will be populated by inserting keys in strictly sorted 2050 ** order. In this case, instead of seeking within the b-tree as part 2051 ** of every OP_IdxInsert opcode, an OP_Last is added before the 2052 ** OP_IdxInsert to seek to the point within the b-tree where each key 2053 ** should be inserted. This is faster. 2054 ** 2055 ** If any of the indexed columns use a collation sequence other than 2056 ** BINARY, this optimization is disabled. This is because the user 2057 ** might change the definition of a collation sequence and then run 2058 ** a VACUUM command. In that case keys may not be written in strictly 2059 ** sorted order. */ 2060 for(i=0; i<pSrcIdx->nColumn; i++){ 2061 char *zColl = pSrcIdx->azColl[i]; 2062 assert( zColl!=0 ); 2063 if( sqlite3_stricmp("BINARY", zColl) ) break; 2064 } 2065 if( i==pSrcIdx->nColumn ){ 2066 idxInsFlags = OPFLAG_USESEEKRESULT; 2067 sqlite3VdbeAddOp3(v, OP_Last, iDest, 0, -1); 2068 } 2069 } 2070 if( !HasRowid(pSrc) && pDestIdx->idxType==2 ){ 2071 idxInsFlags |= OPFLAG_NCHANGE; 2072 } 2073 sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1); 2074 sqlite3VdbeChangeP5(v, idxInsFlags); 2075 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v); 2076 sqlite3VdbeJumpHere(v, addr1); 2077 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); 2078 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); 2079 } 2080 if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest); 2081 sqlite3ReleaseTempReg(pParse, regRowid); 2082 sqlite3ReleaseTempReg(pParse, regData); 2083 if( emptyDestTest ){ 2084 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0); 2085 sqlite3VdbeJumpHere(v, emptyDestTest); 2086 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); 2087 return 0; 2088 }else{ 2089 return 1; 2090 } 2091 } 2092 #endif /* SQLITE_OMIT_XFER_OPT */ 2093