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