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