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==(-1) ){ 94 pIdx->zColAff[n] = SQLITE_AFF_INTEGER; 95 }else{ 96 char aff; 97 assert( x==(-2) ); 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( pParse==sqlite3ParseToplevel(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, 1); 1351 }else if( pTab->pIndex ){ 1352 sqlite3MultiWrite(pParse); 1353 sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, 0); 1354 } 1355 seenReplace = 1; 1356 break; 1357 } 1358 case OE_Ignore: { 1359 /*assert( seenReplace==0 );*/ 1360 sqlite3VdbeGoto(v, ignoreDest); 1361 break; 1362 } 1363 } 1364 sqlite3VdbeResolveLabel(v, addrRowidOk); 1365 if( ipkTop ){ 1366 ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto); 1367 sqlite3VdbeJumpHere(v, ipkTop); 1368 } 1369 } 1370 1371 /* Test all UNIQUE constraints by creating entries for each UNIQUE 1372 ** index and making sure that duplicate entries do not already exist. 1373 ** Compute the revised record entries for indices as we go. 1374 ** 1375 ** This loop also handles the case of the PRIMARY KEY index for a 1376 ** WITHOUT ROWID table. 1377 */ 1378 for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){ 1379 int regIdx; /* Range of registers hold conent for pIdx */ 1380 int regR; /* Range of registers holding conflicting PK */ 1381 int iThisCur; /* Cursor for this UNIQUE index */ 1382 int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */ 1383 1384 if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */ 1385 if( bAffinityDone==0 ){ 1386 sqlite3TableAffinity(v, pTab, regNewData+1); 1387 bAffinityDone = 1; 1388 } 1389 iThisCur = iIdxCur+ix; 1390 addrUniqueOk = sqlite3VdbeMakeLabel(v); 1391 1392 /* Skip partial indices for which the WHERE clause is not true */ 1393 if( pIdx->pPartIdxWhere ){ 1394 sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]); 1395 pParse->ckBase = regNewData+1; 1396 sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk, 1397 SQLITE_JUMPIFNULL); 1398 pParse->ckBase = 0; 1399 } 1400 1401 /* Create a record for this index entry as it should appear after 1402 ** the insert or update. Store that record in the aRegIdx[ix] register 1403 */ 1404 regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn); 1405 for(i=0; i<pIdx->nColumn; i++){ 1406 int iField = pIdx->aiColumn[i]; 1407 int x; 1408 if( iField==(-2) ){ 1409 pParse->ckBase = regNewData+1; 1410 sqlite3ExprCode(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i); 1411 pParse->ckBase = 0; 1412 VdbeComment((v, "%s column %d", pIdx->zName, i)); 1413 }else{ 1414 if( iField==(-1) || iField==pTab->iPKey ){ 1415 if( regRowid==regIdx+i ) continue; /* ROWID already in regIdx+i */ 1416 x = regNewData; 1417 regRowid = pIdx->pPartIdxWhere ? -1 : regIdx+i; 1418 }else{ 1419 x = iField + regNewData + 1; 1420 } 1421 sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i); 1422 VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName)); 1423 } 1424 } 1425 sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]); 1426 VdbeComment((v, "for %s", pIdx->zName)); 1427 sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn); 1428 1429 /* In an UPDATE operation, if this index is the PRIMARY KEY index 1430 ** of a WITHOUT ROWID table and there has been no change the 1431 ** primary key, then no collision is possible. The collision detection 1432 ** logic below can all be skipped. */ 1433 if( isUpdate && pPk==pIdx && pkChng==0 ){ 1434 sqlite3VdbeResolveLabel(v, addrUniqueOk); 1435 continue; 1436 } 1437 1438 /* Find out what action to take in case there is a uniqueness conflict */ 1439 onError = pIdx->onError; 1440 if( onError==OE_None ){ 1441 sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn); 1442 sqlite3VdbeResolveLabel(v, addrUniqueOk); 1443 continue; /* pIdx is not a UNIQUE index */ 1444 } 1445 if( overrideError!=OE_Default ){ 1446 onError = overrideError; 1447 }else if( onError==OE_Default ){ 1448 onError = OE_Abort; 1449 } 1450 1451 /* Check to see if the new index entry will be unique */ 1452 sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk, 1453 regIdx, pIdx->nKeyCol); VdbeCoverage(v); 1454 1455 /* Generate code to handle collisions */ 1456 regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField); 1457 if( isUpdate || onError==OE_Replace ){ 1458 if( HasRowid(pTab) ){ 1459 sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR); 1460 /* Conflict only if the rowid of the existing index entry 1461 ** is different from old-rowid */ 1462 if( isUpdate ){ 1463 sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData); 1464 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); 1465 VdbeCoverage(v); 1466 } 1467 }else{ 1468 int x; 1469 /* Extract the PRIMARY KEY from the end of the index entry and 1470 ** store it in registers regR..regR+nPk-1 */ 1471 if( pIdx!=pPk ){ 1472 for(i=0; i<pPk->nKeyCol; i++){ 1473 x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]); 1474 sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i); 1475 VdbeComment((v, "%s.%s", pTab->zName, 1476 pTab->aCol[pPk->aiColumn[i]].zName)); 1477 } 1478 } 1479 if( isUpdate ){ 1480 /* If currently processing the PRIMARY KEY of a WITHOUT ROWID 1481 ** table, only conflict if the new PRIMARY KEY values are actually 1482 ** different from the old. 1483 ** 1484 ** For a UNIQUE index, only conflict if the PRIMARY KEY values 1485 ** of the matched index row are different from the original PRIMARY 1486 ** KEY values of this row before the update. */ 1487 int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol; 1488 int op = OP_Ne; 1489 int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR); 1490 1491 for(i=0; i<pPk->nKeyCol; i++){ 1492 char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]); 1493 x = pPk->aiColumn[i]; 1494 if( i==(pPk->nKeyCol-1) ){ 1495 addrJump = addrUniqueOk; 1496 op = OP_Eq; 1497 } 1498 sqlite3VdbeAddOp4(v, op, 1499 regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ 1500 ); 1501 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); 1502 VdbeCoverageIf(v, op==OP_Eq); 1503 VdbeCoverageIf(v, op==OP_Ne); 1504 } 1505 } 1506 } 1507 } 1508 1509 /* Generate code that executes if the new index entry is not unique */ 1510 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail 1511 || onError==OE_Ignore || onError==OE_Replace ); 1512 switch( onError ){ 1513 case OE_Rollback: 1514 case OE_Abort: 1515 case OE_Fail: { 1516 sqlite3UniqueConstraint(pParse, onError, pIdx); 1517 break; 1518 } 1519 case OE_Ignore: { 1520 sqlite3VdbeGoto(v, ignoreDest); 1521 break; 1522 } 1523 default: { 1524 Trigger *pTrigger = 0; 1525 assert( onError==OE_Replace ); 1526 sqlite3MultiWrite(pParse); 1527 if( db->flags&SQLITE_RecTriggers ){ 1528 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0); 1529 } 1530 sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur, 1531 regR, nPkField, 0, OE_Replace, pIdx==pPk); 1532 seenReplace = 1; 1533 break; 1534 } 1535 } 1536 sqlite3VdbeResolveLabel(v, addrUniqueOk); 1537 sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn); 1538 if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField); 1539 } 1540 if( ipkTop ){ 1541 sqlite3VdbeGoto(v, ipkTop+1); 1542 sqlite3VdbeJumpHere(v, ipkBottom); 1543 } 1544 1545 *pbMayReplace = seenReplace; 1546 VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace)); 1547 } 1548 1549 /* 1550 ** This routine generates code to finish the INSERT or UPDATE operation 1551 ** that was started by a prior call to sqlite3GenerateConstraintChecks. 1552 ** A consecutive range of registers starting at regNewData contains the 1553 ** rowid and the content to be inserted. 1554 ** 1555 ** The arguments to this routine should be the same as the first six 1556 ** arguments to sqlite3GenerateConstraintChecks. 1557 */ 1558 void sqlite3CompleteInsertion( 1559 Parse *pParse, /* The parser context */ 1560 Table *pTab, /* the table into which we are inserting */ 1561 int iDataCur, /* Cursor of the canonical data source */ 1562 int iIdxCur, /* First index cursor */ 1563 int regNewData, /* Range of content */ 1564 int *aRegIdx, /* Register used by each index. 0 for unused indices */ 1565 int isUpdate, /* True for UPDATE, False for INSERT */ 1566 int appendBias, /* True if this is likely to be an append */ 1567 int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */ 1568 ){ 1569 Vdbe *v; /* Prepared statements under construction */ 1570 Index *pIdx; /* An index being inserted or updated */ 1571 u8 pik_flags; /* flag values passed to the btree insert */ 1572 int regData; /* Content registers (after the rowid) */ 1573 int regRec; /* Register holding assembled record for the table */ 1574 int i; /* Loop counter */ 1575 u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */ 1576 1577 v = sqlite3GetVdbe(pParse); 1578 assert( v!=0 ); 1579 assert( pTab->pSelect==0 ); /* This table is not a VIEW */ 1580 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ 1581 if( aRegIdx[i]==0 ) continue; 1582 bAffinityDone = 1; 1583 if( pIdx->pPartIdxWhere ){ 1584 sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2); 1585 VdbeCoverage(v); 1586 } 1587 sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i]); 1588 pik_flags = 0; 1589 if( useSeekResult ) pik_flags = OPFLAG_USESEEKRESULT; 1590 if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){ 1591 assert( pParse->nested==0 ); 1592 pik_flags |= OPFLAG_NCHANGE; 1593 } 1594 if( pik_flags ) sqlite3VdbeChangeP5(v, pik_flags); 1595 } 1596 if( !HasRowid(pTab) ) return; 1597 regData = regNewData + 1; 1598 regRec = sqlite3GetTempReg(pParse); 1599 sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec); 1600 if( !bAffinityDone ) sqlite3TableAffinity(v, pTab, 0); 1601 sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol); 1602 if( pParse->nested ){ 1603 pik_flags = 0; 1604 }else{ 1605 pik_flags = OPFLAG_NCHANGE; 1606 pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID); 1607 } 1608 if( appendBias ){ 1609 pik_flags |= OPFLAG_APPEND; 1610 } 1611 if( useSeekResult ){ 1612 pik_flags |= OPFLAG_USESEEKRESULT; 1613 } 1614 sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData); 1615 if( !pParse->nested ){ 1616 sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT); 1617 } 1618 sqlite3VdbeChangeP5(v, pik_flags); 1619 } 1620 1621 /* 1622 ** Allocate cursors for the pTab table and all its indices and generate 1623 ** code to open and initialized those cursors. 1624 ** 1625 ** The cursor for the object that contains the complete data (normally 1626 ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT 1627 ** ROWID table) is returned in *piDataCur. The first index cursor is 1628 ** returned in *piIdxCur. The number of indices is returned. 1629 ** 1630 ** Use iBase as the first cursor (either the *piDataCur for rowid tables 1631 ** or the first index for WITHOUT ROWID tables) if it is non-negative. 1632 ** If iBase is negative, then allocate the next available cursor. 1633 ** 1634 ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur. 1635 ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range 1636 ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the 1637 ** pTab->pIndex list. 1638 ** 1639 ** If pTab is a virtual table, then this routine is a no-op and the 1640 ** *piDataCur and *piIdxCur values are left uninitialized. 1641 */ 1642 int sqlite3OpenTableAndIndices( 1643 Parse *pParse, /* Parsing context */ 1644 Table *pTab, /* Table to be opened */ 1645 int op, /* OP_OpenRead or OP_OpenWrite */ 1646 int iBase, /* Use this for the table cursor, if there is one */ 1647 u8 *aToOpen, /* If not NULL: boolean for each table and index */ 1648 int *piDataCur, /* Write the database source cursor number here */ 1649 int *piIdxCur /* Write the first index cursor number here */ 1650 ){ 1651 int i; 1652 int iDb; 1653 int iDataCur; 1654 Index *pIdx; 1655 Vdbe *v; 1656 1657 assert( op==OP_OpenRead || op==OP_OpenWrite ); 1658 if( IsVirtual(pTab) ){ 1659 /* This routine is a no-op for virtual tables. Leave the output 1660 ** variables *piDataCur and *piIdxCur uninitialized so that valgrind 1661 ** can detect if they are used by mistake in the caller. */ 1662 return 0; 1663 } 1664 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 1665 v = sqlite3GetVdbe(pParse); 1666 assert( v!=0 ); 1667 if( iBase<0 ) iBase = pParse->nTab; 1668 iDataCur = iBase++; 1669 if( piDataCur ) *piDataCur = iDataCur; 1670 if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){ 1671 sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op); 1672 }else{ 1673 sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName); 1674 } 1675 if( piIdxCur ) *piIdxCur = iBase; 1676 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ 1677 int iIdxCur = iBase++; 1678 assert( pIdx->pSchema==pTab->pSchema ); 1679 if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) && piDataCur ){ 1680 *piDataCur = iIdxCur; 1681 } 1682 if( aToOpen==0 || aToOpen[i+1] ){ 1683 sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb); 1684 sqlite3VdbeSetP4KeyInfo(pParse, pIdx); 1685 VdbeComment((v, "%s", pIdx->zName)); 1686 } 1687 } 1688 if( iBase>pParse->nTab ) pParse->nTab = iBase; 1689 return i; 1690 } 1691 1692 1693 #ifdef SQLITE_TEST 1694 /* 1695 ** The following global variable is incremented whenever the 1696 ** transfer optimization is used. This is used for testing 1697 ** purposes only - to make sure the transfer optimization really 1698 ** is happening when it is supposed to. 1699 */ 1700 int sqlite3_xferopt_count; 1701 #endif /* SQLITE_TEST */ 1702 1703 1704 #ifndef SQLITE_OMIT_XFER_OPT 1705 /* 1706 ** Check to collation names to see if they are compatible. 1707 */ 1708 static int xferCompatibleCollation(const char *z1, const char *z2){ 1709 if( z1==0 ){ 1710 return z2==0; 1711 } 1712 if( z2==0 ){ 1713 return 0; 1714 } 1715 return sqlite3StrICmp(z1, z2)==0; 1716 } 1717 1718 1719 /* 1720 ** Check to see if index pSrc is compatible as a source of data 1721 ** for index pDest in an insert transfer optimization. The rules 1722 ** for a compatible index: 1723 ** 1724 ** * The index is over the same set of columns 1725 ** * The same DESC and ASC markings occurs on all columns 1726 ** * The same onError processing (OE_Abort, OE_Ignore, etc) 1727 ** * The same collating sequence on each column 1728 ** * The index has the exact same WHERE clause 1729 */ 1730 static int xferCompatibleIndex(Index *pDest, Index *pSrc){ 1731 int i; 1732 assert( pDest && pSrc ); 1733 assert( pDest->pTable!=pSrc->pTable ); 1734 if( pDest->nKeyCol!=pSrc->nKeyCol ){ 1735 return 0; /* Different number of columns */ 1736 } 1737 if( pDest->onError!=pSrc->onError ){ 1738 return 0; /* Different conflict resolution strategies */ 1739 } 1740 for(i=0; i<pSrc->nKeyCol; i++){ 1741 if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){ 1742 return 0; /* Different columns indexed */ 1743 } 1744 if( pSrc->aiColumn[i]==(-2) ){ 1745 assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 ); 1746 if( sqlite3ExprCompare(pSrc->aColExpr->a[i].pExpr, 1747 pDest->aColExpr->a[i].pExpr, -1)!=0 ){ 1748 return 0; /* Different expressions in the index */ 1749 } 1750 } 1751 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){ 1752 return 0; /* Different sort orders */ 1753 } 1754 if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){ 1755 return 0; /* Different collating sequences */ 1756 } 1757 } 1758 if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){ 1759 return 0; /* Different WHERE clauses */ 1760 } 1761 1762 /* If no test above fails then the indices must be compatible */ 1763 return 1; 1764 } 1765 1766 /* 1767 ** Attempt the transfer optimization on INSERTs of the form 1768 ** 1769 ** INSERT INTO tab1 SELECT * FROM tab2; 1770 ** 1771 ** The xfer optimization transfers raw records from tab2 over to tab1. 1772 ** Columns are not decoded and reassembled, which greatly improves 1773 ** performance. Raw index records are transferred in the same way. 1774 ** 1775 ** The xfer optimization is only attempted if tab1 and tab2 are compatible. 1776 ** There are lots of rules for determining compatibility - see comments 1777 ** embedded in the code for details. 1778 ** 1779 ** This routine returns TRUE if the optimization is guaranteed to be used. 1780 ** Sometimes the xfer optimization will only work if the destination table 1781 ** is empty - a factor that can only be determined at run-time. In that 1782 ** case, this routine generates code for the xfer optimization but also 1783 ** does a test to see if the destination table is empty and jumps over the 1784 ** xfer optimization code if the test fails. In that case, this routine 1785 ** returns FALSE so that the caller will know to go ahead and generate 1786 ** an unoptimized transfer. This routine also returns FALSE if there 1787 ** is no chance that the xfer optimization can be applied. 1788 ** 1789 ** This optimization is particularly useful at making VACUUM run faster. 1790 */ 1791 static int xferOptimization( 1792 Parse *pParse, /* Parser context */ 1793 Table *pDest, /* The table we are inserting into */ 1794 Select *pSelect, /* A SELECT statement to use as the data source */ 1795 int onError, /* How to handle constraint errors */ 1796 int iDbDest /* The database of pDest */ 1797 ){ 1798 sqlite3 *db = pParse->db; 1799 ExprList *pEList; /* The result set of the SELECT */ 1800 Table *pSrc; /* The table in the FROM clause of SELECT */ 1801 Index *pSrcIdx, *pDestIdx; /* Source and destination indices */ 1802 struct SrcList_item *pItem; /* An element of pSelect->pSrc */ 1803 int i; /* Loop counter */ 1804 int iDbSrc; /* The database of pSrc */ 1805 int iSrc, iDest; /* Cursors from source and destination */ 1806 int addr1, addr2; /* Loop addresses */ 1807 int emptyDestTest = 0; /* Address of test for empty pDest */ 1808 int emptySrcTest = 0; /* Address of test for empty pSrc */ 1809 Vdbe *v; /* The VDBE we are building */ 1810 int regAutoinc; /* Memory register used by AUTOINC */ 1811 int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */ 1812 int regData, regRowid; /* Registers holding data and rowid */ 1813 1814 if( pSelect==0 ){ 1815 return 0; /* Must be of the form INSERT INTO ... SELECT ... */ 1816 } 1817 if( pParse->pWith || pSelect->pWith ){ 1818 /* Do not attempt to process this query if there are an WITH clauses 1819 ** attached to it. Proceeding may generate a false "no such table: xxx" 1820 ** error if pSelect reads from a CTE named "xxx". */ 1821 return 0; 1822 } 1823 if( sqlite3TriggerList(pParse, pDest) ){ 1824 return 0; /* tab1 must not have triggers */ 1825 } 1826 #ifndef SQLITE_OMIT_VIRTUALTABLE 1827 if( pDest->tabFlags & TF_Virtual ){ 1828 return 0; /* tab1 must not be a virtual table */ 1829 } 1830 #endif 1831 if( onError==OE_Default ){ 1832 if( pDest->iPKey>=0 ) onError = pDest->keyConf; 1833 if( onError==OE_Default ) onError = OE_Abort; 1834 } 1835 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */ 1836 if( pSelect->pSrc->nSrc!=1 ){ 1837 return 0; /* FROM clause must have exactly one term */ 1838 } 1839 if( pSelect->pSrc->a[0].pSelect ){ 1840 return 0; /* FROM clause cannot contain a subquery */ 1841 } 1842 if( pSelect->pWhere ){ 1843 return 0; /* SELECT may not have a WHERE clause */ 1844 } 1845 if( pSelect->pOrderBy ){ 1846 return 0; /* SELECT may not have an ORDER BY clause */ 1847 } 1848 /* Do not need to test for a HAVING clause. If HAVING is present but 1849 ** there is no ORDER BY, we will get an error. */ 1850 if( pSelect->pGroupBy ){ 1851 return 0; /* SELECT may not have a GROUP BY clause */ 1852 } 1853 if( pSelect->pLimit ){ 1854 return 0; /* SELECT may not have a LIMIT clause */ 1855 } 1856 assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */ 1857 if( pSelect->pPrior ){ 1858 return 0; /* SELECT may not be a compound query */ 1859 } 1860 if( pSelect->selFlags & SF_Distinct ){ 1861 return 0; /* SELECT may not be DISTINCT */ 1862 } 1863 pEList = pSelect->pEList; 1864 assert( pEList!=0 ); 1865 if( pEList->nExpr!=1 ){ 1866 return 0; /* The result set must have exactly one column */ 1867 } 1868 assert( pEList->a[0].pExpr ); 1869 if( pEList->a[0].pExpr->op!=TK_ALL ){ 1870 return 0; /* The result set must be the special operator "*" */ 1871 } 1872 1873 /* At this point we have established that the statement is of the 1874 ** correct syntactic form to participate in this optimization. Now 1875 ** we have to check the semantics. 1876 */ 1877 pItem = pSelect->pSrc->a; 1878 pSrc = sqlite3LocateTableItem(pParse, 0, pItem); 1879 if( pSrc==0 ){ 1880 return 0; /* FROM clause does not contain a real table */ 1881 } 1882 if( pSrc==pDest ){ 1883 return 0; /* tab1 and tab2 may not be the same table */ 1884 } 1885 if( HasRowid(pDest)!=HasRowid(pSrc) ){ 1886 return 0; /* source and destination must both be WITHOUT ROWID or not */ 1887 } 1888 #ifndef SQLITE_OMIT_VIRTUALTABLE 1889 if( pSrc->tabFlags & TF_Virtual ){ 1890 return 0; /* tab2 must not be a virtual table */ 1891 } 1892 #endif 1893 if( pSrc->pSelect ){ 1894 return 0; /* tab2 may not be a view */ 1895 } 1896 if( pDest->nCol!=pSrc->nCol ){ 1897 return 0; /* Number of columns must be the same in tab1 and tab2 */ 1898 } 1899 if( pDest->iPKey!=pSrc->iPKey ){ 1900 return 0; /* Both tables must have the same INTEGER PRIMARY KEY */ 1901 } 1902 for(i=0; i<pDest->nCol; i++){ 1903 Column *pDestCol = &pDest->aCol[i]; 1904 Column *pSrcCol = &pSrc->aCol[i]; 1905 if( pDestCol->affinity!=pSrcCol->affinity ){ 1906 return 0; /* Affinity must be the same on all columns */ 1907 } 1908 if( !xferCompatibleCollation(pDestCol->zColl, pSrcCol->zColl) ){ 1909 return 0; /* Collating sequence must be the same on all columns */ 1910 } 1911 if( pDestCol->notNull && !pSrcCol->notNull ){ 1912 return 0; /* tab2 must be NOT NULL if tab1 is */ 1913 } 1914 /* Default values for second and subsequent columns need to match. */ 1915 if( i>0 1916 && ((pDestCol->zDflt==0)!=(pSrcCol->zDflt==0) 1917 || (pDestCol->zDflt && strcmp(pDestCol->zDflt, pSrcCol->zDflt)!=0)) 1918 ){ 1919 return 0; /* Default values must be the same for all columns */ 1920 } 1921 } 1922 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ 1923 if( IsUniqueIndex(pDestIdx) ){ 1924 destHasUniqueIdx = 1; 1925 } 1926 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){ 1927 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; 1928 } 1929 if( pSrcIdx==0 ){ 1930 return 0; /* pDestIdx has no corresponding index in pSrc */ 1931 } 1932 } 1933 #ifndef SQLITE_OMIT_CHECK 1934 if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){ 1935 return 0; /* Tables have different CHECK constraints. Ticket #2252 */ 1936 } 1937 #endif 1938 #ifndef SQLITE_OMIT_FOREIGN_KEY 1939 /* Disallow the transfer optimization if the destination table constains 1940 ** any foreign key constraints. This is more restrictive than necessary. 1941 ** But the main beneficiary of the transfer optimization is the VACUUM 1942 ** command, and the VACUUM command disables foreign key constraints. So 1943 ** the extra complication to make this rule less restrictive is probably 1944 ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e] 1945 */ 1946 if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){ 1947 return 0; 1948 } 1949 #endif 1950 if( (db->flags & SQLITE_CountRows)!=0 ){ 1951 return 0; /* xfer opt does not play well with PRAGMA count_changes */ 1952 } 1953 1954 /* If we get this far, it means that the xfer optimization is at 1955 ** least a possibility, though it might only work if the destination 1956 ** table (tab1) is initially empty. 1957 */ 1958 #ifdef SQLITE_TEST 1959 sqlite3_xferopt_count++; 1960 #endif 1961 iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema); 1962 v = sqlite3GetVdbe(pParse); 1963 sqlite3CodeVerifySchema(pParse, iDbSrc); 1964 iSrc = pParse->nTab++; 1965 iDest = pParse->nTab++; 1966 regAutoinc = autoIncBegin(pParse, iDbDest, pDest); 1967 regData = sqlite3GetTempReg(pParse); 1968 regRowid = sqlite3GetTempReg(pParse); 1969 sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite); 1970 assert( HasRowid(pDest) || destHasUniqueIdx ); 1971 if( (db->flags & SQLITE_Vacuum)==0 && ( 1972 (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */ 1973 || destHasUniqueIdx /* (2) */ 1974 || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */ 1975 )){ 1976 /* In some circumstances, we are able to run the xfer optimization 1977 ** only if the destination table is initially empty. Unless the 1978 ** SQLITE_Vacuum flag is set, this block generates code to make 1979 ** that determination. If SQLITE_Vacuum is set, then the destination 1980 ** table is always empty. 1981 ** 1982 ** Conditions under which the destination must be empty: 1983 ** 1984 ** (1) There is no INTEGER PRIMARY KEY but there are indices. 1985 ** (If the destination is not initially empty, the rowid fields 1986 ** of index entries might need to change.) 1987 ** 1988 ** (2) The destination has a unique index. (The xfer optimization 1989 ** is unable to test uniqueness.) 1990 ** 1991 ** (3) onError is something other than OE_Abort and OE_Rollback. 1992 */ 1993 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v); 1994 emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto); 1995 sqlite3VdbeJumpHere(v, addr1); 1996 } 1997 if( HasRowid(pSrc) ){ 1998 sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead); 1999 emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v); 2000 if( pDest->iPKey>=0 ){ 2001 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); 2002 addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid); 2003 VdbeCoverage(v); 2004 sqlite3RowidConstraint(pParse, onError, pDest); 2005 sqlite3VdbeJumpHere(v, addr2); 2006 autoIncStep(pParse, regAutoinc, regRowid); 2007 }else if( pDest->pIndex==0 ){ 2008 addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid); 2009 }else{ 2010 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); 2011 assert( (pDest->tabFlags & TF_Autoincrement)==0 ); 2012 } 2013 sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData); 2014 sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid); 2015 sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND); 2016 sqlite3VdbeChangeP4(v, -1, pDest->zName, 0); 2017 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v); 2018 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); 2019 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); 2020 }else{ 2021 sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName); 2022 sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName); 2023 } 2024 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ 2025 u8 idxInsFlags = 0; 2026 for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){ 2027 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; 2028 } 2029 assert( pSrcIdx ); 2030 sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc); 2031 sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx); 2032 VdbeComment((v, "%s", pSrcIdx->zName)); 2033 sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest); 2034 sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx); 2035 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR); 2036 VdbeComment((v, "%s", pDestIdx->zName)); 2037 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v); 2038 sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData); 2039 if( db->flags & SQLITE_Vacuum ){ 2040 /* This INSERT command is part of a VACUUM operation, which guarantees 2041 ** that the destination table is empty. If all indexed columns use 2042 ** collation sequence BINARY, then it can also be assumed that the 2043 ** index will be populated by inserting keys in strictly sorted 2044 ** order. In this case, instead of seeking within the b-tree as part 2045 ** of every OP_IdxInsert opcode, an OP_Last is added before the 2046 ** OP_IdxInsert to seek to the point within the b-tree where each key 2047 ** should be inserted. This is faster. 2048 ** 2049 ** If any of the indexed columns use a collation sequence other than 2050 ** BINARY, this optimization is disabled. This is because the user 2051 ** might change the definition of a collation sequence and then run 2052 ** a VACUUM command. In that case keys may not be written in strictly 2053 ** sorted order. */ 2054 for(i=0; i<pSrcIdx->nColumn; i++){ 2055 char *zColl = pSrcIdx->azColl[i]; 2056 assert( zColl!=0 ); 2057 if( sqlite3_stricmp("BINARY", zColl) ) break; 2058 } 2059 if( i==pSrcIdx->nColumn ){ 2060 idxInsFlags = OPFLAG_USESEEKRESULT; 2061 sqlite3VdbeAddOp3(v, OP_Last, iDest, 0, -1); 2062 } 2063 } 2064 if( !HasRowid(pSrc) && pDestIdx->idxType==2 ){ 2065 idxInsFlags |= OPFLAG_NCHANGE; 2066 } 2067 sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1); 2068 sqlite3VdbeChangeP5(v, idxInsFlags); 2069 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v); 2070 sqlite3VdbeJumpHere(v, addr1); 2071 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); 2072 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); 2073 } 2074 if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest); 2075 sqlite3ReleaseTempReg(pParse, regRowid); 2076 sqlite3ReleaseTempReg(pParse, regData); 2077 if( emptyDestTest ){ 2078 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0); 2079 sqlite3VdbeJumpHere(v, emptyDestTest); 2080 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); 2081 return 0; 2082 }else{ 2083 return 1; 2084 } 2085 } 2086 #endif /* SQLITE_OMIT_XFER_OPT */ 2087