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 ** $Id: insert.c,v 1.247 2008/07/08 23:40:20 drh Exp $ 16 */ 17 #include "sqliteInt.h" 18 19 /* 20 ** Set P4 of the most recently inserted opcode to a column affinity 21 ** string for index pIdx. A column affinity string has one character 22 ** for each column in the table, according to the affinity of the column: 23 ** 24 ** Character Column affinity 25 ** ------------------------------ 26 ** 'a' TEXT 27 ** 'b' NONE 28 ** 'c' NUMERIC 29 ** 'd' INTEGER 30 ** 'e' REAL 31 ** 32 ** An extra 'b' is appended to the end of the string to cover the 33 ** rowid that appears as the last column in every index. 34 */ 35 void sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){ 36 if( !pIdx->zColAff ){ 37 /* The first time a column affinity string for a particular index is 38 ** required, it is allocated and populated here. It is then stored as 39 ** a member of the Index structure for subsequent use. 40 ** 41 ** The column affinity string will eventually be deleted by 42 ** sqliteDeleteIndex() when the Index structure itself is cleaned 43 ** up. 44 */ 45 int n; 46 Table *pTab = pIdx->pTable; 47 sqlite3 *db = sqlite3VdbeDb(v); 48 pIdx->zColAff = (char *)sqlite3DbMallocRaw(db, pIdx->nColumn+2); 49 if( !pIdx->zColAff ){ 50 return; 51 } 52 for(n=0; n<pIdx->nColumn; n++){ 53 pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity; 54 } 55 pIdx->zColAff[n++] = SQLITE_AFF_NONE; 56 pIdx->zColAff[n] = 0; 57 } 58 59 sqlite3VdbeChangeP4(v, -1, pIdx->zColAff, 0); 60 } 61 62 /* 63 ** Set P4 of the most recently inserted opcode to a column affinity 64 ** string for table pTab. A column affinity string has one character 65 ** for each column indexed by the index, according to the affinity of the 66 ** column: 67 ** 68 ** Character Column affinity 69 ** ------------------------------ 70 ** 'a' TEXT 71 ** 'b' NONE 72 ** 'c' NUMERIC 73 ** 'd' INTEGER 74 ** 'e' REAL 75 */ 76 void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){ 77 /* The first time a column affinity string for a particular table 78 ** is required, it is allocated and populated here. It is then 79 ** stored as a member of the Table structure for subsequent use. 80 ** 81 ** The column affinity string will eventually be deleted by 82 ** sqlite3DeleteTable() when the Table structure itself is cleaned up. 83 */ 84 if( !pTab->zColAff ){ 85 char *zColAff; 86 int i; 87 sqlite3 *db = sqlite3VdbeDb(v); 88 89 zColAff = (char *)sqlite3DbMallocRaw(db, pTab->nCol+1); 90 if( !zColAff ){ 91 return; 92 } 93 94 for(i=0; i<pTab->nCol; i++){ 95 zColAff[i] = pTab->aCol[i].affinity; 96 } 97 zColAff[pTab->nCol] = '\0'; 98 99 pTab->zColAff = zColAff; 100 } 101 102 sqlite3VdbeChangeP4(v, -1, pTab->zColAff, 0); 103 } 104 105 /* 106 ** Return non-zero if the table pTab in database iDb or any of its indices 107 ** have been opened at any point in the VDBE program beginning at location 108 ** iStartAddr throught the end of the program. This is used to see if 109 ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can 110 ** run without using temporary table for the results of the SELECT. 111 */ 112 static int readsTable(Vdbe *v, int iStartAddr, int iDb, Table *pTab){ 113 int i; 114 int iEnd = sqlite3VdbeCurrentAddr(v); 115 for(i=iStartAddr; i<iEnd; i++){ 116 VdbeOp *pOp = sqlite3VdbeGetOp(v, i); 117 assert( pOp!=0 ); 118 if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){ 119 Index *pIndex; 120 int tnum = pOp->p2; 121 if( tnum==pTab->tnum ){ 122 return 1; 123 } 124 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){ 125 if( tnum==pIndex->tnum ){ 126 return 1; 127 } 128 } 129 } 130 #ifndef SQLITE_OMIT_VIRTUALTABLE 131 if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pTab->pVtab ){ 132 assert( pOp->p4.pVtab!=0 ); 133 assert( pOp->p4type==P4_VTAB ); 134 return 1; 135 } 136 #endif 137 } 138 return 0; 139 } 140 141 #ifndef SQLITE_OMIT_AUTOINCREMENT 142 /* 143 ** Write out code to initialize the autoincrement logic. This code 144 ** looks up the current autoincrement value in the sqlite_sequence 145 ** table and stores that value in a register. Code generated by 146 ** autoIncStep() will keep that register holding the largest 147 ** rowid value. Code generated by autoIncEnd() will write the new 148 ** largest value of the counter back into the sqlite_sequence table. 149 ** 150 ** This routine returns the index of the mem[] cell that contains 151 ** the maximum rowid counter. 152 ** 153 ** Three consecutive registers are allocated by this routine. The 154 ** first two hold the name of the target table and the maximum rowid 155 ** inserted into the target table, respectively. 156 ** The third holds the rowid in sqlite_sequence where we will 157 ** write back the revised maximum rowid. This routine returns the 158 ** index of the second of these three registers. 159 */ 160 static int autoIncBegin( 161 Parse *pParse, /* Parsing context */ 162 int iDb, /* Index of the database holding pTab */ 163 Table *pTab /* The table we are writing to */ 164 ){ 165 int memId = 0; /* Register holding maximum rowid */ 166 if( pTab->autoInc ){ 167 Vdbe *v = pParse->pVdbe; 168 Db *pDb = &pParse->db->aDb[iDb]; 169 int iCur = pParse->nTab; 170 int addr; /* Address of the top of the loop */ 171 assert( v ); 172 pParse->nMem++; /* Holds name of table */ 173 memId = ++pParse->nMem; 174 pParse->nMem++; 175 sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenRead); 176 addr = sqlite3VdbeCurrentAddr(v); 177 sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, pTab->zName, 0); 178 sqlite3VdbeAddOp2(v, OP_Rewind, iCur, addr+9); 179 sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, memId); 180 sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId); 181 sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL); 182 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, memId+1); 183 sqlite3VdbeAddOp3(v, OP_Column, iCur, 1, memId); 184 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9); 185 sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+2); 186 sqlite3VdbeAddOp2(v, OP_Integer, 0, memId); 187 sqlite3VdbeAddOp2(v, OP_Close, iCur, 0); 188 } 189 return memId; 190 } 191 192 /* 193 ** Update the maximum rowid for an autoincrement calculation. 194 ** 195 ** This routine should be called when the top of the stack holds a 196 ** new rowid that is about to be inserted. If that new rowid is 197 ** larger than the maximum rowid in the memId memory cell, then the 198 ** memory cell is updated. The stack is unchanged. 199 */ 200 static void autoIncStep(Parse *pParse, int memId, int regRowid){ 201 if( memId>0 ){ 202 sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid); 203 } 204 } 205 206 /* 207 ** After doing one or more inserts, the maximum rowid is stored 208 ** in reg[memId]. Generate code to write this value back into the 209 ** the sqlite_sequence table. 210 */ 211 static void autoIncEnd( 212 Parse *pParse, /* The parsing context */ 213 int iDb, /* Index of the database holding pTab */ 214 Table *pTab, /* Table we are inserting into */ 215 int memId /* Memory cell holding the maximum rowid */ 216 ){ 217 if( pTab->autoInc ){ 218 int iCur = pParse->nTab; 219 Vdbe *v = pParse->pVdbe; 220 Db *pDb = &pParse->db->aDb[iDb]; 221 int j1; 222 int iRec = ++pParse->nMem; /* Memory cell used for record */ 223 224 assert( v ); 225 sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenWrite); 226 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1); 227 sqlite3VdbeAddOp2(v, OP_NewRowid, iCur, memId+1); 228 sqlite3VdbeJumpHere(v, j1); 229 sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec); 230 sqlite3VdbeAddOp3(v, OP_Insert, iCur, iRec, memId+1); 231 sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 232 sqlite3VdbeAddOp1(v, OP_Close, iCur); 233 } 234 } 235 #else 236 /* 237 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines 238 ** above are all no-ops 239 */ 240 # define autoIncBegin(A,B,C) (0) 241 # define autoIncStep(A,B,C) 242 # define autoIncEnd(A,B,C,D) 243 #endif /* SQLITE_OMIT_AUTOINCREMENT */ 244 245 246 /* Forward declaration */ 247 static int xferOptimization( 248 Parse *pParse, /* Parser context */ 249 Table *pDest, /* The table we are inserting into */ 250 Select *pSelect, /* A SELECT statement to use as the data source */ 251 int onError, /* How to handle constraint errors */ 252 int iDbDest /* The database of pDest */ 253 ); 254 255 /* 256 ** This routine is call to handle SQL of the following forms: 257 ** 258 ** insert into TABLE (IDLIST) values(EXPRLIST) 259 ** insert into TABLE (IDLIST) select 260 ** 261 ** The IDLIST following the table name is always optional. If omitted, 262 ** then a list of all columns for the table is substituted. The IDLIST 263 ** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted. 264 ** 265 ** The pList parameter holds EXPRLIST in the first form of the INSERT 266 ** statement above, and pSelect is NULL. For the second form, pList is 267 ** NULL and pSelect is a pointer to the select statement used to generate 268 ** data for the insert. 269 ** 270 ** The code generated follows one of four templates. For a simple 271 ** select with data coming from a VALUES clause, the code executes 272 ** once straight down through. Pseudo-code follows (we call this 273 ** the "1st template"): 274 ** 275 ** open write cursor to <table> and its indices 276 ** puts VALUES clause expressions onto the stack 277 ** write the resulting record into <table> 278 ** cleanup 279 ** 280 ** The three remaining templates assume the statement is of the form 281 ** 282 ** INSERT INTO <table> SELECT ... 283 ** 284 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" - 285 ** in other words if the SELECT pulls all columns from a single table 286 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and 287 ** if <table2> and <table1> are distinct tables but have identical 288 ** schemas, including all the same indices, then a special optimization 289 ** is invoked that copies raw records from <table2> over to <table1>. 290 ** See the xferOptimization() function for the implementation of this 291 ** template. This is the 2nd template. 292 ** 293 ** open a write cursor to <table> 294 ** open read cursor on <table2> 295 ** transfer all records in <table2> over to <table> 296 ** close cursors 297 ** foreach index on <table> 298 ** open a write cursor on the <table> index 299 ** open a read cursor on the corresponding <table2> index 300 ** transfer all records from the read to the write cursors 301 ** close cursors 302 ** end foreach 303 ** 304 ** The 3rd template is for when the second template does not apply 305 ** and the SELECT clause does not read from <table> at any time. 306 ** The generated code follows this template: 307 ** 308 ** EOF <- 0 309 ** X <- A 310 ** goto B 311 ** A: setup for the SELECT 312 ** loop over the rows in the SELECT 313 ** load values into registers R..R+n 314 ** yield X 315 ** end loop 316 ** cleanup after the SELECT 317 ** EOF <- 1 318 ** yield X 319 ** goto A 320 ** B: open write cursor to <table> and its indices 321 ** C: yield X 322 ** if EOF goto D 323 ** insert the select result into <table> from R..R+n 324 ** goto C 325 ** D: cleanup 326 ** 327 ** The 4th template is used if the insert statement takes its 328 ** values from a SELECT but the data is being inserted into a table 329 ** that is also read as part of the SELECT. In the third form, 330 ** we have to use a intermediate table to store the results of 331 ** the select. The template is like this: 332 ** 333 ** EOF <- 0 334 ** X <- A 335 ** goto B 336 ** A: setup for the SELECT 337 ** loop over the tables in the SELECT 338 ** load value into register R..R+n 339 ** yield X 340 ** end loop 341 ** cleanup after the SELECT 342 ** EOF <- 1 343 ** yield X 344 ** halt-error 345 ** B: open temp table 346 ** L: yield X 347 ** if EOF goto M 348 ** insert row from R..R+n into temp table 349 ** goto L 350 ** M: open write cursor to <table> and its indices 351 ** rewind temp table 352 ** C: loop over rows of intermediate table 353 ** transfer values form intermediate table into <table> 354 ** end loop 355 ** D: cleanup 356 */ 357 void sqlite3Insert( 358 Parse *pParse, /* Parser context */ 359 SrcList *pTabList, /* Name of table into which we are inserting */ 360 ExprList *pList, /* List of values to be inserted */ 361 Select *pSelect, /* A SELECT statement to use as the data source */ 362 IdList *pColumn, /* Column names corresponding to IDLIST. */ 363 int onError /* How to handle constraint errors */ 364 ){ 365 sqlite3 *db; /* The main database structure */ 366 Table *pTab; /* The table to insert into. aka TABLE */ 367 char *zTab; /* Name of the table into which we are inserting */ 368 const char *zDb; /* Name of the database holding this table */ 369 int i, j, idx; /* Loop counters */ 370 Vdbe *v; /* Generate code into this virtual machine */ 371 Index *pIdx; /* For looping over indices of the table */ 372 int nColumn; /* Number of columns in the data */ 373 int nHidden = 0; /* Number of hidden columns if TABLE is virtual */ 374 int baseCur = 0; /* VDBE Cursor number for pTab */ 375 int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */ 376 int endOfLoop; /* Label for the end of the insertion loop */ 377 int useTempTable = 0; /* Store SELECT results in intermediate table */ 378 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */ 379 int addrInsTop = 0; /* Jump to label "D" */ 380 int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */ 381 int addrSelect = 0; /* Address of coroutine that implements the SELECT */ 382 SelectDest dest; /* Destination for SELECT on rhs of INSERT */ 383 int newIdx = -1; /* Cursor for the NEW pseudo-table */ 384 int iDb; /* Index of database holding TABLE */ 385 Db *pDb; /* The database containing table being inserted into */ 386 int appendFlag = 0; /* True if the insert is likely to be an append */ 387 388 /* Register allocations */ 389 int regFromSelect; /* Base register for data coming from SELECT */ 390 int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */ 391 int regRowCount = 0; /* Memory cell used for the row counter */ 392 int regIns; /* Block of regs holding rowid+data being inserted */ 393 int regRowid; /* registers holding insert rowid */ 394 int regData; /* register holding first column to insert */ 395 int regRecord; /* Holds the assemblied row record */ 396 int regEof; /* Register recording end of SELECT data */ 397 int *aRegIdx = 0; /* One register allocated to each index */ 398 399 400 #ifndef SQLITE_OMIT_TRIGGER 401 int isView; /* True if attempting to insert into a view */ 402 int triggers_exist = 0; /* True if there are FOR EACH ROW triggers */ 403 #endif 404 405 db = pParse->db; 406 if( pParse->nErr || db->mallocFailed ){ 407 goto insert_cleanup; 408 } 409 410 /* Locate the table into which we will be inserting new information. 411 */ 412 assert( pTabList->nSrc==1 ); 413 zTab = pTabList->a[0].zName; 414 if( zTab==0 ) goto insert_cleanup; 415 pTab = sqlite3SrcListLookup(pParse, pTabList); 416 if( pTab==0 ){ 417 goto insert_cleanup; 418 } 419 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 420 assert( iDb<db->nDb ); 421 pDb = &db->aDb[iDb]; 422 zDb = pDb->zName; 423 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){ 424 goto insert_cleanup; 425 } 426 427 /* Figure out if we have any triggers and if the table being 428 ** inserted into is a view 429 */ 430 #ifndef SQLITE_OMIT_TRIGGER 431 triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0); 432 isView = pTab->pSelect!=0; 433 #else 434 # define triggers_exist 0 435 # define isView 0 436 #endif 437 #ifdef SQLITE_OMIT_VIEW 438 # undef isView 439 # define isView 0 440 #endif 441 442 /* Ensure that: 443 * (a) the table is not read-only, 444 * (b) that if it is a view then ON INSERT triggers exist 445 */ 446 if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){ 447 goto insert_cleanup; 448 } 449 assert( pTab!=0 ); 450 451 /* If pTab is really a view, make sure it has been initialized. 452 ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual 453 ** module table). 454 */ 455 if( sqlite3ViewGetColumnNames(pParse, pTab) ){ 456 goto insert_cleanup; 457 } 458 459 /* Allocate a VDBE 460 */ 461 v = sqlite3GetVdbe(pParse); 462 if( v==0 ) goto insert_cleanup; 463 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v); 464 sqlite3BeginWriteOperation(pParse, pSelect || triggers_exist, iDb); 465 466 /* if there are row triggers, allocate a temp table for new.* references. */ 467 if( triggers_exist ){ 468 newIdx = pParse->nTab++; 469 } 470 471 #ifndef SQLITE_OMIT_XFER_OPT 472 /* If the statement is of the form 473 ** 474 ** INSERT INTO <table1> SELECT * FROM <table2>; 475 ** 476 ** Then special optimizations can be applied that make the transfer 477 ** very fast and which reduce fragmentation of indices. 478 ** 479 ** This is the 2nd template. 480 */ 481 if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){ 482 assert( !triggers_exist ); 483 assert( pList==0 ); 484 goto insert_cleanup; 485 } 486 #endif /* SQLITE_OMIT_XFER_OPT */ 487 488 /* If this is an AUTOINCREMENT table, look up the sequence number in the 489 ** sqlite_sequence table and store it in memory cell regAutoinc. 490 */ 491 regAutoinc = autoIncBegin(pParse, iDb, pTab); 492 493 /* Figure out how many columns of data are supplied. If the data 494 ** is coming from a SELECT statement, then generate a co-routine that 495 ** produces a single row of the SELECT on each invocation. The 496 ** co-routine is the common header to the 3rd and 4th templates. 497 */ 498 if( pSelect ){ 499 /* Data is coming from a SELECT. Generate code to implement that SELECT 500 ** as a co-routine. The code is common to both the 3rd and 4th 501 ** templates: 502 ** 503 ** EOF <- 0 504 ** X <- A 505 ** goto B 506 ** A: setup for the SELECT 507 ** loop over the tables in the SELECT 508 ** load value into register R..R+n 509 ** yield X 510 ** end loop 511 ** cleanup after the SELECT 512 ** EOF <- 1 513 ** yield X 514 ** halt-error 515 ** 516 ** On each invocation of the co-routine, it puts a single row of the 517 ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1. 518 ** (These output registers are allocated by sqlite3Select().) When 519 ** the SELECT completes, it sets the EOF flag stored in regEof. 520 */ 521 int rc, j1; 522 523 regEof = ++pParse->nMem; 524 sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof); /* EOF <- 0 */ 525 VdbeComment((v, "SELECT eof flag")); 526 sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem); 527 addrSelect = sqlite3VdbeCurrentAddr(v)+2; 528 sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm); 529 j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0); 530 VdbeComment((v, "Jump over SELECT coroutine")); 531 532 /* Resolve the expressions in the SELECT statement and execute it. */ 533 rc = sqlite3Select(pParse, pSelect, &dest, 0, 0, 0); 534 if( rc || pParse->nErr || db->mallocFailed ){ 535 goto insert_cleanup; 536 } 537 sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof); /* EOF <- 1 */ 538 sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm); /* yield X */ 539 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort); 540 VdbeComment((v, "End of SELECT coroutine")); 541 sqlite3VdbeJumpHere(v, j1); /* label B: */ 542 543 regFromSelect = dest.iMem; 544 assert( pSelect->pEList ); 545 nColumn = pSelect->pEList->nExpr; 546 assert( dest.nMem==nColumn ); 547 548 /* Set useTempTable to TRUE if the result of the SELECT statement 549 ** should be written into a temporary table (template 4). Set to 550 ** FALSE if each* row of the SELECT can be written directly into 551 ** the destination table (template 3). 552 ** 553 ** A temp table must be used if the table being updated is also one 554 ** of the tables being read by the SELECT statement. Also use a 555 ** temp table in the case of row triggers. 556 */ 557 if( triggers_exist || readsTable(v, addrSelect, iDb, pTab) ){ 558 useTempTable = 1; 559 } 560 561 if( useTempTable ){ 562 /* Invoke the coroutine to extract information from the SELECT 563 ** and add it to a transient table srcTab. The code generated 564 ** here is from the 4th template: 565 ** 566 ** B: open temp table 567 ** L: yield X 568 ** if EOF goto M 569 ** insert row from R..R+n into temp table 570 ** goto L 571 ** M: ... 572 */ 573 int regRec; /* Register to hold packed record */ 574 int regRowid; /* Register to hold temp table ROWID */ 575 int addrTop; /* Label "L" */ 576 int addrIf; /* Address of jump to M */ 577 578 srcTab = pParse->nTab++; 579 regRec = sqlite3GetTempReg(pParse); 580 regRowid = sqlite3GetTempReg(pParse); 581 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn); 582 addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm); 583 addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof); 584 sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec); 585 sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regRowid); 586 sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regRowid); 587 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop); 588 sqlite3VdbeJumpHere(v, addrIf); 589 sqlite3ReleaseTempReg(pParse, regRec); 590 sqlite3ReleaseTempReg(pParse, regRowid); 591 } 592 }else{ 593 /* This is the case if the data for the INSERT is coming from a VALUES 594 ** clause 595 */ 596 NameContext sNC; 597 memset(&sNC, 0, sizeof(sNC)); 598 sNC.pParse = pParse; 599 srcTab = -1; 600 assert( useTempTable==0 ); 601 nColumn = pList ? pList->nExpr : 0; 602 for(i=0; i<nColumn; i++){ 603 if( sqlite3ExprResolveNames(&sNC, pList->a[i].pExpr) ){ 604 goto insert_cleanup; 605 } 606 } 607 } 608 609 /* Make sure the number of columns in the source data matches the number 610 ** of columns to be inserted into the table. 611 */ 612 if( IsVirtual(pTab) ){ 613 for(i=0; i<pTab->nCol; i++){ 614 nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0); 615 } 616 } 617 if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){ 618 sqlite3ErrorMsg(pParse, 619 "table %S has %d columns but %d values were supplied", 620 pTabList, 0, pTab->nCol, nColumn); 621 goto insert_cleanup; 622 } 623 if( pColumn!=0 && nColumn!=pColumn->nId ){ 624 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId); 625 goto insert_cleanup; 626 } 627 628 /* If the INSERT statement included an IDLIST term, then make sure 629 ** all elements of the IDLIST really are columns of the table and 630 ** remember the column indices. 631 ** 632 ** If the table has an INTEGER PRIMARY KEY column and that column 633 ** is named in the IDLIST, then record in the keyColumn variable 634 ** the index into IDLIST of the primary key column. keyColumn is 635 ** the index of the primary key as it appears in IDLIST, not as 636 ** is appears in the original table. (The index of the primary 637 ** key in the original table is pTab->iPKey.) 638 */ 639 if( pColumn ){ 640 for(i=0; i<pColumn->nId; i++){ 641 pColumn->a[i].idx = -1; 642 } 643 for(i=0; i<pColumn->nId; i++){ 644 for(j=0; j<pTab->nCol; j++){ 645 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){ 646 pColumn->a[i].idx = j; 647 if( j==pTab->iPKey ){ 648 keyColumn = i; 649 } 650 break; 651 } 652 } 653 if( j>=pTab->nCol ){ 654 if( sqlite3IsRowid(pColumn->a[i].zName) ){ 655 keyColumn = i; 656 }else{ 657 sqlite3ErrorMsg(pParse, "table %S has no column named %s", 658 pTabList, 0, pColumn->a[i].zName); 659 pParse->nErr++; 660 goto insert_cleanup; 661 } 662 } 663 } 664 } 665 666 /* If there is no IDLIST term but the table has an integer primary 667 ** key, the set the keyColumn variable to the primary key column index 668 ** in the original table definition. 669 */ 670 if( pColumn==0 && nColumn>0 ){ 671 keyColumn = pTab->iPKey; 672 } 673 674 /* Open the temp table for FOR EACH ROW triggers 675 */ 676 if( triggers_exist ){ 677 sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol); 678 sqlite3VdbeAddOp2(v, OP_OpenPseudo, newIdx, 0); 679 } 680 681 /* Initialize the count of rows to be inserted 682 */ 683 if( db->flags & SQLITE_CountRows ){ 684 regRowCount = ++pParse->nMem; 685 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount); 686 } 687 688 /* If this is not a view, open the table and and all indices */ 689 if( !isView ){ 690 int nIdx; 691 int i; 692 693 baseCur = pParse->nTab; 694 nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite); 695 aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1)); 696 if( aRegIdx==0 ){ 697 goto insert_cleanup; 698 } 699 for(i=0; i<nIdx; i++){ 700 aRegIdx[i] = ++pParse->nMem; 701 } 702 } 703 704 /* This is the top of the main insertion loop */ 705 if( useTempTable ){ 706 /* This block codes the top of loop only. The complete loop is the 707 ** following pseudocode (template 4): 708 ** 709 ** rewind temp table 710 ** C: loop over rows of intermediate table 711 ** transfer values form intermediate table into <table> 712 ** end loop 713 ** D: ... 714 */ 715 addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); 716 addrCont = sqlite3VdbeCurrentAddr(v); 717 }else if( pSelect ){ 718 /* This block codes the top of loop only. The complete loop is the 719 ** following pseudocode (template 3): 720 ** 721 ** C: yield X 722 ** if EOF goto D 723 ** insert the select result into <table> from R..R+n 724 ** goto C 725 ** D: ... 726 */ 727 addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm); 728 addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof); 729 } 730 731 /* Allocate registers for holding the rowid of the new row, 732 ** the content of the new row, and the assemblied row record. 733 */ 734 regRecord = ++pParse->nMem; 735 regRowid = regIns = pParse->nMem+1; 736 pParse->nMem += pTab->nCol + 1; 737 if( IsVirtual(pTab) ){ 738 regRowid++; 739 pParse->nMem++; 740 } 741 regData = regRowid+1; 742 743 /* Run the BEFORE and INSTEAD OF triggers, if there are any 744 */ 745 endOfLoop = sqlite3VdbeMakeLabel(v); 746 if( triggers_exist & TRIGGER_BEFORE ){ 747 int regRowid; 748 int regCols; 749 int regRec; 750 751 /* build the NEW.* reference row. Note that if there is an INTEGER 752 ** PRIMARY KEY into which a NULL is being inserted, that NULL will be 753 ** translated into a unique ID for the row. But on a BEFORE trigger, 754 ** we do not know what the unique ID will be (because the insert has 755 ** not happened yet) so we substitute a rowid of -1 756 */ 757 regRowid = sqlite3GetTempReg(pParse); 758 if( keyColumn<0 ){ 759 sqlite3VdbeAddOp2(v, OP_Integer, -1, regRowid); 760 }else if( useTempTable ){ 761 sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid); 762 }else{ 763 int j1; 764 assert( pSelect==0 ); /* Otherwise useTempTable is true */ 765 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid); 766 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); 767 sqlite3VdbeAddOp2(v, OP_Integer, -1, regRowid); 768 sqlite3VdbeJumpHere(v, j1); 769 sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); 770 } 771 772 /* Cannot have triggers on a virtual table. If it were possible, 773 ** this block would have to account for hidden column. 774 */ 775 assert(!IsVirtual(pTab)); 776 777 /* Create the new column data 778 */ 779 regCols = sqlite3GetTempRange(pParse, pTab->nCol); 780 for(i=0; i<pTab->nCol; i++){ 781 if( pColumn==0 ){ 782 j = i; 783 }else{ 784 for(j=0; j<pColumn->nId; j++){ 785 if( pColumn->a[j].idx==i ) break; 786 } 787 } 788 if( pColumn && j>=pColumn->nId ){ 789 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i); 790 }else if( useTempTable ){ 791 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i); 792 }else{ 793 assert( pSelect==0 ); /* Otherwise useTempTable is true */ 794 sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i); 795 } 796 } 797 regRec = sqlite3GetTempReg(pParse); 798 sqlite3VdbeAddOp3(v, OP_MakeRecord, regCols, pTab->nCol, regRec); 799 800 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger, 801 ** do not attempt any conversions before assembling the record. 802 ** If this is a real table, attempt conversions as required by the 803 ** table column affinities. 804 */ 805 if( !isView ){ 806 sqlite3TableAffinityStr(v, pTab); 807 } 808 sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regRowid); 809 sqlite3ReleaseTempReg(pParse, regRec); 810 sqlite3ReleaseTempReg(pParse, regRowid); 811 sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol); 812 813 /* Fire BEFORE or INSTEAD OF triggers */ 814 if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_BEFORE, pTab, 815 newIdx, -1, onError, endOfLoop, 0, 0) ){ 816 goto insert_cleanup; 817 } 818 } 819 820 /* Push the record number for the new entry onto the stack. The 821 ** record number is a randomly generate integer created by NewRowid 822 ** except when the table has an INTEGER PRIMARY KEY column, in which 823 ** case the record number is the same as that column. 824 */ 825 if( !isView ){ 826 if( IsVirtual(pTab) ){ 827 /* The row that the VUpdate opcode will delete: none */ 828 sqlite3VdbeAddOp2(v, OP_Null, 0, regIns); 829 } 830 if( keyColumn>=0 ){ 831 if( useTempTable ){ 832 sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid); 833 }else if( pSelect ){ 834 sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid); 835 }else{ 836 VdbeOp *pOp; 837 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid); 838 pOp = sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v) - 1); 839 if( pOp && pOp->opcode==OP_Null && !IsVirtual(pTab) ){ 840 appendFlag = 1; 841 pOp->opcode = OP_NewRowid; 842 pOp->p1 = baseCur; 843 pOp->p2 = regRowid; 844 pOp->p3 = regAutoinc; 845 } 846 } 847 /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid 848 ** to generate a unique primary key value. 849 */ 850 if( !appendFlag ){ 851 int j1; 852 if( !IsVirtual(pTab) ){ 853 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); 854 sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc); 855 sqlite3VdbeJumpHere(v, j1); 856 }else{ 857 j1 = sqlite3VdbeCurrentAddr(v); 858 sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2); 859 } 860 sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); 861 } 862 }else if( IsVirtual(pTab) ){ 863 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid); 864 }else{ 865 sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc); 866 appendFlag = 1; 867 } 868 autoIncStep(pParse, regAutoinc, regRowid); 869 870 /* Push onto the stack, data for all columns of the new entry, beginning 871 ** with the first column. 872 */ 873 nHidden = 0; 874 for(i=0; i<pTab->nCol; i++){ 875 int iRegStore = regRowid+1+i; 876 if( i==pTab->iPKey ){ 877 /* The value of the INTEGER PRIMARY KEY column is always a NULL. 878 ** Whenever this column is read, the record number will be substituted 879 ** in its place. So will fill this column with a NULL to avoid 880 ** taking up data space with information that will never be used. */ 881 sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore); 882 continue; 883 } 884 if( pColumn==0 ){ 885 if( IsHiddenColumn(&pTab->aCol[i]) ){ 886 assert( IsVirtual(pTab) ); 887 j = -1; 888 nHidden++; 889 }else{ 890 j = i - nHidden; 891 } 892 }else{ 893 for(j=0; j<pColumn->nId; j++){ 894 if( pColumn->a[j].idx==i ) break; 895 } 896 } 897 if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){ 898 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore); 899 }else if( useTempTable ){ 900 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); 901 }else if( pSelect ){ 902 sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore); 903 }else{ 904 sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore); 905 } 906 } 907 908 /* Generate code to check constraints and generate index keys and 909 ** do the insertion. 910 */ 911 #ifndef SQLITE_OMIT_VIRTUALTABLE 912 if( IsVirtual(pTab) ){ 913 sqlite3VtabMakeWritable(pParse, pTab); 914 sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, 915 (const char*)pTab->pVtab, P4_VTAB); 916 }else 917 #endif 918 { 919 sqlite3GenerateConstraintChecks( 920 pParse, 921 pTab, 922 baseCur, 923 regIns, 924 aRegIdx, 925 keyColumn>=0, 926 0, 927 onError, 928 endOfLoop 929 ); 930 sqlite3CompleteInsertion( 931 pParse, 932 pTab, 933 baseCur, 934 regIns, 935 aRegIdx, 936 0, 937 0, 938 (triggers_exist & TRIGGER_AFTER)!=0 ? newIdx : -1, 939 appendFlag 940 ); 941 } 942 } 943 944 /* Update the count of rows that are inserted 945 */ 946 if( (db->flags & SQLITE_CountRows)!=0 ){ 947 sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1); 948 } 949 950 if( triggers_exist ){ 951 /* Code AFTER triggers */ 952 if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_AFTER, pTab, 953 newIdx, -1, onError, endOfLoop, 0, 0) ){ 954 goto insert_cleanup; 955 } 956 } 957 958 /* The bottom of the main insertion loop, if the data source 959 ** is a SELECT statement. 960 */ 961 sqlite3VdbeResolveLabel(v, endOfLoop); 962 if( useTempTable ){ 963 sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); 964 sqlite3VdbeJumpHere(v, addrInsTop); 965 sqlite3VdbeAddOp1(v, OP_Close, srcTab); 966 }else if( pSelect ){ 967 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont); 968 sqlite3VdbeJumpHere(v, addrInsTop); 969 } 970 971 if( !IsVirtual(pTab) && !isView ){ 972 /* Close all tables opened */ 973 sqlite3VdbeAddOp1(v, OP_Close, baseCur); 974 for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){ 975 sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur); 976 } 977 } 978 979 /* Update the sqlite_sequence table by storing the content of the 980 ** counter value in memory regAutoinc back into the sqlite_sequence 981 ** table. 982 */ 983 autoIncEnd(pParse, iDb, pTab, regAutoinc); 984 985 /* 986 ** Return the number of rows inserted. If this routine is 987 ** generating code because of a call to sqlite3NestedParse(), do not 988 ** invoke the callback function. 989 */ 990 if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){ 991 sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1); 992 sqlite3VdbeSetNumCols(v, 1); 993 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", P4_STATIC); 994 } 995 996 insert_cleanup: 997 sqlite3SrcListDelete(pTabList); 998 sqlite3ExprListDelete(pList); 999 sqlite3SelectDelete(pSelect); 1000 sqlite3IdListDelete(pColumn); 1001 sqlite3_free(aRegIdx); 1002 } 1003 1004 /* 1005 ** Generate code to do constraint checks prior to an INSERT or an UPDATE. 1006 ** 1007 ** The input is a range of consecutive registers as follows: 1008 ** 1009 ** 1. The rowid of the row to be updated before the update. This 1010 ** value is omitted unless we are doing an UPDATE that involves a 1011 ** change to the record number or writing to a virtual table. 1012 ** 1013 ** 2. The rowid of the row after the update. 1014 ** 1015 ** 3. The data in the first column of the entry after the update. 1016 ** 1017 ** i. Data from middle columns... 1018 ** 1019 ** N. The data in the last column of the entry after the update. 1020 ** 1021 ** The regRowid parameter is the index of the register containing (2). 1022 ** 1023 ** The old rowid shown as entry (1) above is omitted unless both isUpdate 1024 ** and rowidChng are 1. isUpdate is true for UPDATEs and false for 1025 ** INSERTs. RowidChng means that the new rowid is explicitly specified by 1026 ** the update or insert statement. If rowidChng is false, it means that 1027 ** the rowid is computed automatically in an insert or that the rowid value 1028 ** is not modified by the update. 1029 ** 1030 ** The code generated by this routine store new index entries into 1031 ** registers identified by aRegIdx[]. No index entry is created for 1032 ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is 1033 ** the same as the order of indices on the linked list of indices 1034 ** attached to the table. 1035 ** 1036 ** This routine also generates code to check constraints. NOT NULL, 1037 ** CHECK, and UNIQUE constraints are all checked. If a constraint fails, 1038 ** then the appropriate action is performed. There are five possible 1039 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE. 1040 ** 1041 ** Constraint type Action What Happens 1042 ** --------------- ---------- ---------------------------------------- 1043 ** any ROLLBACK The current transaction is rolled back and 1044 ** sqlite3_exec() returns immediately with a 1045 ** return code of SQLITE_CONSTRAINT. 1046 ** 1047 ** any ABORT Back out changes from the current command 1048 ** only (do not do a complete rollback) then 1049 ** cause sqlite3_exec() to return immediately 1050 ** with SQLITE_CONSTRAINT. 1051 ** 1052 ** any FAIL Sqlite_exec() returns immediately with a 1053 ** return code of SQLITE_CONSTRAINT. The 1054 ** transaction is not rolled back and any 1055 ** prior changes are retained. 1056 ** 1057 ** any IGNORE The record number and data is popped from 1058 ** the stack and there is an immediate jump 1059 ** to label ignoreDest. 1060 ** 1061 ** NOT NULL REPLACE The NULL value is replace by the default 1062 ** value for that column. If the default value 1063 ** is NULL, the action is the same as ABORT. 1064 ** 1065 ** UNIQUE REPLACE The other row that conflicts with the row 1066 ** being inserted is removed. 1067 ** 1068 ** CHECK REPLACE Illegal. The results in an exception. 1069 ** 1070 ** Which action to take is determined by the overrideError parameter. 1071 ** Or if overrideError==OE_Default, then the pParse->onError parameter 1072 ** is used. Or if pParse->onError==OE_Default then the onError value 1073 ** for the constraint is used. 1074 ** 1075 ** The calling routine must open a read/write cursor for pTab with 1076 ** cursor number "baseCur". All indices of pTab must also have open 1077 ** read/write cursors with cursor number baseCur+i for the i-th cursor. 1078 ** Except, if there is no possibility of a REPLACE action then 1079 ** cursors do not need to be open for indices where aRegIdx[i]==0. 1080 */ 1081 void sqlite3GenerateConstraintChecks( 1082 Parse *pParse, /* The parser context */ 1083 Table *pTab, /* the table into which we are inserting */ 1084 int baseCur, /* Index of a read/write cursor pointing at pTab */ 1085 int regRowid, /* Index of the range of input registers */ 1086 int *aRegIdx, /* Register used by each index. 0 for unused indices */ 1087 int rowidChng, /* True if the rowid might collide with existing entry */ 1088 int isUpdate, /* True for UPDATE, False for INSERT */ 1089 int overrideError, /* Override onError to this if not OE_Default */ 1090 int ignoreDest /* Jump to this label on an OE_Ignore resolution */ 1091 ){ 1092 int i; 1093 Vdbe *v; 1094 int nCol; 1095 int onError; 1096 int j1, j2, j3; /* Addresses of jump instructions */ 1097 int regData; /* Register containing first data column */ 1098 int iCur; 1099 Index *pIdx; 1100 int seenReplace = 0; 1101 int hasTwoRowids = (isUpdate && rowidChng); 1102 1103 v = sqlite3GetVdbe(pParse); 1104 assert( v!=0 ); 1105 assert( pTab->pSelect==0 ); /* This table is not a VIEW */ 1106 nCol = pTab->nCol; 1107 regData = regRowid + 1; 1108 1109 1110 /* Test all NOT NULL constraints. 1111 */ 1112 for(i=0; i<nCol; i++){ 1113 if( i==pTab->iPKey ){ 1114 continue; 1115 } 1116 onError = pTab->aCol[i].notNull; 1117 if( onError==OE_None ) continue; 1118 if( overrideError!=OE_Default ){ 1119 onError = overrideError; 1120 }else if( onError==OE_Default ){ 1121 onError = OE_Abort; 1122 } 1123 if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){ 1124 onError = OE_Abort; 1125 } 1126 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i); 1127 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail 1128 || onError==OE_Ignore || onError==OE_Replace ); 1129 switch( onError ){ 1130 case OE_Rollback: 1131 case OE_Abort: 1132 case OE_Fail: { 1133 char *zMsg; 1134 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError); 1135 zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL", 1136 pTab->zName, pTab->aCol[i].zName); 1137 sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC); 1138 break; 1139 } 1140 case OE_Ignore: { 1141 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest); 1142 break; 1143 } 1144 case OE_Replace: { 1145 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i); 1146 break; 1147 } 1148 } 1149 sqlite3VdbeJumpHere(v, j1); 1150 } 1151 1152 /* Test all CHECK constraints 1153 */ 1154 #ifndef SQLITE_OMIT_CHECK 1155 if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){ 1156 int allOk = sqlite3VdbeMakeLabel(v); 1157 pParse->ckBase = regData; 1158 sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL); 1159 onError = overrideError!=OE_Default ? overrideError : OE_Abort; 1160 if( onError==OE_Ignore ){ 1161 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest); 1162 }else{ 1163 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError); 1164 } 1165 sqlite3VdbeResolveLabel(v, allOk); 1166 } 1167 #endif /* !defined(SQLITE_OMIT_CHECK) */ 1168 1169 /* If we have an INTEGER PRIMARY KEY, make sure the primary key 1170 ** of the new record does not previously exist. Except, if this 1171 ** is an UPDATE and the primary key is not changing, that is OK. 1172 */ 1173 if( rowidChng ){ 1174 onError = pTab->keyConf; 1175 if( overrideError!=OE_Default ){ 1176 onError = overrideError; 1177 }else if( onError==OE_Default ){ 1178 onError = OE_Abort; 1179 } 1180 1181 if( onError!=OE_Replace || pTab->pIndex ){ 1182 if( isUpdate ){ 1183 j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, regRowid-1); 1184 } 1185 j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid); 1186 switch( onError ){ 1187 default: { 1188 onError = OE_Abort; 1189 /* Fall thru into the next case */ 1190 } 1191 case OE_Rollback: 1192 case OE_Abort: 1193 case OE_Fail: { 1194 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, 1195 "PRIMARY KEY must be unique", P4_STATIC); 1196 break; 1197 } 1198 case OE_Replace: { 1199 sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0); 1200 seenReplace = 1; 1201 break; 1202 } 1203 case OE_Ignore: { 1204 assert( seenReplace==0 ); 1205 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest); 1206 break; 1207 } 1208 } 1209 sqlite3VdbeJumpHere(v, j3); 1210 if( isUpdate ){ 1211 sqlite3VdbeJumpHere(v, j2); 1212 } 1213 } 1214 } 1215 1216 /* Test all UNIQUE constraints by creating entries for each UNIQUE 1217 ** index and making sure that duplicate entries do not already exist. 1218 ** Add the new records to the indices as we go. 1219 */ 1220 for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){ 1221 int regIdx; 1222 int regR; 1223 1224 if( aRegIdx[iCur]==0 ) continue; /* Skip unused indices */ 1225 1226 /* Create a key for accessing the index entry */ 1227 regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1); 1228 for(i=0; i<pIdx->nColumn; i++){ 1229 int idx = pIdx->aiColumn[i]; 1230 if( idx==pTab->iPKey ){ 1231 sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i); 1232 }else{ 1233 sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i); 1234 } 1235 } 1236 sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i); 1237 sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]); 1238 sqlite3IndexAffinityStr(v, pIdx); 1239 sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1); 1240 sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1); 1241 1242 /* Find out what action to take in case there is an indexing conflict */ 1243 onError = pIdx->onError; 1244 if( onError==OE_None ) continue; /* pIdx is not a UNIQUE index */ 1245 if( overrideError!=OE_Default ){ 1246 onError = overrideError; 1247 }else if( onError==OE_Default ){ 1248 onError = OE_Abort; 1249 } 1250 if( seenReplace ){ 1251 if( onError==OE_Ignore ) onError = OE_Replace; 1252 else if( onError==OE_Fail ) onError = OE_Abort; 1253 } 1254 1255 1256 /* Check to see if the new index entry will be unique */ 1257 j2 = sqlite3VdbeAddOp3(v, OP_IsNull, regIdx, 0, pIdx->nColumn); 1258 regR = sqlite3GetTempReg(pParse); 1259 sqlite3VdbeAddOp2(v, OP_SCopy, regRowid-hasTwoRowids, regR); 1260 j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0, 1261 regR, SQLITE_INT_TO_PTR(aRegIdx[iCur]), 1262 P4_INT32); 1263 1264 /* Generate code that executes if the new index entry is not unique */ 1265 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail 1266 || onError==OE_Ignore || onError==OE_Replace ); 1267 switch( onError ){ 1268 case OE_Rollback: 1269 case OE_Abort: 1270 case OE_Fail: { 1271 int j, n1, n2; 1272 char zErrMsg[200]; 1273 sqlite3_snprintf(sizeof(zErrMsg), zErrMsg, 1274 pIdx->nColumn>1 ? "columns " : "column "); 1275 n1 = strlen(zErrMsg); 1276 for(j=0; j<pIdx->nColumn && n1<sizeof(zErrMsg)-30; j++){ 1277 char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName; 1278 n2 = strlen(zCol); 1279 if( j>0 ){ 1280 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], ", "); 1281 n1 += 2; 1282 } 1283 if( n1+n2>sizeof(zErrMsg)-30 ){ 1284 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "..."); 1285 n1 += 3; 1286 break; 1287 }else{ 1288 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "%s", zCol); 1289 n1 += n2; 1290 } 1291 } 1292 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], 1293 pIdx->nColumn>1 ? " are not unique" : " is not unique"); 1294 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, zErrMsg,0); 1295 break; 1296 } 1297 case OE_Ignore: { 1298 assert( seenReplace==0 ); 1299 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest); 1300 break; 1301 } 1302 case OE_Replace: { 1303 sqlite3GenerateRowDelete(pParse, pTab, baseCur, regR, 0); 1304 seenReplace = 1; 1305 break; 1306 } 1307 } 1308 sqlite3VdbeJumpHere(v, j2); 1309 sqlite3VdbeJumpHere(v, j3); 1310 sqlite3ReleaseTempReg(pParse, regR); 1311 } 1312 } 1313 1314 /* 1315 ** This routine generates code to finish the INSERT or UPDATE operation 1316 ** that was started by a prior call to sqlite3GenerateConstraintChecks. 1317 ** A consecutive range of registers starting at regRowid contains the 1318 ** rowid and the content to be inserted. 1319 ** 1320 ** The arguments to this routine should be the same as the first six 1321 ** arguments to sqlite3GenerateConstraintChecks. 1322 */ 1323 void sqlite3CompleteInsertion( 1324 Parse *pParse, /* The parser context */ 1325 Table *pTab, /* the table into which we are inserting */ 1326 int baseCur, /* Index of a read/write cursor pointing at pTab */ 1327 int regRowid, /* Range of content */ 1328 int *aRegIdx, /* Register used by each index. 0 for unused indices */ 1329 int rowidChng, /* True if the record number will change */ 1330 int isUpdate, /* True for UPDATE, False for INSERT */ 1331 int newIdx, /* Index of NEW table for triggers. -1 if none */ 1332 int appendBias /* True if this is likely to be an append */ 1333 ){ 1334 int i; 1335 Vdbe *v; 1336 int nIdx; 1337 Index *pIdx; 1338 int pik_flags; 1339 int regData; 1340 int regRec; 1341 1342 v = sqlite3GetVdbe(pParse); 1343 assert( v!=0 ); 1344 assert( pTab->pSelect==0 ); /* This table is not a VIEW */ 1345 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){} 1346 for(i=nIdx-1; i>=0; i--){ 1347 if( aRegIdx[i]==0 ) continue; 1348 sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]); 1349 } 1350 regData = regRowid + 1; 1351 regRec = sqlite3GetTempReg(pParse); 1352 sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec); 1353 sqlite3TableAffinityStr(v, pTab); 1354 sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol); 1355 #ifndef SQLITE_OMIT_TRIGGER 1356 if( newIdx>=0 ){ 1357 sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regRowid); 1358 } 1359 #endif 1360 if( pParse->nested ){ 1361 pik_flags = 0; 1362 }else{ 1363 pik_flags = OPFLAG_NCHANGE; 1364 pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID); 1365 } 1366 if( appendBias ){ 1367 pik_flags |= OPFLAG_APPEND; 1368 } 1369 sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid); 1370 if( !pParse->nested ){ 1371 sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC); 1372 } 1373 sqlite3VdbeChangeP5(v, pik_flags); 1374 } 1375 1376 /* 1377 ** Generate code that will open cursors for a table and for all 1378 ** indices of that table. The "baseCur" parameter is the cursor number used 1379 ** for the table. Indices are opened on subsequent cursors. 1380 ** 1381 ** Return the number of indices on the table. 1382 */ 1383 int sqlite3OpenTableAndIndices( 1384 Parse *pParse, /* Parsing context */ 1385 Table *pTab, /* Table to be opened */ 1386 int baseCur, /* Cursor number assigned to the table */ 1387 int op /* OP_OpenRead or OP_OpenWrite */ 1388 ){ 1389 int i; 1390 int iDb; 1391 Index *pIdx; 1392 Vdbe *v; 1393 1394 if( IsVirtual(pTab) ) return 0; 1395 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 1396 v = sqlite3GetVdbe(pParse); 1397 assert( v!=0 ); 1398 sqlite3OpenTable(pParse, baseCur, iDb, pTab, op); 1399 for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ 1400 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx); 1401 assert( pIdx->pSchema==pTab->pSchema ); 1402 sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb, 1403 (char*)pKey, P4_KEYINFO_HANDOFF); 1404 VdbeComment((v, "%s", pIdx->zName)); 1405 } 1406 if( pParse->nTab<=baseCur+i ){ 1407 pParse->nTab = baseCur+i; 1408 } 1409 return i-1; 1410 } 1411 1412 1413 #ifdef SQLITE_TEST 1414 /* 1415 ** The following global variable is incremented whenever the 1416 ** transfer optimization is used. This is used for testing 1417 ** purposes only - to make sure the transfer optimization really 1418 ** is happening when it is suppose to. 1419 */ 1420 int sqlite3_xferopt_count; 1421 #endif /* SQLITE_TEST */ 1422 1423 1424 #ifndef SQLITE_OMIT_XFER_OPT 1425 /* 1426 ** Check to collation names to see if they are compatible. 1427 */ 1428 static int xferCompatibleCollation(const char *z1, const char *z2){ 1429 if( z1==0 ){ 1430 return z2==0; 1431 } 1432 if( z2==0 ){ 1433 return 0; 1434 } 1435 return sqlite3StrICmp(z1, z2)==0; 1436 } 1437 1438 1439 /* 1440 ** Check to see if index pSrc is compatible as a source of data 1441 ** for index pDest in an insert transfer optimization. The rules 1442 ** for a compatible index: 1443 ** 1444 ** * The index is over the same set of columns 1445 ** * The same DESC and ASC markings occurs on all columns 1446 ** * The same onError processing (OE_Abort, OE_Ignore, etc) 1447 ** * The same collating sequence on each column 1448 */ 1449 static int xferCompatibleIndex(Index *pDest, Index *pSrc){ 1450 int i; 1451 assert( pDest && pSrc ); 1452 assert( pDest->pTable!=pSrc->pTable ); 1453 if( pDest->nColumn!=pSrc->nColumn ){ 1454 return 0; /* Different number of columns */ 1455 } 1456 if( pDest->onError!=pSrc->onError ){ 1457 return 0; /* Different conflict resolution strategies */ 1458 } 1459 for(i=0; i<pSrc->nColumn; i++){ 1460 if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){ 1461 return 0; /* Different columns indexed */ 1462 } 1463 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){ 1464 return 0; /* Different sort orders */ 1465 } 1466 if( pSrc->azColl[i]!=pDest->azColl[i] ){ 1467 return 0; /* Different collating sequences */ 1468 } 1469 } 1470 1471 /* If no test above fails then the indices must be compatible */ 1472 return 1; 1473 } 1474 1475 /* 1476 ** Attempt the transfer optimization on INSERTs of the form 1477 ** 1478 ** INSERT INTO tab1 SELECT * FROM tab2; 1479 ** 1480 ** This optimization is only attempted if 1481 ** 1482 ** (1) tab1 and tab2 have identical schemas including all the 1483 ** same indices and constraints 1484 ** 1485 ** (2) tab1 and tab2 are different tables 1486 ** 1487 ** (3) There must be no triggers on tab1 1488 ** 1489 ** (4) The result set of the SELECT statement is "*" 1490 ** 1491 ** (5) The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY, 1492 ** or LIMIT clause. 1493 ** 1494 ** (6) The SELECT statement is a simple (not a compound) select that 1495 ** contains only tab2 in its FROM clause 1496 ** 1497 ** This method for implementing the INSERT transfers raw records from 1498 ** tab2 over to tab1. The columns are not decoded. Raw records from 1499 ** the indices of tab2 are transfered to tab1 as well. In so doing, 1500 ** the resulting tab1 has much less fragmentation. 1501 ** 1502 ** This routine returns TRUE if the optimization is attempted. If any 1503 ** of the conditions above fail so that the optimization should not 1504 ** be attempted, then this routine returns FALSE. 1505 */ 1506 static int xferOptimization( 1507 Parse *pParse, /* Parser context */ 1508 Table *pDest, /* The table we are inserting into */ 1509 Select *pSelect, /* A SELECT statement to use as the data source */ 1510 int onError, /* How to handle constraint errors */ 1511 int iDbDest /* The database of pDest */ 1512 ){ 1513 ExprList *pEList; /* The result set of the SELECT */ 1514 Table *pSrc; /* The table in the FROM clause of SELECT */ 1515 Index *pSrcIdx, *pDestIdx; /* Source and destination indices */ 1516 struct SrcList_item *pItem; /* An element of pSelect->pSrc */ 1517 int i; /* Loop counter */ 1518 int iDbSrc; /* The database of pSrc */ 1519 int iSrc, iDest; /* Cursors from source and destination */ 1520 int addr1, addr2; /* Loop addresses */ 1521 int emptyDestTest; /* Address of test for empty pDest */ 1522 int emptySrcTest; /* Address of test for empty pSrc */ 1523 Vdbe *v; /* The VDBE we are building */ 1524 KeyInfo *pKey; /* Key information for an index */ 1525 int regAutoinc; /* Memory register used by AUTOINC */ 1526 int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */ 1527 int regData, regRowid; /* Registers holding data and rowid */ 1528 1529 if( pSelect==0 ){ 1530 return 0; /* Must be of the form INSERT INTO ... SELECT ... */ 1531 } 1532 if( pDest->pTrigger ){ 1533 return 0; /* tab1 must not have triggers */ 1534 } 1535 #ifndef SQLITE_OMIT_VIRTUALTABLE 1536 if( pDest->isVirtual ){ 1537 return 0; /* tab1 must not be a virtual table */ 1538 } 1539 #endif 1540 if( onError==OE_Default ){ 1541 onError = OE_Abort; 1542 } 1543 if( onError!=OE_Abort && onError!=OE_Rollback ){ 1544 return 0; /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */ 1545 } 1546 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */ 1547 if( pSelect->pSrc->nSrc!=1 ){ 1548 return 0; /* FROM clause must have exactly one term */ 1549 } 1550 if( pSelect->pSrc->a[0].pSelect ){ 1551 return 0; /* FROM clause cannot contain a subquery */ 1552 } 1553 if( pSelect->pWhere ){ 1554 return 0; /* SELECT may not have a WHERE clause */ 1555 } 1556 if( pSelect->pOrderBy ){ 1557 return 0; /* SELECT may not have an ORDER BY clause */ 1558 } 1559 /* Do not need to test for a HAVING clause. If HAVING is present but 1560 ** there is no ORDER BY, we will get an error. */ 1561 if( pSelect->pGroupBy ){ 1562 return 0; /* SELECT may not have a GROUP BY clause */ 1563 } 1564 if( pSelect->pLimit ){ 1565 return 0; /* SELECT may not have a LIMIT clause */ 1566 } 1567 assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */ 1568 if( pSelect->pPrior ){ 1569 return 0; /* SELECT may not be a compound query */ 1570 } 1571 if( pSelect->isDistinct ){ 1572 return 0; /* SELECT may not be DISTINCT */ 1573 } 1574 pEList = pSelect->pEList; 1575 assert( pEList!=0 ); 1576 if( pEList->nExpr!=1 ){ 1577 return 0; /* The result set must have exactly one column */ 1578 } 1579 assert( pEList->a[0].pExpr ); 1580 if( pEList->a[0].pExpr->op!=TK_ALL ){ 1581 return 0; /* The result set must be the special operator "*" */ 1582 } 1583 1584 /* At this point we have established that the statement is of the 1585 ** correct syntactic form to participate in this optimization. Now 1586 ** we have to check the semantics. 1587 */ 1588 pItem = pSelect->pSrc->a; 1589 pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase); 1590 if( pSrc==0 ){ 1591 return 0; /* FROM clause does not contain a real table */ 1592 } 1593 if( pSrc==pDest ){ 1594 return 0; /* tab1 and tab2 may not be the same table */ 1595 } 1596 #ifndef SQLITE_OMIT_VIRTUALTABLE 1597 if( pSrc->isVirtual ){ 1598 return 0; /* tab2 must not be a virtual table */ 1599 } 1600 #endif 1601 if( pSrc->pSelect ){ 1602 return 0; /* tab2 may not be a view */ 1603 } 1604 if( pDest->nCol!=pSrc->nCol ){ 1605 return 0; /* Number of columns must be the same in tab1 and tab2 */ 1606 } 1607 if( pDest->iPKey!=pSrc->iPKey ){ 1608 return 0; /* Both tables must have the same INTEGER PRIMARY KEY */ 1609 } 1610 for(i=0; i<pDest->nCol; i++){ 1611 if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){ 1612 return 0; /* Affinity must be the same on all columns */ 1613 } 1614 if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){ 1615 return 0; /* Collating sequence must be the same on all columns */ 1616 } 1617 if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){ 1618 return 0; /* tab2 must be NOT NULL if tab1 is */ 1619 } 1620 } 1621 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ 1622 if( pDestIdx->onError!=OE_None ){ 1623 destHasUniqueIdx = 1; 1624 } 1625 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){ 1626 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; 1627 } 1628 if( pSrcIdx==0 ){ 1629 return 0; /* pDestIdx has no corresponding index in pSrc */ 1630 } 1631 } 1632 #ifndef SQLITE_OMIT_CHECK 1633 if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){ 1634 return 0; /* Tables have different CHECK constraints. Ticket #2252 */ 1635 } 1636 #endif 1637 1638 /* If we get this far, it means either: 1639 ** 1640 ** * We can always do the transfer if the table contains an 1641 ** an integer primary key 1642 ** 1643 ** * We can conditionally do the transfer if the destination 1644 ** table is empty. 1645 */ 1646 #ifdef SQLITE_TEST 1647 sqlite3_xferopt_count++; 1648 #endif 1649 iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema); 1650 v = sqlite3GetVdbe(pParse); 1651 sqlite3CodeVerifySchema(pParse, iDbSrc); 1652 iSrc = pParse->nTab++; 1653 iDest = pParse->nTab++; 1654 regAutoinc = autoIncBegin(pParse, iDbDest, pDest); 1655 sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite); 1656 if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){ 1657 /* If tables do not have an INTEGER PRIMARY KEY and there 1658 ** are indices to be copied and the destination is not empty, 1659 ** we have to disallow the transfer optimization because the 1660 ** the rowids might change which will mess up indexing. 1661 ** 1662 ** Or if the destination has a UNIQUE index and is not empty, 1663 ** we also disallow the transfer optimization because we cannot 1664 ** insure that all entries in the union of DEST and SRC will be 1665 ** unique. 1666 */ 1667 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); 1668 emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0); 1669 sqlite3VdbeJumpHere(v, addr1); 1670 }else{ 1671 emptyDestTest = 0; 1672 } 1673 sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead); 1674 emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); 1675 regData = sqlite3GetTempReg(pParse); 1676 regRowid = sqlite3GetTempReg(pParse); 1677 if( pDest->iPKey>=0 ){ 1678 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); 1679 addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid); 1680 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, 1681 "PRIMARY KEY must be unique", P4_STATIC); 1682 sqlite3VdbeJumpHere(v, addr2); 1683 autoIncStep(pParse, regAutoinc, regRowid); 1684 }else if( pDest->pIndex==0 ){ 1685 addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid); 1686 }else{ 1687 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); 1688 assert( pDest->autoInc==0 ); 1689 } 1690 sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData); 1691 sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid); 1692 sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND); 1693 sqlite3VdbeChangeP4(v, -1, pDest->zName, 0); 1694 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); 1695 autoIncEnd(pParse, iDbDest, pDest, regAutoinc); 1696 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ 1697 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){ 1698 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; 1699 } 1700 assert( pSrcIdx ); 1701 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); 1702 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); 1703 pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx); 1704 sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc, 1705 (char*)pKey, P4_KEYINFO_HANDOFF); 1706 VdbeComment((v, "%s", pSrcIdx->zName)); 1707 pKey = sqlite3IndexKeyinfo(pParse, pDestIdx); 1708 sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest, 1709 (char*)pKey, P4_KEYINFO_HANDOFF); 1710 VdbeComment((v, "%s", pDestIdx->zName)); 1711 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); 1712 sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData); 1713 sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1); 1714 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); 1715 sqlite3VdbeJumpHere(v, addr1); 1716 } 1717 sqlite3VdbeJumpHere(v, emptySrcTest); 1718 sqlite3ReleaseTempReg(pParse, regRowid); 1719 sqlite3ReleaseTempReg(pParse, regData); 1720 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); 1721 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); 1722 if( emptyDestTest ){ 1723 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0); 1724 sqlite3VdbeJumpHere(v, emptyDestTest); 1725 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); 1726 return 0; 1727 }else{ 1728 return 1; 1729 } 1730 } 1731 #endif /* SQLITE_OMIT_XFER_OPT */ 1732 1733 /* Make sure "isView" gets undefined in case this file becomes part of 1734 ** the amalgamation - so that subsequent files do not see isView as a 1735 ** macro. */ 1736 #undef isView 1737