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