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