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.143 2005/09/20 17:42:23 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 ** 'n' NUMERIC 27 ** 'i' INTEGER 28 ** 't' TEXT 29 ** 'o' NONE 30 */ 31 void sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){ 32 if( !pIdx->zColAff ){ 33 /* The first time a column affinity string for a particular index is 34 ** required, it is allocated and populated here. It is then stored as 35 ** a member of the Index structure for subsequent use. 36 ** 37 ** The column affinity string will eventually be deleted by 38 ** sqliteDeleteIndex() when the Index structure itself is cleaned 39 ** up. 40 */ 41 int n; 42 Table *pTab = pIdx->pTable; 43 pIdx->zColAff = (char *)sqliteMalloc(pIdx->nColumn+1); 44 if( !pIdx->zColAff ){ 45 return; 46 } 47 for(n=0; n<pIdx->nColumn; n++){ 48 pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity; 49 } 50 pIdx->zColAff[pIdx->nColumn] = '\0'; 51 } 52 53 sqlite3VdbeChangeP3(v, -1, pIdx->zColAff, 0); 54 } 55 56 /* 57 ** Set P3 of the most recently inserted opcode to a column affinity 58 ** string for table pTab. A column affinity string has one character 59 ** for each column indexed by the index, according to the affinity of the 60 ** column: 61 ** 62 ** Character Column affinity 63 ** ------------------------------ 64 ** 'n' NUMERIC 65 ** 'i' INTEGER 66 ** 't' TEXT 67 ** 'o' NONE 68 */ 69 void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){ 70 /* The first time a column affinity string for a particular table 71 ** is required, it is allocated and populated here. It is then 72 ** stored as a member of the Table structure for subsequent use. 73 ** 74 ** The column affinity string will eventually be deleted by 75 ** sqlite3DeleteTable() when the Table structure itself is cleaned up. 76 */ 77 if( !pTab->zColAff ){ 78 char *zColAff; 79 int i; 80 81 zColAff = (char *)sqliteMalloc(pTab->nCol+1); 82 if( !zColAff ){ 83 return; 84 } 85 86 for(i=0; i<pTab->nCol; i++){ 87 zColAff[i] = pTab->aCol[i].affinity; 88 } 89 zColAff[pTab->nCol] = '\0'; 90 91 pTab->zColAff = zColAff; 92 } 93 94 sqlite3VdbeChangeP3(v, -1, pTab->zColAff, 0); 95 } 96 97 /* 98 ** Return non-zero if SELECT statement p opens the table with rootpage 99 ** iTab in database iDb. This is used to see if a statement of the form 100 ** "INSERT INTO <iDb, iTab> SELECT ..." can run without using temporary 101 ** table for the results of the SELECT. 102 ** 103 ** No checking is done for sub-selects that are part of expressions. 104 */ 105 static int selectReadsTable(Select *p, int iDb, int iTab){ 106 int i; 107 struct SrcList_item *pItem; 108 if( p->pSrc==0 ) return 0; 109 for(i=0, pItem=p->pSrc->a; i<p->pSrc->nSrc; i++, pItem++){ 110 if( pItem->pSelect ){ 111 if( selectReadsTable(pItem->pSelect, iDb, iTab) ) return 1; 112 }else{ 113 if( pItem->pTab->iDb==iDb && pItem->pTab->tnum==iTab ) return 1; 114 } 115 } 116 return 0; 117 } 118 119 /* 120 ** This routine is call to handle SQL of the following forms: 121 ** 122 ** insert into TABLE (IDLIST) values(EXPRLIST) 123 ** insert into TABLE (IDLIST) select 124 ** 125 ** The IDLIST following the table name is always optional. If omitted, 126 ** then a list of all columns for the table is substituted. The IDLIST 127 ** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted. 128 ** 129 ** The pList parameter holds EXPRLIST in the first form of the INSERT 130 ** statement above, and pSelect is NULL. For the second form, pList is 131 ** NULL and pSelect is a pointer to the select statement used to generate 132 ** data for the insert. 133 ** 134 ** The code generated follows one of three templates. For a simple 135 ** select with data coming from a VALUES clause, the code executes 136 ** once straight down through. The template looks like this: 137 ** 138 ** open write cursor to <table> and its indices 139 ** puts VALUES clause expressions onto the stack 140 ** write the resulting record into <table> 141 ** cleanup 142 ** 143 ** If the statement is of the form 144 ** 145 ** INSERT INTO <table> SELECT ... 146 ** 147 ** And the SELECT clause does not read from <table> at any time, then 148 ** the generated code follows this template: 149 ** 150 ** goto B 151 ** A: setup for the SELECT 152 ** loop over the tables in the SELECT 153 ** gosub C 154 ** end loop 155 ** cleanup after the SELECT 156 ** goto D 157 ** B: open write cursor to <table> and its indices 158 ** goto A 159 ** C: insert the select result into <table> 160 ** return 161 ** D: cleanup 162 ** 163 ** The third template is used if the insert statement takes its 164 ** values from a SELECT but the data is being inserted into a table 165 ** that is also read as part of the SELECT. In the third form, 166 ** we have to use a intermediate table to store the results of 167 ** the select. The template is like this: 168 ** 169 ** goto B 170 ** A: setup for the SELECT 171 ** loop over the tables in the SELECT 172 ** gosub C 173 ** end loop 174 ** cleanup after the SELECT 175 ** goto D 176 ** C: insert the select result into the intermediate table 177 ** return 178 ** B: open a cursor to an intermediate table 179 ** goto A 180 ** D: open write cursor to <table> and its indices 181 ** loop over the intermediate table 182 ** transfer values form intermediate table into <table> 183 ** end the loop 184 ** cleanup 185 */ 186 void sqlite3Insert( 187 Parse *pParse, /* Parser context */ 188 SrcList *pTabList, /* Name of table into which we are inserting */ 189 ExprList *pList, /* List of values to be inserted */ 190 Select *pSelect, /* A SELECT statement to use as the data source */ 191 IdList *pColumn, /* Column names corresponding to IDLIST. */ 192 int onError /* How to handle constraint errors */ 193 ){ 194 Table *pTab; /* The table to insert into */ 195 char *zTab; /* Name of the table into which we are inserting */ 196 const char *zDb; /* Name of the database holding this table */ 197 int i, j, idx; /* Loop counters */ 198 Vdbe *v; /* Generate code into this virtual machine */ 199 Index *pIdx; /* For looping over indices of the table */ 200 int nColumn; /* Number of columns in the data */ 201 int base = 0; /* VDBE Cursor number for pTab */ 202 int iCont=0,iBreak=0; /* Beginning and end of the loop over srcTab */ 203 sqlite3 *db; /* The main database structure */ 204 int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */ 205 int endOfLoop; /* Label for the end of the insertion loop */ 206 int useTempTable = 0; /* Store SELECT results in intermediate table */ 207 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */ 208 int iSelectLoop = 0; /* Address of code that implements the SELECT */ 209 int iCleanup = 0; /* Address of the cleanup code */ 210 int iInsertBlock = 0; /* Address of the subroutine used to insert data */ 211 int iCntMem = 0; /* Memory cell used for the row counter */ 212 int newIdx = -1; /* Cursor for the NEW table */ 213 Db *pDb; /* The database containing table being inserted into */ 214 int counterMem = 0; /* Memory cell holding AUTOINCREMENT counter */ 215 216 #ifndef SQLITE_OMIT_TRIGGER 217 int isView; /* True if attempting to insert into a view */ 218 int triggers_exist = 0; /* True if there are FOR EACH ROW triggers */ 219 #endif 220 221 #ifndef SQLITE_OMIT_AUTOINCREMENT 222 int counterRowid; /* Memory cell holding rowid of autoinc counter */ 223 #endif 224 225 if( pParse->nErr || sqlite3_malloc_failed ) goto insert_cleanup; 226 db = pParse->db; 227 228 /* Locate the table into which we will be inserting new information. 229 */ 230 assert( pTabList->nSrc==1 ); 231 zTab = pTabList->a[0].zName; 232 if( zTab==0 ) goto insert_cleanup; 233 pTab = sqlite3SrcListLookup(pParse, pTabList); 234 if( pTab==0 ){ 235 goto insert_cleanup; 236 } 237 assert( pTab->iDb<db->nDb ); 238 pDb = &db->aDb[pTab->iDb]; 239 zDb = pDb->zName; 240 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){ 241 goto insert_cleanup; 242 } 243 244 /* Figure out if we have any triggers and if the table being 245 ** inserted into is a view 246 */ 247 #ifndef SQLITE_OMIT_TRIGGER 248 triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0); 249 isView = pTab->pSelect!=0; 250 #else 251 # define triggers_exist 0 252 # define isView 0 253 #endif 254 #ifdef SQLITE_OMIT_VIEW 255 # undef isView 256 # define isView 0 257 #endif 258 259 /* Ensure that: 260 * (a) the table is not read-only, 261 * (b) that if it is a view then ON INSERT triggers exist 262 */ 263 if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){ 264 goto insert_cleanup; 265 } 266 if( pTab==0 ) goto insert_cleanup; 267 268 /* If pTab is really a view, make sure it has been initialized. 269 */ 270 if( isView && sqlite3ViewGetColumnNames(pParse, pTab) ){ 271 goto insert_cleanup; 272 } 273 274 /* Ensure all required collation sequences are available. */ 275 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 276 if( sqlite3CheckIndexCollSeq(pParse, pIdx) ){ 277 goto insert_cleanup; 278 } 279 } 280 281 /* Allocate a VDBE 282 */ 283 v = sqlite3GetVdbe(pParse); 284 if( v==0 ) goto insert_cleanup; 285 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v); 286 sqlite3BeginWriteOperation(pParse, pSelect || triggers_exist, pTab->iDb); 287 288 /* if there are row triggers, allocate a temp table for new.* references. */ 289 if( triggers_exist ){ 290 newIdx = pParse->nTab++; 291 } 292 293 #ifndef SQLITE_OMIT_AUTOINCREMENT 294 /* If this is an AUTOINCREMENT table, look up the sequence number in the 295 ** sqlite_sequence table and store it in memory cell counterMem. Also 296 ** remember the rowid of the sqlite_sequence table entry in memory cell 297 ** counterRowid. 298 */ 299 if( pTab->autoInc ){ 300 int iCur = pParse->nTab; 301 int base = sqlite3VdbeCurrentAddr(v); 302 counterRowid = pParse->nMem++; 303 counterMem = pParse->nMem++; 304 sqlite3VdbeAddOp(v, OP_Integer, pTab->iDb, 0); 305 sqlite3VdbeAddOp(v, OP_OpenRead, iCur, pDb->pSeqTab->tnum); 306 sqlite3VdbeAddOp(v, OP_SetNumColumns, iCur, 2); 307 sqlite3VdbeAddOp(v, OP_Rewind, iCur, base+13); 308 sqlite3VdbeAddOp(v, OP_Column, iCur, 0); 309 sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0); 310 sqlite3VdbeAddOp(v, OP_Ne, 28417, base+12); 311 sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0); 312 sqlite3VdbeAddOp(v, OP_MemStore, counterRowid, 1); 313 sqlite3VdbeAddOp(v, OP_Column, iCur, 1); 314 sqlite3VdbeAddOp(v, OP_MemStore, counterMem, 1); 315 sqlite3VdbeAddOp(v, OP_Goto, 0, base+13); 316 sqlite3VdbeAddOp(v, OP_Next, iCur, base+4); 317 sqlite3VdbeAddOp(v, OP_Close, iCur, 0); 318 } 319 #endif /* SQLITE_OMIT_AUTOINCREMENT */ 320 321 /* Figure out how many columns of data are supplied. If the data 322 ** is coming from a SELECT statement, then this step also generates 323 ** all the code to implement the SELECT statement and invoke a subroutine 324 ** to process each row of the result. (Template 2.) If the SELECT 325 ** statement uses the the table that is being inserted into, then the 326 ** subroutine is also coded here. That subroutine stores the SELECT 327 ** results in a temporary table. (Template 3.) 328 */ 329 if( pSelect ){ 330 /* Data is coming from a SELECT. Generate code to implement that SELECT 331 */ 332 int rc, iInitCode; 333 iInitCode = sqlite3VdbeAddOp(v, OP_Goto, 0, 0); 334 iSelectLoop = sqlite3VdbeCurrentAddr(v); 335 iInsertBlock = sqlite3VdbeMakeLabel(v); 336 337 /* Resolve the expressions in the SELECT statement and execute it. */ 338 rc = sqlite3Select(pParse, pSelect, SRT_Subroutine, iInsertBlock,0,0,0,0); 339 if( rc || pParse->nErr || sqlite3_malloc_failed ) goto insert_cleanup; 340 341 iCleanup = sqlite3VdbeMakeLabel(v); 342 sqlite3VdbeAddOp(v, OP_Goto, 0, iCleanup); 343 assert( pSelect->pEList ); 344 nColumn = pSelect->pEList->nExpr; 345 346 /* Set useTempTable to TRUE if the result of the SELECT statement 347 ** should be written into a temporary table. Set to FALSE if each 348 ** row of the SELECT can be written directly into the result table. 349 ** 350 ** A temp table must be used if the table being updated is also one 351 ** of the tables being read by the SELECT statement. Also use a 352 ** temp table in the case of row triggers. 353 */ 354 if( triggers_exist || selectReadsTable(pSelect, pTab->iDb, pTab->tnum) ){ 355 useTempTable = 1; 356 } 357 358 if( useTempTable ){ 359 /* Generate the subroutine that SELECT calls to process each row of 360 ** the result. Store the result in a temporary table 361 */ 362 srcTab = pParse->nTab++; 363 sqlite3VdbeResolveLabel(v, iInsertBlock); 364 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0); 365 sqlite3TableAffinityStr(v, pTab); 366 sqlite3VdbeAddOp(v, OP_NewRowid, srcTab, 0); 367 sqlite3VdbeAddOp(v, OP_Pull, 1, 0); 368 sqlite3VdbeAddOp(v, OP_Insert, srcTab, 0); 369 sqlite3VdbeAddOp(v, OP_Return, 0, 0); 370 371 /* The following code runs first because the GOTO at the very top 372 ** of the program jumps to it. Create the temporary table, then jump 373 ** back up and execute the SELECT code above. 374 */ 375 sqlite3VdbeJumpHere(v, iInitCode); 376 sqlite3VdbeAddOp(v, OP_OpenVirtual, srcTab, 0); 377 sqlite3VdbeAddOp(v, OP_SetNumColumns, srcTab, nColumn); 378 sqlite3VdbeAddOp(v, OP_Goto, 0, iSelectLoop); 379 sqlite3VdbeResolveLabel(v, iCleanup); 380 }else{ 381 sqlite3VdbeJumpHere(v, iInitCode); 382 } 383 }else{ 384 /* This is the case if the data for the INSERT is coming from a VALUES 385 ** clause 386 */ 387 NameContext sNC; 388 memset(&sNC, 0, sizeof(sNC)); 389 sNC.pParse = pParse; 390 assert( pList!=0 ); 391 srcTab = -1; 392 useTempTable = 0; 393 assert( pList ); 394 nColumn = pList->nExpr; 395 for(i=0; i<nColumn; i++){ 396 if( sqlite3ExprResolveNames(&sNC, pList->a[i].pExpr) ){ 397 goto insert_cleanup; 398 } 399 } 400 } 401 402 /* Make sure the number of columns in the source data matches the number 403 ** of columns to be inserted into the table. 404 */ 405 if( pColumn==0 && nColumn!=pTab->nCol ){ 406 sqlite3ErrorMsg(pParse, 407 "table %S has %d columns but %d values were supplied", 408 pTabList, 0, pTab->nCol, nColumn); 409 goto insert_cleanup; 410 } 411 if( pColumn!=0 && nColumn!=pColumn->nId ){ 412 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId); 413 goto insert_cleanup; 414 } 415 416 /* If the INSERT statement included an IDLIST term, then make sure 417 ** all elements of the IDLIST really are columns of the table and 418 ** remember the column indices. 419 ** 420 ** If the table has an INTEGER PRIMARY KEY column and that column 421 ** is named in the IDLIST, then record in the keyColumn variable 422 ** the index into IDLIST of the primary key column. keyColumn is 423 ** the index of the primary key as it appears in IDLIST, not as 424 ** is appears in the original table. (The index of the primary 425 ** key in the original table is pTab->iPKey.) 426 */ 427 if( pColumn ){ 428 for(i=0; i<pColumn->nId; i++){ 429 pColumn->a[i].idx = -1; 430 } 431 for(i=0; i<pColumn->nId; i++){ 432 for(j=0; j<pTab->nCol; j++){ 433 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){ 434 pColumn->a[i].idx = j; 435 if( j==pTab->iPKey ){ 436 keyColumn = i; 437 } 438 break; 439 } 440 } 441 if( j>=pTab->nCol ){ 442 if( sqlite3IsRowid(pColumn->a[i].zName) ){ 443 keyColumn = i; 444 }else{ 445 sqlite3ErrorMsg(pParse, "table %S has no column named %s", 446 pTabList, 0, pColumn->a[i].zName); 447 pParse->nErr++; 448 goto insert_cleanup; 449 } 450 } 451 } 452 } 453 454 /* If there is no IDLIST term but the table has an integer primary 455 ** key, the set the keyColumn variable to the primary key column index 456 ** in the original table definition. 457 */ 458 if( pColumn==0 ){ 459 keyColumn = pTab->iPKey; 460 } 461 462 /* Open the temp table for FOR EACH ROW triggers 463 */ 464 if( triggers_exist ){ 465 sqlite3VdbeAddOp(v, OP_OpenPseudo, newIdx, 0); 466 sqlite3VdbeAddOp(v, OP_SetNumColumns, newIdx, pTab->nCol); 467 } 468 469 /* Initialize the count of rows to be inserted 470 */ 471 if( db->flags & SQLITE_CountRows ){ 472 iCntMem = pParse->nMem++; 473 sqlite3VdbeAddOp(v, OP_MemInt, 0, iCntMem); 474 } 475 476 /* Open tables and indices if there are no row triggers */ 477 if( !triggers_exist ){ 478 base = pParse->nTab; 479 sqlite3OpenTableAndIndices(pParse, pTab, base, OP_OpenWrite); 480 } 481 482 /* If the data source is a temporary table, then we have to create 483 ** a loop because there might be multiple rows of data. If the data 484 ** source is a subroutine call from the SELECT statement, then we need 485 ** to launch the SELECT statement processing. 486 */ 487 if( useTempTable ){ 488 iBreak = sqlite3VdbeMakeLabel(v); 489 sqlite3VdbeAddOp(v, OP_Rewind, srcTab, iBreak); 490 iCont = sqlite3VdbeCurrentAddr(v); 491 }else if( pSelect ){ 492 sqlite3VdbeAddOp(v, OP_Goto, 0, iSelectLoop); 493 sqlite3VdbeResolveLabel(v, iInsertBlock); 494 } 495 496 /* Run the BEFORE and INSTEAD OF triggers, if there are any 497 */ 498 endOfLoop = sqlite3VdbeMakeLabel(v); 499 if( triggers_exist & TRIGGER_BEFORE ){ 500 501 /* build the NEW.* reference row. Note that if there is an INTEGER 502 ** PRIMARY KEY into which a NULL is being inserted, that NULL will be 503 ** translated into a unique ID for the row. But on a BEFORE trigger, 504 ** we do not know what the unique ID will be (because the insert has 505 ** not happened yet) so we substitute a rowid of -1 506 */ 507 if( keyColumn<0 ){ 508 sqlite3VdbeAddOp(v, OP_Integer, -1, 0); 509 }else if( useTempTable ){ 510 sqlite3VdbeAddOp(v, OP_Column, srcTab, keyColumn); 511 }else{ 512 assert( pSelect==0 ); /* Otherwise useTempTable is true */ 513 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr); 514 sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3); 515 sqlite3VdbeAddOp(v, OP_Pop, 1, 0); 516 sqlite3VdbeAddOp(v, OP_Integer, -1, 0); 517 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0); 518 } 519 520 /* Create the new column data 521 */ 522 for(i=0; i<pTab->nCol; i++){ 523 if( pColumn==0 ){ 524 j = i; 525 }else{ 526 for(j=0; j<pColumn->nId; j++){ 527 if( pColumn->a[j].idx==i ) break; 528 } 529 } 530 if( pColumn && j>=pColumn->nId ){ 531 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt); 532 }else if( useTempTable ){ 533 sqlite3VdbeAddOp(v, OP_Column, srcTab, j); 534 }else{ 535 assert( pSelect==0 ); /* Otherwise useTempTable is true */ 536 sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr); 537 } 538 } 539 sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0); 540 541 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger, 542 ** do not attempt any conversions before assembling the record. 543 ** If this is a real table, attempt conversions as required by the 544 ** table column affinities. 545 */ 546 if( !isView ){ 547 sqlite3TableAffinityStr(v, pTab); 548 } 549 sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0); 550 551 /* Fire BEFORE or INSTEAD OF triggers */ 552 if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_BEFORE, pTab, 553 newIdx, -1, onError, endOfLoop) ){ 554 goto insert_cleanup; 555 } 556 } 557 558 /* If any triggers exists, the opening of tables and indices is deferred 559 ** until now. 560 */ 561 if( triggers_exist && !isView ){ 562 base = pParse->nTab; 563 sqlite3OpenTableAndIndices(pParse, pTab, base, OP_OpenWrite); 564 } 565 566 /* Push the record number for the new entry onto the stack. The 567 ** record number is a randomly generate integer created by NewRowid 568 ** except when the table has an INTEGER PRIMARY KEY column, in which 569 ** case the record number is the same as that column. 570 */ 571 if( !isView ){ 572 if( keyColumn>=0 ){ 573 if( useTempTable ){ 574 sqlite3VdbeAddOp(v, OP_Column, srcTab, keyColumn); 575 }else if( pSelect ){ 576 sqlite3VdbeAddOp(v, OP_Dup, nColumn - keyColumn - 1, 1); 577 }else{ 578 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr); 579 } 580 /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid 581 ** to generate a unique primary key value. 582 */ 583 sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3); 584 sqlite3VdbeAddOp(v, OP_Pop, 1, 0); 585 sqlite3VdbeAddOp(v, OP_NewRowid, base, counterMem); 586 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0); 587 }else{ 588 sqlite3VdbeAddOp(v, OP_NewRowid, base, counterMem); 589 } 590 #ifndef SQLITE_OMIT_AUTOINCREMENT 591 if( pTab->autoInc ){ 592 sqlite3VdbeAddOp(v, OP_MemMax, counterMem, 0); 593 } 594 #endif /* SQLITE_OMIT_AUTOINCREMENT */ 595 596 /* Push onto the stack, data for all columns of the new entry, beginning 597 ** with the first column. 598 */ 599 for(i=0; i<pTab->nCol; i++){ 600 if( i==pTab->iPKey ){ 601 /* The value of the INTEGER PRIMARY KEY column is always a NULL. 602 ** Whenever this column is read, the record number will be substituted 603 ** in its place. So will fill this column with a NULL to avoid 604 ** taking up data space with information that will never be used. */ 605 sqlite3VdbeAddOp(v, OP_Null, 0, 0); 606 continue; 607 } 608 if( pColumn==0 ){ 609 j = i; 610 }else{ 611 for(j=0; j<pColumn->nId; j++){ 612 if( pColumn->a[j].idx==i ) break; 613 } 614 } 615 if( pColumn && j>=pColumn->nId ){ 616 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt); 617 }else if( useTempTable ){ 618 sqlite3VdbeAddOp(v, OP_Column, srcTab, j); 619 }else if( pSelect ){ 620 sqlite3VdbeAddOp(v, OP_Dup, i+nColumn-j, 1); 621 }else{ 622 sqlite3ExprCode(pParse, pList->a[j].pExpr); 623 } 624 } 625 626 /* Generate code to check constraints and generate index keys and 627 ** do the insertion. 628 */ 629 sqlite3GenerateConstraintChecks(pParse, pTab, base, 0, keyColumn>=0, 630 0, onError, endOfLoop); 631 sqlite3CompleteInsertion(pParse, pTab, base, 0,0,0, 632 (triggers_exist & TRIGGER_AFTER)!=0 ? newIdx : -1); 633 } 634 635 /* Update the count of rows that are inserted 636 */ 637 if( (db->flags & SQLITE_CountRows)!=0 ){ 638 sqlite3VdbeAddOp(v, OP_MemIncr, iCntMem, 0); 639 } 640 641 if( triggers_exist ){ 642 /* Close all tables opened */ 643 if( !isView ){ 644 sqlite3VdbeAddOp(v, OP_Close, base, 0); 645 for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){ 646 sqlite3VdbeAddOp(v, OP_Close, idx+base, 0); 647 } 648 } 649 650 /* Code AFTER triggers */ 651 if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_AFTER, pTab, 652 newIdx, -1, onError, endOfLoop) ){ 653 goto insert_cleanup; 654 } 655 } 656 657 /* The bottom of the loop, if the data source is a SELECT statement 658 */ 659 sqlite3VdbeResolveLabel(v, endOfLoop); 660 if( useTempTable ){ 661 sqlite3VdbeAddOp(v, OP_Next, srcTab, iCont); 662 sqlite3VdbeResolveLabel(v, iBreak); 663 sqlite3VdbeAddOp(v, OP_Close, srcTab, 0); 664 }else if( pSelect ){ 665 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0); 666 sqlite3VdbeAddOp(v, OP_Return, 0, 0); 667 sqlite3VdbeResolveLabel(v, iCleanup); 668 } 669 670 if( !triggers_exist ){ 671 /* Close all tables opened */ 672 sqlite3VdbeAddOp(v, OP_Close, base, 0); 673 for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){ 674 sqlite3VdbeAddOp(v, OP_Close, idx+base, 0); 675 } 676 } 677 678 #ifndef SQLITE_OMIT_AUTOINCREMENT 679 /* Update the sqlite_sequence table by storing the content of the 680 ** counter value in memory counterMem back into the sqlite_sequence 681 ** table. 682 */ 683 if( pTab->autoInc ){ 684 int iCur = pParse->nTab; 685 int base = sqlite3VdbeCurrentAddr(v); 686 sqlite3VdbeAddOp(v, OP_Integer, pTab->iDb, 0); 687 sqlite3VdbeAddOp(v, OP_OpenWrite, iCur, pDb->pSeqTab->tnum); 688 sqlite3VdbeAddOp(v, OP_SetNumColumns, iCur, 2); 689 sqlite3VdbeAddOp(v, OP_MemLoad, counterRowid, 0); 690 sqlite3VdbeAddOp(v, OP_NotNull, -1, base+7); 691 sqlite3VdbeAddOp(v, OP_Pop, 1, 0); 692 sqlite3VdbeAddOp(v, OP_NewRowid, iCur, 0); 693 sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0); 694 sqlite3VdbeAddOp(v, OP_MemLoad, counterMem, 0); 695 sqlite3VdbeAddOp(v, OP_MakeRecord, 2, 0); 696 sqlite3VdbeAddOp(v, OP_Insert, iCur, 0); 697 sqlite3VdbeAddOp(v, OP_Close, iCur, 0); 698 } 699 #endif 700 701 /* 702 ** Return the number of rows inserted. If this routine is 703 ** generating code because of a call to sqlite3NestedParse(), do not 704 ** invoke the callback function. 705 */ 706 if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){ 707 sqlite3VdbeAddOp(v, OP_MemLoad, iCntMem, 0); 708 sqlite3VdbeAddOp(v, OP_Callback, 1, 0); 709 sqlite3VdbeSetNumCols(v, 1); 710 sqlite3VdbeSetColName(v, 0, "rows inserted", P3_STATIC); 711 } 712 713 insert_cleanup: 714 sqlite3SrcListDelete(pTabList); 715 sqlite3ExprListDelete(pList); 716 sqlite3SelectDelete(pSelect); 717 sqlite3IdListDelete(pColumn); 718 } 719 720 /* 721 ** Generate code to do a constraint check prior to an INSERT or an UPDATE. 722 ** 723 ** When this routine is called, the stack contains (from bottom to top) 724 ** the following values: 725 ** 726 ** 1. The rowid of the row to be updated before the update. This 727 ** value is omitted unless we are doing an UPDATE that involves a 728 ** change to the record number. 729 ** 730 ** 2. The rowid of the row after the update. 731 ** 732 ** 3. The data in the first column of the entry after the update. 733 ** 734 ** i. Data from middle columns... 735 ** 736 ** N. The data in the last column of the entry after the update. 737 ** 738 ** The old rowid shown as entry (1) above is omitted unless both isUpdate 739 ** and rowidChng are 1. isUpdate is true for UPDATEs and false for 740 ** INSERTs and rowidChng is true if the record number is being changed. 741 ** 742 ** The code generated by this routine pushes additional entries onto 743 ** the stack which are the keys for new index entries for the new record. 744 ** The order of index keys is the same as the order of the indices on 745 ** the pTable->pIndex list. A key is only created for index i if 746 ** aIdxUsed!=0 and aIdxUsed[i]!=0. 747 ** 748 ** This routine also generates code to check constraints. NOT NULL, 749 ** CHECK, and UNIQUE constraints are all checked. If a constraint fails, 750 ** then the appropriate action is performed. There are five possible 751 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE. 752 ** 753 ** Constraint type Action What Happens 754 ** --------------- ---------- ---------------------------------------- 755 ** any ROLLBACK The current transaction is rolled back and 756 ** sqlite3_exec() returns immediately with a 757 ** return code of SQLITE_CONSTRAINT. 758 ** 759 ** any ABORT Back out changes from the current command 760 ** only (do not do a complete rollback) then 761 ** cause sqlite3_exec() to return immediately 762 ** with SQLITE_CONSTRAINT. 763 ** 764 ** any FAIL Sqlite_exec() returns immediately with a 765 ** return code of SQLITE_CONSTRAINT. The 766 ** transaction is not rolled back and any 767 ** prior changes are retained. 768 ** 769 ** any IGNORE The record number and data is popped from 770 ** the stack and there is an immediate jump 771 ** to label ignoreDest. 772 ** 773 ** NOT NULL REPLACE The NULL value is replace by the default 774 ** value for that column. If the default value 775 ** is NULL, the action is the same as ABORT. 776 ** 777 ** UNIQUE REPLACE The other row that conflicts with the row 778 ** being inserted is removed. 779 ** 780 ** CHECK REPLACE Illegal. The results in an exception. 781 ** 782 ** Which action to take is determined by the overrideError parameter. 783 ** Or if overrideError==OE_Default, then the pParse->onError parameter 784 ** is used. Or if pParse->onError==OE_Default then the onError value 785 ** for the constraint is used. 786 ** 787 ** The calling routine must open a read/write cursor for pTab with 788 ** cursor number "base". All indices of pTab must also have open 789 ** read/write cursors with cursor number base+i for the i-th cursor. 790 ** Except, if there is no possibility of a REPLACE action then 791 ** cursors do not need to be open for indices where aIdxUsed[i]==0. 792 ** 793 ** If the isUpdate flag is true, it means that the "base" cursor is 794 ** initially pointing to an entry that is being updated. The isUpdate 795 ** flag causes extra code to be generated so that the "base" cursor 796 ** is still pointing at the same entry after the routine returns. 797 ** Without the isUpdate flag, the "base" cursor might be moved. 798 */ 799 void sqlite3GenerateConstraintChecks( 800 Parse *pParse, /* The parser context */ 801 Table *pTab, /* the table into which we are inserting */ 802 int base, /* Index of a read/write cursor pointing at pTab */ 803 char *aIdxUsed, /* Which indices are used. NULL means all are used */ 804 int rowidChng, /* True if the record number will change */ 805 int isUpdate, /* True for UPDATE, False for INSERT */ 806 int overrideError, /* Override onError to this if not OE_Default */ 807 int ignoreDest /* Jump to this label on an OE_Ignore resolution */ 808 ){ 809 int i; 810 Vdbe *v; 811 int nCol; 812 int onError; 813 int addr; 814 int extra; 815 int iCur; 816 Index *pIdx; 817 int seenReplace = 0; 818 int jumpInst1=0, jumpInst2; 819 int hasTwoRowids = (isUpdate && rowidChng); 820 821 v = sqlite3GetVdbe(pParse); 822 assert( v!=0 ); 823 assert( pTab->pSelect==0 ); /* This table is not a VIEW */ 824 nCol = pTab->nCol; 825 826 /* Test all NOT NULL constraints. 827 */ 828 for(i=0; i<nCol; i++){ 829 if( i==pTab->iPKey ){ 830 continue; 831 } 832 onError = pTab->aCol[i].notNull; 833 if( onError==OE_None ) continue; 834 if( overrideError!=OE_Default ){ 835 onError = overrideError; 836 }else if( onError==OE_Default ){ 837 onError = OE_Abort; 838 } 839 if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){ 840 onError = OE_Abort; 841 } 842 sqlite3VdbeAddOp(v, OP_Dup, nCol-1-i, 1); 843 addr = sqlite3VdbeAddOp(v, OP_NotNull, 1, 0); 844 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail 845 || onError==OE_Ignore || onError==OE_Replace ); 846 switch( onError ){ 847 case OE_Rollback: 848 case OE_Abort: 849 case OE_Fail: { 850 char *zMsg = 0; 851 sqlite3VdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError); 852 sqlite3SetString(&zMsg, pTab->zName, ".", pTab->aCol[i].zName, 853 " may not be NULL", (char*)0); 854 sqlite3VdbeChangeP3(v, -1, zMsg, P3_DYNAMIC); 855 break; 856 } 857 case OE_Ignore: { 858 sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0); 859 sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest); 860 break; 861 } 862 case OE_Replace: { 863 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt); 864 sqlite3VdbeAddOp(v, OP_Push, nCol-i, 0); 865 break; 866 } 867 } 868 sqlite3VdbeJumpHere(v, addr); 869 } 870 871 /* Test all CHECK constraints 872 */ 873 /**** TBD ****/ 874 875 /* If we have an INTEGER PRIMARY KEY, make sure the primary key 876 ** of the new record does not previously exist. Except, if this 877 ** is an UPDATE and the primary key is not changing, that is OK. 878 */ 879 if( rowidChng ){ 880 onError = pTab->keyConf; 881 if( overrideError!=OE_Default ){ 882 onError = overrideError; 883 }else if( onError==OE_Default ){ 884 onError = OE_Abort; 885 } 886 887 if( isUpdate ){ 888 sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1); 889 sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1); 890 jumpInst1 = sqlite3VdbeAddOp(v, OP_Eq, 0, 0); 891 } 892 sqlite3VdbeAddOp(v, OP_Dup, nCol, 1); 893 jumpInst2 = sqlite3VdbeAddOp(v, OP_NotExists, base, 0); 894 switch( onError ){ 895 default: { 896 onError = OE_Abort; 897 /* Fall thru into the next case */ 898 } 899 case OE_Rollback: 900 case OE_Abort: 901 case OE_Fail: { 902 sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError, 903 "PRIMARY KEY must be unique", P3_STATIC); 904 break; 905 } 906 case OE_Replace: { 907 sqlite3GenerateRowIndexDelete(pParse->db, v, pTab, base, 0); 908 if( isUpdate ){ 909 sqlite3VdbeAddOp(v, OP_Dup, nCol+hasTwoRowids, 1); 910 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0); 911 } 912 seenReplace = 1; 913 break; 914 } 915 case OE_Ignore: { 916 assert( seenReplace==0 ); 917 sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0); 918 sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest); 919 break; 920 } 921 } 922 sqlite3VdbeJumpHere(v, jumpInst2); 923 if( isUpdate ){ 924 sqlite3VdbeJumpHere(v, jumpInst1); 925 sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1); 926 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0); 927 } 928 } 929 930 /* Test all UNIQUE constraints by creating entries for each UNIQUE 931 ** index and making sure that duplicate entries do not already exist. 932 ** Add the new records to the indices as we go. 933 */ 934 extra = -1; 935 for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){ 936 if( aIdxUsed && aIdxUsed[iCur]==0 ) continue; /* Skip unused indices */ 937 extra++; 938 939 /* Create a key for accessing the index entry */ 940 sqlite3VdbeAddOp(v, OP_Dup, nCol+extra, 1); 941 for(i=0; i<pIdx->nColumn; i++){ 942 int idx = pIdx->aiColumn[i]; 943 if( idx==pTab->iPKey ){ 944 sqlite3VdbeAddOp(v, OP_Dup, i+extra+nCol+1, 1); 945 }else{ 946 sqlite3VdbeAddOp(v, OP_Dup, i+extra+nCol-idx, 1); 947 } 948 } 949 jumpInst1 = sqlite3VdbeAddOp(v, OP_MakeIdxRec, pIdx->nColumn, 0); 950 sqlite3IndexAffinityStr(v, pIdx); 951 952 /* Find out what action to take in case there is an indexing conflict */ 953 onError = pIdx->onError; 954 if( onError==OE_None ) continue; /* pIdx is not a UNIQUE index */ 955 if( overrideError!=OE_Default ){ 956 onError = overrideError; 957 }else if( onError==OE_Default ){ 958 onError = OE_Abort; 959 } 960 if( seenReplace ){ 961 if( onError==OE_Ignore ) onError = OE_Replace; 962 else if( onError==OE_Fail ) onError = OE_Abort; 963 } 964 965 966 /* Check to see if the new index entry will be unique */ 967 sqlite3VdbeAddOp(v, OP_Dup, extra+nCol+1+hasTwoRowids, 1); 968 jumpInst2 = sqlite3VdbeAddOp(v, OP_IsUnique, base+iCur+1, 0); 969 970 /* Generate code that executes if the new index entry is not unique */ 971 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail 972 || onError==OE_Ignore || onError==OE_Replace ); 973 switch( onError ){ 974 case OE_Rollback: 975 case OE_Abort: 976 case OE_Fail: { 977 int j, n1, n2; 978 char zErrMsg[200]; 979 strcpy(zErrMsg, pIdx->nColumn>1 ? "columns " : "column "); 980 n1 = strlen(zErrMsg); 981 for(j=0; j<pIdx->nColumn && n1<sizeof(zErrMsg)-30; j++){ 982 char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName; 983 n2 = strlen(zCol); 984 if( j>0 ){ 985 strcpy(&zErrMsg[n1], ", "); 986 n1 += 2; 987 } 988 if( n1+n2>sizeof(zErrMsg)-30 ){ 989 strcpy(&zErrMsg[n1], "..."); 990 n1 += 3; 991 break; 992 }else{ 993 strcpy(&zErrMsg[n1], zCol); 994 n1 += n2; 995 } 996 } 997 strcpy(&zErrMsg[n1], 998 pIdx->nColumn>1 ? " are not unique" : " is not unique"); 999 sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError, zErrMsg, 0); 1000 break; 1001 } 1002 case OE_Ignore: { 1003 assert( seenReplace==0 ); 1004 sqlite3VdbeAddOp(v, OP_Pop, nCol+extra+3+hasTwoRowids, 0); 1005 sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest); 1006 break; 1007 } 1008 case OE_Replace: { 1009 sqlite3GenerateRowDelete(pParse->db, v, pTab, base, 0); 1010 if( isUpdate ){ 1011 sqlite3VdbeAddOp(v, OP_Dup, nCol+extra+1+hasTwoRowids, 1); 1012 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0); 1013 } 1014 seenReplace = 1; 1015 break; 1016 } 1017 } 1018 #if NULL_DISTINCT_FOR_UNIQUE 1019 sqlite3VdbeJumpHere(v, jumpInst1); 1020 #endif 1021 sqlite3VdbeJumpHere(v, jumpInst2); 1022 } 1023 } 1024 1025 /* 1026 ** This routine generates code to finish the INSERT or UPDATE operation 1027 ** that was started by a prior call to sqlite3GenerateConstraintChecks. 1028 ** The stack must contain keys for all active indices followed by data 1029 ** and the rowid for the new entry. This routine creates the new 1030 ** entries in all indices and in the main table. 1031 ** 1032 ** The arguments to this routine should be the same as the first six 1033 ** arguments to sqlite3GenerateConstraintChecks. 1034 */ 1035 void sqlite3CompleteInsertion( 1036 Parse *pParse, /* The parser context */ 1037 Table *pTab, /* the table into which we are inserting */ 1038 int base, /* Index of a read/write cursor pointing at pTab */ 1039 char *aIdxUsed, /* Which indices are used. NULL means all are used */ 1040 int rowidChng, /* True if the record number will change */ 1041 int isUpdate, /* True for UPDATE, False for INSERT */ 1042 int newIdx /* Index of NEW table for triggers. -1 if none */ 1043 ){ 1044 int i; 1045 Vdbe *v; 1046 int nIdx; 1047 Index *pIdx; 1048 int pik_flags; 1049 1050 v = sqlite3GetVdbe(pParse); 1051 assert( v!=0 ); 1052 assert( pTab->pSelect==0 ); /* This table is not a VIEW */ 1053 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){} 1054 for(i=nIdx-1; i>=0; i--){ 1055 if( aIdxUsed && aIdxUsed[i]==0 ) continue; 1056 sqlite3VdbeAddOp(v, OP_IdxInsert, base+i+1, 0); 1057 } 1058 sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0); 1059 sqlite3TableAffinityStr(v, pTab); 1060 #ifndef SQLITE_OMIT_TRIGGER 1061 if( newIdx>=0 ){ 1062 sqlite3VdbeAddOp(v, OP_Dup, 1, 0); 1063 sqlite3VdbeAddOp(v, OP_Dup, 1, 0); 1064 sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0); 1065 } 1066 #endif 1067 if( pParse->nested ){ 1068 pik_flags = 0; 1069 }else{ 1070 pik_flags = (OPFLAG_NCHANGE|(isUpdate?0:OPFLAG_LASTROWID)); 1071 } 1072 sqlite3VdbeAddOp(v, OP_Insert, base, pik_flags); 1073 1074 if( isUpdate && rowidChng ){ 1075 sqlite3VdbeAddOp(v, OP_Pop, 1, 0); 1076 } 1077 } 1078 1079 /* 1080 ** Generate code that will open cursors for a table and for all 1081 ** indices of that table. The "base" parameter is the cursor number used 1082 ** for the table. Indices are opened on subsequent cursors. 1083 */ 1084 void sqlite3OpenTableAndIndices( 1085 Parse *pParse, /* Parsing context */ 1086 Table *pTab, /* Table to be opened */ 1087 int base, /* Cursor number assigned to the table */ 1088 int op /* OP_OpenRead or OP_OpenWrite */ 1089 ){ 1090 int i; 1091 Index *pIdx; 1092 Vdbe *v = sqlite3GetVdbe(pParse); 1093 assert( v!=0 ); 1094 sqlite3VdbeAddOp(v, OP_Integer, pTab->iDb, 0); 1095 VdbeComment((v, "# %s", pTab->zName)); 1096 sqlite3VdbeAddOp(v, op, base, pTab->tnum); 1097 sqlite3VdbeAddOp(v, OP_SetNumColumns, base, pTab->nCol); 1098 for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ 1099 sqlite3VdbeAddOp(v, OP_Integer, pIdx->iDb, 0); 1100 VdbeComment((v, "# %s", pIdx->zName)); 1101 sqlite3VdbeOp3(v, op, i+base, pIdx->tnum, 1102 (char*)&pIdx->keyInfo, P3_KEYINFO); 1103 } 1104 if( pParse->nTab<=base+i ){ 1105 pParse->nTab = base+i; 1106 } 1107 } 1108