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