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