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