00001 /* 00002 ** 2001 September 15 00003 ** 00004 ** The author disclaims copyright to this source code. In place of 00005 ** a legal notice, here is a blessing: 00006 ** 00007 ** May you do good and not evil. 00008 ** May you find forgiveness for yourself and forgive others. 00009 ** May you share freely, never taking more than you give. 00010 ** 00011 ************************************************************************* 00012 ** This file contains C code routines that are called by the parser 00013 ** to handle INSERT statements in SQLite. 00014 ** 00015 ** $Id: insert.c,v 1.251 2008/11/03 20:55:07 drh Exp $ 00016 */ 00017 #include "sqliteInt.h" 00018 00019 /* 00020 ** Set P4 of the most recently inserted opcode to a column affinity 00021 ** string for index pIdx. A column affinity string has one character 00022 ** for each column in the table, according to the affinity of the column: 00023 ** 00024 ** Character Column affinity 00025 ** ------------------------------ 00026 ** 'a' TEXT 00027 ** 'b' NONE 00028 ** 'c' NUMERIC 00029 ** 'd' INTEGER 00030 ** 'e' REAL 00031 ** 00032 ** An extra 'b' is appended to the end of the string to cover the 00033 ** rowid that appears as the last column in every index. 00034 */ 00035 void sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){ 00036 if( !pIdx->zColAff ){ 00037 /* The first time a column affinity string for a particular index is 00038 ** required, it is allocated and populated here. It is then stored as 00039 ** a member of the Index structure for subsequent use. 00040 ** 00041 ** The column affinity string will eventually be deleted by 00042 ** sqliteDeleteIndex() when the Index structure itself is cleaned 00043 ** up. 00044 */ 00045 int n; 00046 Table *pTab = pIdx->pTable; 00047 sqlite3 *db = sqlite3VdbeDb(v); 00048 pIdx->zColAff = (char *)sqlite3Malloc(pIdx->nColumn+2); 00049 if( !pIdx->zColAff ){ 00050 db->mallocFailed = 1; 00051 return; 00052 } 00053 for(n=0; n<pIdx->nColumn; n++){ 00054 pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity; 00055 } 00056 pIdx->zColAff[n++] = SQLITE_AFF_NONE; 00057 pIdx->zColAff[n] = 0; 00058 } 00059 00060 sqlite3VdbeChangeP4(v, -1, pIdx->zColAff, 0); 00061 } 00062 00063 /* 00064 ** Set P4 of the most recently inserted opcode to a column affinity 00065 ** string for table pTab. A column affinity string has one character 00066 ** for each column indexed by the index, according to the affinity of the 00067 ** column: 00068 ** 00069 ** Character Column affinity 00070 ** ------------------------------ 00071 ** 'a' TEXT 00072 ** 'b' NONE 00073 ** 'c' NUMERIC 00074 ** 'd' INTEGER 00075 ** 'e' REAL 00076 */ 00077 void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){ 00078 /* The first time a column affinity string for a particular table 00079 ** is required, it is allocated and populated here. It is then 00080 ** stored as a member of the Table structure for subsequent use. 00081 ** 00082 ** The column affinity string will eventually be deleted by 00083 ** sqlite3DeleteTable() when the Table structure itself is cleaned up. 00084 */ 00085 if( !pTab->zColAff ){ 00086 char *zColAff; 00087 int i; 00088 sqlite3 *db = sqlite3VdbeDb(v); 00089 00090 zColAff = (char *)sqlite3Malloc(pTab->nCol+1); 00091 if( !zColAff ){ 00092 db->mallocFailed = 1; 00093 return; 00094 } 00095 00096 for(i=0; i<pTab->nCol; i++){ 00097 zColAff[i] = pTab->aCol[i].affinity; 00098 } 00099 zColAff[pTab->nCol] = '\0'; 00100 00101 pTab->zColAff = zColAff; 00102 } 00103 00104 sqlite3VdbeChangeP4(v, -1, pTab->zColAff, 0); 00105 } 00106 00107 /* 00108 ** Return non-zero if the table pTab in database iDb or any of its indices 00109 ** have been opened at any point in the VDBE program beginning at location 00110 ** iStartAddr throught the end of the program. This is used to see if 00111 ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can 00112 ** run without using temporary table for the results of the SELECT. 00113 */ 00114 static int readsTable(Vdbe *v, int iStartAddr, int iDb, Table *pTab){ 00115 int i; 00116 int iEnd = sqlite3VdbeCurrentAddr(v); 00117 for(i=iStartAddr; i<iEnd; i++){ 00118 VdbeOp *pOp = sqlite3VdbeGetOp(v, i); 00119 assert( pOp!=0 ); 00120 if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){ 00121 Index *pIndex; 00122 int tnum = pOp->p2; 00123 if( tnum==pTab->tnum ){ 00124 return 1; 00125 } 00126 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){ 00127 if( tnum==pIndex->tnum ){ 00128 return 1; 00129 } 00130 } 00131 } 00132 #ifndef SQLITE_OMIT_VIRTUALTABLE 00133 if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pTab->pVtab ){ 00134 assert( pOp->p4.pVtab!=0 ); 00135 assert( pOp->p4type==P4_VTAB ); 00136 return 1; 00137 } 00138 #endif 00139 } 00140 return 0; 00141 } 00142 00143 #ifndef SQLITE_OMIT_AUTOINCREMENT 00144 /* 00145 ** Write out code to initialize the autoincrement logic. This code 00146 ** looks up the current autoincrement value in the sqlite_sequence 00147 ** table and stores that value in a register. Code generated by 00148 ** autoIncStep() will keep that register holding the largest 00149 ** rowid value. Code generated by autoIncEnd() will write the new 00150 ** largest value of the counter back into the sqlite_sequence table. 00151 ** 00152 ** This routine returns the index of the mem[] cell that contains 00153 ** the maximum rowid counter. 00154 ** 00155 ** Three consecutive registers are allocated by this routine. The 00156 ** first two hold the name of the target table and the maximum rowid 00157 ** inserted into the target table, respectively. 00158 ** The third holds the rowid in sqlite_sequence where we will 00159 ** write back the revised maximum rowid. This routine returns the 00160 ** index of the second of these three registers. 00161 */ 00162 static int autoIncBegin( 00163 Parse *pParse, /* Parsing context */ 00164 int iDb, /* Index of the database holding pTab */ 00165 Table *pTab /* The table we are writing to */ 00166 ){ 00167 int memId = 0; /* Register holding maximum rowid */ 00168 if( pTab->tabFlags & TF_Autoincrement ){ 00169 Vdbe *v = pParse->pVdbe; 00170 Db *pDb = &pParse->db->aDb[iDb]; 00171 int iCur = pParse->nTab; 00172 int addr; /* Address of the top of the loop */ 00173 assert( v ); 00174 pParse->nMem++; /* Holds name of table */ 00175 memId = ++pParse->nMem; 00176 pParse->nMem++; 00177 sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenRead); 00178 addr = sqlite3VdbeCurrentAddr(v); 00179 sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, pTab->zName, 0); 00180 sqlite3VdbeAddOp2(v, OP_Rewind, iCur, addr+9); 00181 sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, memId); 00182 sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId); 00183 sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL); 00184 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, memId+1); 00185 sqlite3VdbeAddOp3(v, OP_Column, iCur, 1, memId); 00186 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9); 00187 sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+2); 00188 sqlite3VdbeAddOp2(v, OP_Integer, 0, memId); 00189 sqlite3VdbeAddOp2(v, OP_Close, iCur, 0); 00190 } 00191 return memId; 00192 } 00193 00194 /* 00195 ** Update the maximum rowid for an autoincrement calculation. 00196 ** 00197 ** This routine should be called when the top of the stack holds a 00198 ** new rowid that is about to be inserted. If that new rowid is 00199 ** larger than the maximum rowid in the memId memory cell, then the 00200 ** memory cell is updated. The stack is unchanged. 00201 */ 00202 static void autoIncStep(Parse *pParse, int memId, int regRowid){ 00203 if( memId>0 ){ 00204 sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid); 00205 } 00206 } 00207 00208 /* 00209 ** After doing one or more inserts, the maximum rowid is stored 00210 ** in reg[memId]. Generate code to write this value back into the 00211 ** the sqlite_sequence table. 00212 */ 00213 static void autoIncEnd( 00214 Parse *pParse, /* The parsing context */ 00215 int iDb, /* Index of the database holding pTab */ 00216 Table *pTab, /* Table we are inserting into */ 00217 int memId /* Memory cell holding the maximum rowid */ 00218 ){ 00219 if( pTab->tabFlags & TF_Autoincrement ){ 00220 int iCur = pParse->nTab; 00221 Vdbe *v = pParse->pVdbe; 00222 Db *pDb = &pParse->db->aDb[iDb]; 00223 int j1; 00224 int iRec = ++pParse->nMem; /* Memory cell used for record */ 00225 00226 assert( v ); 00227 sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenWrite); 00228 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1); 00229 sqlite3VdbeAddOp2(v, OP_NewRowid, iCur, memId+1); 00230 sqlite3VdbeJumpHere(v, j1); 00231 sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec); 00232 sqlite3VdbeAddOp3(v, OP_Insert, iCur, iRec, memId+1); 00233 sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 00234 sqlite3VdbeAddOp1(v, OP_Close, iCur); 00235 } 00236 } 00237 #else 00238 /* 00239 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines 00240 ** above are all no-ops 00241 */ 00242 # define autoIncBegin(A,B,C) (0) 00243 # define autoIncStep(A,B,C) 00244 # define autoIncEnd(A,B,C,D) 00245 #endif /* SQLITE_OMIT_AUTOINCREMENT */ 00246 00247 00248 /* Forward declaration */ 00249 static int xferOptimization( 00250 Parse *pParse, /* Parser context */ 00251 Table *pDest, /* The table we are inserting into */ 00252 Select *pSelect, /* A SELECT statement to use as the data source */ 00253 int onError, /* How to handle constraint errors */ 00254 int iDbDest /* The database of pDest */ 00255 ); 00256 00257 /* 00258 ** This routine is call to handle SQL of the following forms: 00259 ** 00260 ** insert into TABLE (IDLIST) values(EXPRLIST) 00261 ** insert into TABLE (IDLIST) select 00262 ** 00263 ** The IDLIST following the table name is always optional. If omitted, 00264 ** then a list of all columns for the table is substituted. The IDLIST 00265 ** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted. 00266 ** 00267 ** The pList parameter holds EXPRLIST in the first form of the INSERT 00268 ** statement above, and pSelect is NULL. For the second form, pList is 00269 ** NULL and pSelect is a pointer to the select statement used to generate 00270 ** data for the insert. 00271 ** 00272 ** The code generated follows one of four templates. For a simple 00273 ** select with data coming from a VALUES clause, the code executes 00274 ** once straight down through. Pseudo-code follows (we call this 00275 ** the "1st template"): 00276 ** 00277 ** open write cursor to <table> and its indices 00278 ** puts VALUES clause expressions onto the stack 00279 ** write the resulting record into <table> 00280 ** cleanup 00281 ** 00282 ** The three remaining templates assume the statement is of the form 00283 ** 00284 ** INSERT INTO <table> SELECT ... 00285 ** 00286 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" - 00287 ** in other words if the SELECT pulls all columns from a single table 00288 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and 00289 ** if <table2> and <table1> are distinct tables but have identical 00290 ** schemas, including all the same indices, then a special optimization 00291 ** is invoked that copies raw records from <table2> over to <table1>. 00292 ** See the xferOptimization() function for the implementation of this 00293 ** template. This is the 2nd template. 00294 ** 00295 ** open a write cursor to <table> 00296 ** open read cursor on <table2> 00297 ** transfer all records in <table2> over to <table> 00298 ** close cursors 00299 ** foreach index on <table> 00300 ** open a write cursor on the <table> index 00301 ** open a read cursor on the corresponding <table2> index 00302 ** transfer all records from the read to the write cursors 00303 ** close cursors 00304 ** end foreach 00305 ** 00306 ** The 3rd template is for when the second template does not apply 00307 ** and the SELECT clause does not read from <table> at any time. 00308 ** The generated code follows this template: 00309 ** 00310 ** EOF <- 0 00311 ** X <- A 00312 ** goto B 00313 ** A: setup for the SELECT 00314 ** loop over the rows in the SELECT 00315 ** load values into registers R..R+n 00316 ** yield X 00317 ** end loop 00318 ** cleanup after the SELECT 00319 ** EOF <- 1 00320 ** yield X 00321 ** goto A 00322 ** B: open write cursor to <table> and its indices 00323 ** C: yield X 00324 ** if EOF goto D 00325 ** insert the select result into <table> from R..R+n 00326 ** goto C 00327 ** D: cleanup 00328 ** 00329 ** The 4th template is used if the insert statement takes its 00330 ** values from a SELECT but the data is being inserted into a table 00331 ** that is also read as part of the SELECT. In the third form, 00332 ** we have to use a intermediate table to store the results of 00333 ** the select. The template is like this: 00334 ** 00335 ** EOF <- 0 00336 ** X <- A 00337 ** goto B 00338 ** A: setup for the SELECT 00339 ** loop over the tables in the SELECT 00340 ** load value into register R..R+n 00341 ** yield X 00342 ** end loop 00343 ** cleanup after the SELECT 00344 ** EOF <- 1 00345 ** yield X 00346 ** halt-error 00347 ** B: open temp table 00348 ** L: yield X 00349 ** if EOF goto M 00350 ** insert row from R..R+n into temp table 00351 ** goto L 00352 ** M: open write cursor to <table> and its indices 00353 ** rewind temp table 00354 ** C: loop over rows of intermediate table 00355 ** transfer values form intermediate table into <table> 00356 ** end loop 00357 ** D: cleanup 00358 */ 00359 void sqlite3Insert( 00360 Parse *pParse, /* Parser context */ 00361 SrcList *pTabList, /* Name of table into which we are inserting */ 00362 ExprList *pList, /* List of values to be inserted */ 00363 Select *pSelect, /* A SELECT statement to use as the data source */ 00364 IdList *pColumn, /* Column names corresponding to IDLIST. */ 00365 int onError /* How to handle constraint errors */ 00366 ){ 00367 sqlite3 *db; /* The main database structure */ 00368 Table *pTab; /* The table to insert into. aka TABLE */ 00369 char *zTab; /* Name of the table into which we are inserting */ 00370 const char *zDb; /* Name of the database holding this table */ 00371 int i, j, idx; /* Loop counters */ 00372 Vdbe *v; /* Generate code into this virtual machine */ 00373 Index *pIdx; /* For looping over indices of the table */ 00374 int nColumn; /* Number of columns in the data */ 00375 int nHidden = 0; /* Number of hidden columns if TABLE is virtual */ 00376 int baseCur = 0; /* VDBE Cursor number for pTab */ 00377 int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */ 00378 int endOfLoop; /* Label for the end of the insertion loop */ 00379 int useTempTable = 0; /* Store SELECT results in intermediate table */ 00380 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */ 00381 int addrInsTop = 0; /* Jump to label "D" */ 00382 int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */ 00383 int addrSelect = 0; /* Address of coroutine that implements the SELECT */ 00384 SelectDest dest; /* Destination for SELECT on rhs of INSERT */ 00385 int newIdx = -1; /* Cursor for the NEW pseudo-table */ 00386 int iDb; /* Index of database holding TABLE */ 00387 Db *pDb; /* The database containing table being inserted into */ 00388 int appendFlag = 0; /* True if the insert is likely to be an append */ 00389 00390 /* Register allocations */ 00391 int regFromSelect; /* Base register for data coming from SELECT */ 00392 int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */ 00393 int regRowCount = 0; /* Memory cell used for the row counter */ 00394 int regIns; /* Block of regs holding rowid+data being inserted */ 00395 int regRowid; /* registers holding insert rowid */ 00396 int regData; /* register holding first column to insert */ 00397 int regRecord; /* Holds the assemblied row record */ 00398 int regEof; /* Register recording end of SELECT data */ 00399 int *aRegIdx = 0; /* One register allocated to each index */ 00400 00401 00402 #ifndef SQLITE_OMIT_TRIGGER 00403 int isView; /* True if attempting to insert into a view */ 00404 int triggers_exist = 0; /* True if there are FOR EACH ROW triggers */ 00405 #endif 00406 00407 db = pParse->db; 00408 if( pParse->nErr || db->mallocFailed ){ 00409 goto insert_cleanup; 00410 } 00411 00412 /* Locate the table into which we will be inserting new information. 00413 */ 00414 assert( pTabList->nSrc==1 ); 00415 zTab = pTabList->a[0].zName; 00416 if( zTab==0 ) goto insert_cleanup; 00417 pTab = sqlite3SrcListLookup(pParse, pTabList); 00418 if( pTab==0 ){ 00419 goto insert_cleanup; 00420 } 00421 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 00422 assert( iDb<db->nDb ); 00423 pDb = &db->aDb[iDb]; 00424 zDb = pDb->zName; 00425 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){ 00426 goto insert_cleanup; 00427 } 00428 00429 /* Figure out if we have any triggers and if the table being 00430 ** inserted into is a view 00431 */ 00432 #ifndef SQLITE_OMIT_TRIGGER 00433 triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0); 00434 isView = pTab->pSelect!=0; 00435 #else 00436 # define triggers_exist 0 00437 # define isView 0 00438 #endif 00439 #ifdef SQLITE_OMIT_VIEW 00440 # undef isView 00441 # define isView 0 00442 #endif 00443 00444 /* Ensure that: 00445 * (a) the table is not read-only, 00446 * (b) that if it is a view then ON INSERT triggers exist 00447 */ 00448 if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){ 00449 goto insert_cleanup; 00450 } 00451 assert( pTab!=0 ); 00452 00453 /* If pTab is really a view, make sure it has been initialized. 00454 ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual 00455 ** module table). 00456 */ 00457 if( sqlite3ViewGetColumnNames(pParse, pTab) ){ 00458 goto insert_cleanup; 00459 } 00460 00461 /* Allocate a VDBE 00462 */ 00463 v = sqlite3GetVdbe(pParse); 00464 if( v==0 ) goto insert_cleanup; 00465 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v); 00466 sqlite3BeginWriteOperation(pParse, pSelect || triggers_exist, iDb); 00467 00468 /* if there are row triggers, allocate a temp table for new.* references. */ 00469 if( triggers_exist ){ 00470 newIdx = pParse->nTab++; 00471 } 00472 00473 #ifndef SQLITE_OMIT_XFER_OPT 00474 /* If the statement is of the form 00475 ** 00476 ** INSERT INTO <table1> SELECT * FROM <table2>; 00477 ** 00478 ** Then special optimizations can be applied that make the transfer 00479 ** very fast and which reduce fragmentation of indices. 00480 ** 00481 ** This is the 2nd template. 00482 */ 00483 if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){ 00484 assert( !triggers_exist ); 00485 assert( pList==0 ); 00486 goto insert_cleanup; 00487 } 00488 #endif /* SQLITE_OMIT_XFER_OPT */ 00489 00490 /* If this is an AUTOINCREMENT table, look up the sequence number in the 00491 ** sqlite_sequence table and store it in memory cell regAutoinc. 00492 */ 00493 regAutoinc = autoIncBegin(pParse, iDb, pTab); 00494 00495 /* Figure out how many columns of data are supplied. If the data 00496 ** is coming from a SELECT statement, then generate a co-routine that 00497 ** produces a single row of the SELECT on each invocation. The 00498 ** co-routine is the common header to the 3rd and 4th templates. 00499 */ 00500 if( pSelect ){ 00501 /* Data is coming from a SELECT. Generate code to implement that SELECT 00502 ** as a co-routine. The code is common to both the 3rd and 4th 00503 ** templates: 00504 ** 00505 ** EOF <- 0 00506 ** X <- A 00507 ** goto B 00508 ** A: setup for the SELECT 00509 ** loop over the tables in the SELECT 00510 ** load value into register R..R+n 00511 ** yield X 00512 ** end loop 00513 ** cleanup after the SELECT 00514 ** EOF <- 1 00515 ** yield X 00516 ** halt-error 00517 ** 00518 ** On each invocation of the co-routine, it puts a single row of the 00519 ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1. 00520 ** (These output registers are allocated by sqlite3Select().) When 00521 ** the SELECT completes, it sets the EOF flag stored in regEof. 00522 */ 00523 int rc, j1; 00524 00525 regEof = ++pParse->nMem; 00526 sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof); /* EOF <- 0 */ 00527 VdbeComment((v, "SELECT eof flag")); 00528 sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem); 00529 addrSelect = sqlite3VdbeCurrentAddr(v)+2; 00530 sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm); 00531 j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0); 00532 VdbeComment((v, "Jump over SELECT coroutine")); 00533 00534 /* Resolve the expressions in the SELECT statement and execute it. */ 00535 rc = sqlite3Select(pParse, pSelect, &dest); 00536 if( rc || pParse->nErr || db->mallocFailed ){ 00537 goto insert_cleanup; 00538 } 00539 sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof); /* EOF <- 1 */ 00540 sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm); /* yield X */ 00541 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort); 00542 VdbeComment((v, "End of SELECT coroutine")); 00543 sqlite3VdbeJumpHere(v, j1); /* label B: */ 00544 00545 regFromSelect = dest.iMem; 00546 assert( pSelect->pEList ); 00547 nColumn = pSelect->pEList->nExpr; 00548 assert( dest.nMem==nColumn ); 00549 00550 /* Set useTempTable to TRUE if the result of the SELECT statement 00551 ** should be written into a temporary table (template 4). Set to 00552 ** FALSE if each* row of the SELECT can be written directly into 00553 ** the destination table (template 3). 00554 ** 00555 ** A temp table must be used if the table being updated is also one 00556 ** of the tables being read by the SELECT statement. Also use a 00557 ** temp table in the case of row triggers. 00558 */ 00559 if( triggers_exist || readsTable(v, addrSelect, iDb, pTab) ){ 00560 useTempTable = 1; 00561 } 00562 00563 if( useTempTable ){ 00564 /* Invoke the coroutine to extract information from the SELECT 00565 ** and add it to a transient table srcTab. The code generated 00566 ** here is from the 4th template: 00567 ** 00568 ** B: open temp table 00569 ** L: yield X 00570 ** if EOF goto M 00571 ** insert row from R..R+n into temp table 00572 ** goto L 00573 ** M: ... 00574 */ 00575 int regRec; /* Register to hold packed record */ 00576 int regRowid; /* Register to hold temp table ROWID */ 00577 int addrTop; /* Label "L" */ 00578 int addrIf; /* Address of jump to M */ 00579 00580 srcTab = pParse->nTab++; 00581 regRec = sqlite3GetTempReg(pParse); 00582 regRowid = sqlite3GetTempReg(pParse); 00583 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn); 00584 addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm); 00585 addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof); 00586 sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec); 00587 sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regRowid); 00588 sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regRowid); 00589 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop); 00590 sqlite3VdbeJumpHere(v, addrIf); 00591 sqlite3ReleaseTempReg(pParse, regRec); 00592 sqlite3ReleaseTempReg(pParse, regRowid); 00593 } 00594 }else{ 00595 /* This is the case if the data for the INSERT is coming from a VALUES 00596 ** clause 00597 */ 00598 NameContext sNC; 00599 memset(&sNC, 0, sizeof(sNC)); 00600 sNC.pParse = pParse; 00601 srcTab = -1; 00602 assert( useTempTable==0 ); 00603 nColumn = pList ? pList->nExpr : 0; 00604 for(i=0; i<nColumn; i++){ 00605 if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){ 00606 goto insert_cleanup; 00607 } 00608 } 00609 } 00610 00611 /* Make sure the number of columns in the source data matches the number 00612 ** of columns to be inserted into the table. 00613 */ 00614 if( IsVirtual(pTab) ){ 00615 for(i=0; i<pTab->nCol; i++){ 00616 nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0); 00617 } 00618 } 00619 if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){ 00620 sqlite3ErrorMsg(pParse, 00621 "table %S has %d columns but %d values were supplied", 00622 pTabList, 0, pTab->nCol, nColumn); 00623 goto insert_cleanup; 00624 } 00625 if( pColumn!=0 && nColumn!=pColumn->nId ){ 00626 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId); 00627 goto insert_cleanup; 00628 } 00629 00630 /* If the INSERT statement included an IDLIST term, then make sure 00631 ** all elements of the IDLIST really are columns of the table and 00632 ** remember the column indices. 00633 ** 00634 ** If the table has an INTEGER PRIMARY KEY column and that column 00635 ** is named in the IDLIST, then record in the keyColumn variable 00636 ** the index into IDLIST of the primary key column. keyColumn is 00637 ** the index of the primary key as it appears in IDLIST, not as 00638 ** is appears in the original table. (The index of the primary 00639 ** key in the original table is pTab->iPKey.) 00640 */ 00641 if( pColumn ){ 00642 for(i=0; i<pColumn->nId; i++){ 00643 pColumn->a[i].idx = -1; 00644 } 00645 for(i=0; i<pColumn->nId; i++){ 00646 for(j=0; j<pTab->nCol; j++){ 00647 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){ 00648 pColumn->a[i].idx = j; 00649 if( j==pTab->iPKey ){ 00650 keyColumn = i; 00651 } 00652 break; 00653 } 00654 } 00655 if( j>=pTab->nCol ){ 00656 if( sqlite3IsRowid(pColumn->a[i].zName) ){ 00657 keyColumn = i; 00658 }else{ 00659 sqlite3ErrorMsg(pParse, "table %S has no column named %s", 00660 pTabList, 0, pColumn->a[i].zName); 00661 pParse->nErr++; 00662 goto insert_cleanup; 00663 } 00664 } 00665 } 00666 } 00667 00668 /* If there is no IDLIST term but the table has an integer primary 00669 ** key, the set the keyColumn variable to the primary key column index 00670 ** in the original table definition. 00671 */ 00672 if( pColumn==0 && nColumn>0 ){ 00673 keyColumn = pTab->iPKey; 00674 } 00675 00676 /* Open the temp table for FOR EACH ROW triggers 00677 */ 00678 if( triggers_exist ){ 00679 sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol); 00680 sqlite3VdbeAddOp2(v, OP_OpenPseudo, newIdx, 0); 00681 } 00682 00683 /* Initialize the count of rows to be inserted 00684 */ 00685 if( db->flags & SQLITE_CountRows ){ 00686 regRowCount = ++pParse->nMem; 00687 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount); 00688 } 00689 00690 /* If this is not a view, open the table and and all indices */ 00691 if( !isView ){ 00692 int nIdx; 00693 int i; 00694 00695 baseCur = pParse->nTab; 00696 nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite); 00697 aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1)); 00698 if( aRegIdx==0 ){ 00699 goto insert_cleanup; 00700 } 00701 for(i=0; i<nIdx; i++){ 00702 aRegIdx[i] = ++pParse->nMem; 00703 } 00704 } 00705 00706 /* This is the top of the main insertion loop */ 00707 if( useTempTable ){ 00708 /* This block codes the top of loop only. The complete loop is the 00709 ** following pseudocode (template 4): 00710 ** 00711 ** rewind temp table 00712 ** C: loop over rows of intermediate table 00713 ** transfer values form intermediate table into <table> 00714 ** end loop 00715 ** D: ... 00716 */ 00717 addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); 00718 addrCont = sqlite3VdbeCurrentAddr(v); 00719 }else if( pSelect ){ 00720 /* This block codes the top of loop only. The complete loop is the 00721 ** following pseudocode (template 3): 00722 ** 00723 ** C: yield X 00724 ** if EOF goto D 00725 ** insert the select result into <table> from R..R+n 00726 ** goto C 00727 ** D: ... 00728 */ 00729 addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm); 00730 addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof); 00731 } 00732 00733 /* Allocate registers for holding the rowid of the new row, 00734 ** the content of the new row, and the assemblied row record. 00735 */ 00736 regRecord = ++pParse->nMem; 00737 regRowid = regIns = pParse->nMem+1; 00738 pParse->nMem += pTab->nCol + 1; 00739 if( IsVirtual(pTab) ){ 00740 regRowid++; 00741 pParse->nMem++; 00742 } 00743 regData = regRowid+1; 00744 00745 /* Run the BEFORE and INSTEAD OF triggers, if there are any 00746 */ 00747 endOfLoop = sqlite3VdbeMakeLabel(v); 00748 if( triggers_exist & TRIGGER_BEFORE ){ 00749 int regRowid; 00750 int regCols; 00751 int regRec; 00752 00753 /* build the NEW.* reference row. Note that if there is an INTEGER 00754 ** PRIMARY KEY into which a NULL is being inserted, that NULL will be 00755 ** translated into a unique ID for the row. But on a BEFORE trigger, 00756 ** we do not know what the unique ID will be (because the insert has 00757 ** not happened yet) so we substitute a rowid of -1 00758 */ 00759 regRowid = sqlite3GetTempReg(pParse); 00760 if( keyColumn<0 ){ 00761 sqlite3VdbeAddOp2(v, OP_Integer, -1, regRowid); 00762 }else if( useTempTable ){ 00763 sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid); 00764 }else{ 00765 int j1; 00766 assert( pSelect==0 ); /* Otherwise useTempTable is true */ 00767 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid); 00768 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); 00769 sqlite3VdbeAddOp2(v, OP_Integer, -1, regRowid); 00770 sqlite3VdbeJumpHere(v, j1); 00771 sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); 00772 } 00773 00774 /* Cannot have triggers on a virtual table. If it were possible, 00775 ** this block would have to account for hidden column. 00776 */ 00777 assert(!IsVirtual(pTab)); 00778 00779 /* Create the new column data 00780 */ 00781 regCols = sqlite3GetTempRange(pParse, pTab->nCol); 00782 for(i=0; i<pTab->nCol; i++){ 00783 if( pColumn==0 ){ 00784 j = i; 00785 }else{ 00786 for(j=0; j<pColumn->nId; j++){ 00787 if( pColumn->a[j].idx==i ) break; 00788 } 00789 } 00790 if( pColumn && j>=pColumn->nId ){ 00791 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i); 00792 }else if( useTempTable ){ 00793 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i); 00794 }else{ 00795 assert( pSelect==0 ); /* Otherwise useTempTable is true */ 00796 sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i); 00797 } 00798 } 00799 regRec = sqlite3GetTempReg(pParse); 00800 sqlite3VdbeAddOp3(v, OP_MakeRecord, regCols, pTab->nCol, regRec); 00801 00802 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger, 00803 ** do not attempt any conversions before assembling the record. 00804 ** If this is a real table, attempt conversions as required by the 00805 ** table column affinities. 00806 */ 00807 if( !isView ){ 00808 sqlite3TableAffinityStr(v, pTab); 00809 } 00810 sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regRowid); 00811 sqlite3ReleaseTempReg(pParse, regRec); 00812 sqlite3ReleaseTempReg(pParse, regRowid); 00813 sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol); 00814 00815 /* Fire BEFORE or INSTEAD OF triggers */ 00816 if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_BEFORE, pTab, 00817 newIdx, -1, onError, endOfLoop, 0, 0) ){ 00818 goto insert_cleanup; 00819 } 00820 } 00821 00822 /* Push the record number for the new entry onto the stack. The 00823 ** record number is a randomly generate integer created by NewRowid 00824 ** except when the table has an INTEGER PRIMARY KEY column, in which 00825 ** case the record number is the same as that column. 00826 */ 00827 if( !isView ){ 00828 if( IsVirtual(pTab) ){ 00829 /* The row that the VUpdate opcode will delete: none */ 00830 sqlite3VdbeAddOp2(v, OP_Null, 0, regIns); 00831 } 00832 if( keyColumn>=0 ){ 00833 if( useTempTable ){ 00834 sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid); 00835 }else if( pSelect ){ 00836 sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid); 00837 }else{ 00838 VdbeOp *pOp; 00839 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid); 00840 pOp = sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v) - 1); 00841 if( pOp && pOp->opcode==OP_Null && !IsVirtual(pTab) ){ 00842 appendFlag = 1; 00843 pOp->opcode = OP_NewRowid; 00844 pOp->p1 = baseCur; 00845 pOp->p2 = regRowid; 00846 pOp->p3 = regAutoinc; 00847 } 00848 } 00849 /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid 00850 ** to generate a unique primary key value. 00851 */ 00852 if( !appendFlag ){ 00853 int j1; 00854 if( !IsVirtual(pTab) ){ 00855 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); 00856 sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc); 00857 sqlite3VdbeJumpHere(v, j1); 00858 }else{ 00859 j1 = sqlite3VdbeCurrentAddr(v); 00860 sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2); 00861 } 00862 sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); 00863 } 00864 }else if( IsVirtual(pTab) ){ 00865 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid); 00866 }else{ 00867 sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc); 00868 appendFlag = 1; 00869 } 00870 autoIncStep(pParse, regAutoinc, regRowid); 00871 00872 /* Push onto the stack, data for all columns of the new entry, beginning 00873 ** with the first column. 00874 */ 00875 nHidden = 0; 00876 for(i=0; i<pTab->nCol; i++){ 00877 int iRegStore = regRowid+1+i; 00878 if( i==pTab->iPKey ){ 00879 /* The value of the INTEGER PRIMARY KEY column is always a NULL. 00880 ** Whenever this column is read, the record number will be substituted 00881 ** in its place. So will fill this column with a NULL to avoid 00882 ** taking up data space with information that will never be used. */ 00883 sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore); 00884 continue; 00885 } 00886 if( pColumn==0 ){ 00887 if( IsHiddenColumn(&pTab->aCol[i]) ){ 00888 assert( IsVirtual(pTab) ); 00889 j = -1; 00890 nHidden++; 00891 }else{ 00892 j = i - nHidden; 00893 } 00894 }else{ 00895 for(j=0; j<pColumn->nId; j++){ 00896 if( pColumn->a[j].idx==i ) break; 00897 } 00898 } 00899 if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){ 00900 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore); 00901 }else if( useTempTable ){ 00902 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); 00903 }else if( pSelect ){ 00904 sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore); 00905 }else{ 00906 sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore); 00907 } 00908 } 00909 00910 /* Generate code to check constraints and generate index keys and 00911 ** do the insertion. 00912 */ 00913 #ifndef SQLITE_OMIT_VIRTUALTABLE 00914 if( IsVirtual(pTab) ){ 00915 sqlite3VtabMakeWritable(pParse, pTab); 00916 sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, 00917 (const char*)pTab->pVtab, P4_VTAB); 00918 }else 00919 #endif 00920 { 00921 sqlite3GenerateConstraintChecks( 00922 pParse, 00923 pTab, 00924 baseCur, 00925 regIns, 00926 aRegIdx, 00927 keyColumn>=0, 00928 0, 00929 onError, 00930 endOfLoop 00931 ); 00932 sqlite3CompleteInsertion( 00933 pParse, 00934 pTab, 00935 baseCur, 00936 regIns, 00937 aRegIdx, 00938 0, 00939 0, 00940 (triggers_exist & TRIGGER_AFTER)!=0 ? newIdx : -1, 00941 appendFlag 00942 ); 00943 } 00944 } 00945 00946 /* Update the count of rows that are inserted 00947 */ 00948 if( (db->flags & SQLITE_CountRows)!=0 ){ 00949 sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1); 00950 } 00951 00952 if( triggers_exist ){ 00953 /* Code AFTER triggers */ 00954 if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_AFTER, pTab, 00955 newIdx, -1, onError, endOfLoop, 0, 0) ){ 00956 goto insert_cleanup; 00957 } 00958 } 00959 00960 /* The bottom of the main insertion loop, if the data source 00961 ** is a SELECT statement. 00962 */ 00963 sqlite3VdbeResolveLabel(v, endOfLoop); 00964 if( useTempTable ){ 00965 sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); 00966 sqlite3VdbeJumpHere(v, addrInsTop); 00967 sqlite3VdbeAddOp1(v, OP_Close, srcTab); 00968 }else if( pSelect ){ 00969 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont); 00970 sqlite3VdbeJumpHere(v, addrInsTop); 00971 } 00972 00973 if( !IsVirtual(pTab) && !isView ){ 00974 /* Close all tables opened */ 00975 sqlite3VdbeAddOp1(v, OP_Close, baseCur); 00976 for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){ 00977 sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur); 00978 } 00979 } 00980 00981 /* Update the sqlite_sequence table by storing the content of the 00982 ** counter value in memory regAutoinc back into the sqlite_sequence 00983 ** table. 00984 */ 00985 autoIncEnd(pParse, iDb, pTab, regAutoinc); 00986 00987 /* 00988 ** Return the number of rows inserted. If this routine is 00989 ** generating code because of a call to sqlite3NestedParse(), do not 00990 ** invoke the callback function. 00991 */ 00992 if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){ 00993 sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1); 00994 sqlite3VdbeSetNumCols(v, 1); 00995 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC); 00996 } 00997 00998 insert_cleanup: 00999 sqlite3SrcListDelete(db, pTabList); 01000 sqlite3ExprListDelete(db, pList); 01001 sqlite3SelectDelete(db, pSelect); 01002 sqlite3IdListDelete(db, pColumn); 01003 sqlite3DbFree(db, aRegIdx); 01004 } 01005 01006 /* 01007 ** Generate code to do constraint checks prior to an INSERT or an UPDATE. 01008 ** 01009 ** The input is a range of consecutive registers as follows: 01010 ** 01011 ** 1. The rowid of the row to be updated before the update. This 01012 ** value is omitted unless we are doing an UPDATE that involves a 01013 ** change to the record number or writing to a virtual table. 01014 ** 01015 ** 2. The rowid of the row after the update. 01016 ** 01017 ** 3. The data in the first column of the entry after the update. 01018 ** 01019 ** i. Data from middle columns... 01020 ** 01021 ** N. The data in the last column of the entry after the update. 01022 ** 01023 ** The regRowid parameter is the index of the register containing (2). 01024 ** 01025 ** The old rowid shown as entry (1) above is omitted unless both isUpdate 01026 ** and rowidChng are 1. isUpdate is true for UPDATEs and false for 01027 ** INSERTs. RowidChng means that the new rowid is explicitly specified by 01028 ** the update or insert statement. If rowidChng is false, it means that 01029 ** the rowid is computed automatically in an insert or that the rowid value 01030 ** is not modified by the update. 01031 ** 01032 ** The code generated by this routine store new index entries into 01033 ** registers identified by aRegIdx[]. No index entry is created for 01034 ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is 01035 ** the same as the order of indices on the linked list of indices 01036 ** attached to the table. 01037 ** 01038 ** This routine also generates code to check constraints. NOT NULL, 01039 ** CHECK, and UNIQUE constraints are all checked. If a constraint fails, 01040 ** then the appropriate action is performed. There are five possible 01041 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE. 01042 ** 01043 ** Constraint type Action What Happens 01044 ** --------------- ---------- ---------------------------------------- 01045 ** any ROLLBACK The current transaction is rolled back and 01046 ** sqlite3_exec() returns immediately with a 01047 ** return code of SQLITE_CONSTRAINT. 01048 ** 01049 ** any ABORT Back out changes from the current command 01050 ** only (do not do a complete rollback) then 01051 ** cause sqlite3_exec() to return immediately 01052 ** with SQLITE_CONSTRAINT. 01053 ** 01054 ** any FAIL Sqlite_exec() returns immediately with a 01055 ** return code of SQLITE_CONSTRAINT. The 01056 ** transaction is not rolled back and any 01057 ** prior changes are retained. 01058 ** 01059 ** any IGNORE The record number and data is popped from 01060 ** the stack and there is an immediate jump 01061 ** to label ignoreDest. 01062 ** 01063 ** NOT NULL REPLACE The NULL value is replace by the default 01064 ** value for that column. If the default value 01065 ** is NULL, the action is the same as ABORT. 01066 ** 01067 ** UNIQUE REPLACE The other row that conflicts with the row 01068 ** being inserted is removed. 01069 ** 01070 ** CHECK REPLACE Illegal. The results in an exception. 01071 ** 01072 ** Which action to take is determined by the overrideError parameter. 01073 ** Or if overrideError==OE_Default, then the pParse->onError parameter 01074 ** is used. Or if pParse->onError==OE_Default then the onError value 01075 ** for the constraint is used. 01076 ** 01077 ** The calling routine must open a read/write cursor for pTab with 01078 ** cursor number "baseCur". All indices of pTab must also have open 01079 ** read/write cursors with cursor number baseCur+i for the i-th cursor. 01080 ** Except, if there is no possibility of a REPLACE action then 01081 ** cursors do not need to be open for indices where aRegIdx[i]==0. 01082 */ 01083 void sqlite3GenerateConstraintChecks( 01084 Parse *pParse, /* The parser context */ 01085 Table *pTab, /* the table into which we are inserting */ 01086 int baseCur, /* Index of a read/write cursor pointing at pTab */ 01087 int regRowid, /* Index of the range of input registers */ 01088 int *aRegIdx, /* Register used by each index. 0 for unused indices */ 01089 int rowidChng, /* True if the rowid might collide with existing entry */ 01090 int isUpdate, /* True for UPDATE, False for INSERT */ 01091 int overrideError, /* Override onError to this if not OE_Default */ 01092 int ignoreDest /* Jump to this label on an OE_Ignore resolution */ 01093 ){ 01094 int i; 01095 Vdbe *v; 01096 int nCol; 01097 int onError; 01098 int j1, j2, j3; /* Addresses of jump instructions */ 01099 int regData; /* Register containing first data column */ 01100 int iCur; 01101 Index *pIdx; 01102 int seenReplace = 0; 01103 int hasTwoRowids = (isUpdate && rowidChng); 01104 01105 v = sqlite3GetVdbe(pParse); 01106 assert( v!=0 ); 01107 assert( pTab->pSelect==0 ); /* This table is not a VIEW */ 01108 nCol = pTab->nCol; 01109 regData = regRowid + 1; 01110 01111 01112 /* Test all NOT NULL constraints. 01113 */ 01114 for(i=0; i<nCol; i++){ 01115 if( i==pTab->iPKey ){ 01116 continue; 01117 } 01118 onError = pTab->aCol[i].notNull; 01119 if( onError==OE_None ) continue; 01120 if( overrideError!=OE_Default ){ 01121 onError = overrideError; 01122 }else if( onError==OE_Default ){ 01123 onError = OE_Abort; 01124 } 01125 if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){ 01126 onError = OE_Abort; 01127 } 01128 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i); 01129 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail 01130 || onError==OE_Ignore || onError==OE_Replace ); 01131 switch( onError ){ 01132 case OE_Rollback: 01133 case OE_Abort: 01134 case OE_Fail: { 01135 char *zMsg; 01136 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError); 01137 zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL", 01138 pTab->zName, pTab->aCol[i].zName); 01139 sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC); 01140 break; 01141 } 01142 case OE_Ignore: { 01143 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest); 01144 break; 01145 } 01146 case OE_Replace: { 01147 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i); 01148 break; 01149 } 01150 } 01151 sqlite3VdbeJumpHere(v, j1); 01152 } 01153 01154 /* Test all CHECK constraints 01155 */ 01156 #ifndef SQLITE_OMIT_CHECK 01157 if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){ 01158 int allOk = sqlite3VdbeMakeLabel(v); 01159 pParse->ckBase = regData; 01160 sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL); 01161 onError = overrideError!=OE_Default ? overrideError : OE_Abort; 01162 if( onError==OE_Ignore ){ 01163 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest); 01164 }else{ 01165 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError); 01166 } 01167 sqlite3VdbeResolveLabel(v, allOk); 01168 } 01169 #endif /* !defined(SQLITE_OMIT_CHECK) */ 01170 01171 /* If we have an INTEGER PRIMARY KEY, make sure the primary key 01172 ** of the new record does not previously exist. Except, if this 01173 ** is an UPDATE and the primary key is not changing, that is OK. 01174 */ 01175 if( rowidChng ){ 01176 onError = pTab->keyConf; 01177 if( overrideError!=OE_Default ){ 01178 onError = overrideError; 01179 }else if( onError==OE_Default ){ 01180 onError = OE_Abort; 01181 } 01182 01183 if( onError!=OE_Replace || pTab->pIndex ){ 01184 if( isUpdate ){ 01185 j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, regRowid-1); 01186 } 01187 j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid); 01188 switch( onError ){ 01189 default: { 01190 onError = OE_Abort; 01191 /* Fall thru into the next case */ 01192 } 01193 case OE_Rollback: 01194 case OE_Abort: 01195 case OE_Fail: { 01196 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, 01197 "PRIMARY KEY must be unique", P4_STATIC); 01198 break; 01199 } 01200 case OE_Replace: { 01201 sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0); 01202 seenReplace = 1; 01203 break; 01204 } 01205 case OE_Ignore: { 01206 assert( seenReplace==0 ); 01207 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest); 01208 break; 01209 } 01210 } 01211 sqlite3VdbeJumpHere(v, j3); 01212 if( isUpdate ){ 01213 sqlite3VdbeJumpHere(v, j2); 01214 } 01215 } 01216 } 01217 01218 /* Test all UNIQUE constraints by creating entries for each UNIQUE 01219 ** index and making sure that duplicate entries do not already exist. 01220 ** Add the new records to the indices as we go. 01221 */ 01222 for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){ 01223 int regIdx; 01224 int regR; 01225 01226 if( aRegIdx[iCur]==0 ) continue; /* Skip unused indices */ 01227 01228 /* Create a key for accessing the index entry */ 01229 regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1); 01230 for(i=0; i<pIdx->nColumn; i++){ 01231 int idx = pIdx->aiColumn[i]; 01232 if( idx==pTab->iPKey ){ 01233 sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i); 01234 }else{ 01235 sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i); 01236 } 01237 } 01238 sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i); 01239 sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]); 01240 sqlite3IndexAffinityStr(v, pIdx); 01241 sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1); 01242 sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1); 01243 01244 /* Find out what action to take in case there is an indexing conflict */ 01245 onError = pIdx->onError; 01246 if( onError==OE_None ) continue; /* pIdx is not a UNIQUE index */ 01247 if( overrideError!=OE_Default ){ 01248 onError = overrideError; 01249 }else if( onError==OE_Default ){ 01250 onError = OE_Abort; 01251 } 01252 if( seenReplace ){ 01253 if( onError==OE_Ignore ) onError = OE_Replace; 01254 else if( onError==OE_Fail ) onError = OE_Abort; 01255 } 01256 01257 01258 /* Check to see if the new index entry will be unique */ 01259 j2 = sqlite3VdbeAddOp3(v, OP_IsNull, regIdx, 0, pIdx->nColumn); 01260 regR = sqlite3GetTempReg(pParse); 01261 sqlite3VdbeAddOp2(v, OP_SCopy, regRowid-hasTwoRowids, regR); 01262 j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0, 01263 regR, SQLITE_INT_TO_PTR(aRegIdx[iCur]), 01264 P4_INT32); 01265 01266 /* Generate code that executes if the new index entry is not unique */ 01267 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail 01268 || onError==OE_Ignore || onError==OE_Replace ); 01269 switch( onError ){ 01270 case OE_Rollback: 01271 case OE_Abort: 01272 case OE_Fail: { 01273 int j, n1, n2; 01274 char zErrMsg[200]; 01275 sqlite3_snprintf(sizeof(zErrMsg), zErrMsg, 01276 pIdx->nColumn>1 ? "columns " : "column "); 01277 n1 = strlen(zErrMsg); 01278 for(j=0; j<pIdx->nColumn && n1<sizeof(zErrMsg)-30; j++){ 01279 char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName; 01280 n2 = strlen(zCol); 01281 if( j>0 ){ 01282 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], ", "); 01283 n1 += 2; 01284 } 01285 if( n1+n2>sizeof(zErrMsg)-30 ){ 01286 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "..."); 01287 n1 += 3; 01288 break; 01289 }else{ 01290 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "%s", zCol); 01291 n1 += n2; 01292 } 01293 } 01294 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], 01295 pIdx->nColumn>1 ? " are not unique" : " is not unique"); 01296 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, zErrMsg,0); 01297 break; 01298 } 01299 case OE_Ignore: { 01300 assert( seenReplace==0 ); 01301 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest); 01302 break; 01303 } 01304 case OE_Replace: { 01305 sqlite3GenerateRowDelete(pParse, pTab, baseCur, regR, 0); 01306 seenReplace = 1; 01307 break; 01308 } 01309 } 01310 sqlite3VdbeJumpHere(v, j2); 01311 sqlite3VdbeJumpHere(v, j3); 01312 sqlite3ReleaseTempReg(pParse, regR); 01313 } 01314 } 01315 01316 /* 01317 ** This routine generates code to finish the INSERT or UPDATE operation 01318 ** that was started by a prior call to sqlite3GenerateConstraintChecks. 01319 ** A consecutive range of registers starting at regRowid contains the 01320 ** rowid and the content to be inserted. 01321 ** 01322 ** The arguments to this routine should be the same as the first six 01323 ** arguments to sqlite3GenerateConstraintChecks. 01324 */ 01325 void sqlite3CompleteInsertion( 01326 Parse *pParse, /* The parser context */ 01327 Table *pTab, /* the table into which we are inserting */ 01328 int baseCur, /* Index of a read/write cursor pointing at pTab */ 01329 int regRowid, /* Range of content */ 01330 int *aRegIdx, /* Register used by each index. 0 for unused indices */ 01331 int rowidChng, /* True if the record number will change */ 01332 int isUpdate, /* True for UPDATE, False for INSERT */ 01333 int newIdx, /* Index of NEW table for triggers. -1 if none */ 01334 int appendBias /* True if this is likely to be an append */ 01335 ){ 01336 int i; 01337 Vdbe *v; 01338 int nIdx; 01339 Index *pIdx; 01340 int pik_flags; 01341 int regData; 01342 int regRec; 01343 01344 v = sqlite3GetVdbe(pParse); 01345 assert( v!=0 ); 01346 assert( pTab->pSelect==0 ); /* This table is not a VIEW */ 01347 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){} 01348 for(i=nIdx-1; i>=0; i--){ 01349 if( aRegIdx[i]==0 ) continue; 01350 sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]); 01351 } 01352 regData = regRowid + 1; 01353 regRec = sqlite3GetTempReg(pParse); 01354 sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec); 01355 sqlite3TableAffinityStr(v, pTab); 01356 sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol); 01357 #ifndef SQLITE_OMIT_TRIGGER 01358 if( newIdx>=0 ){ 01359 sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regRowid); 01360 } 01361 #endif 01362 if( pParse->nested ){ 01363 pik_flags = 0; 01364 }else{ 01365 pik_flags = OPFLAG_NCHANGE; 01366 pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID); 01367 } 01368 if( appendBias ){ 01369 pik_flags |= OPFLAG_APPEND; 01370 } 01371 sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid); 01372 if( !pParse->nested ){ 01373 sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC); 01374 } 01375 sqlite3VdbeChangeP5(v, pik_flags); 01376 } 01377 01378 /* 01379 ** Generate code that will open cursors for a table and for all 01380 ** indices of that table. The "baseCur" parameter is the cursor number used 01381 ** for the table. Indices are opened on subsequent cursors. 01382 ** 01383 ** Return the number of indices on the table. 01384 */ 01385 int sqlite3OpenTableAndIndices( 01386 Parse *pParse, /* Parsing context */ 01387 Table *pTab, /* Table to be opened */ 01388 int baseCur, /* Cursor number assigned to the table */ 01389 int op /* OP_OpenRead or OP_OpenWrite */ 01390 ){ 01391 int i; 01392 int iDb; 01393 Index *pIdx; 01394 Vdbe *v; 01395 01396 if( IsVirtual(pTab) ) return 0; 01397 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 01398 v = sqlite3GetVdbe(pParse); 01399 assert( v!=0 ); 01400 sqlite3OpenTable(pParse, baseCur, iDb, pTab, op); 01401 for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ 01402 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx); 01403 assert( pIdx->pSchema==pTab->pSchema ); 01404 sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb, 01405 (char*)pKey, P4_KEYINFO_HANDOFF); 01406 VdbeComment((v, "%s", pIdx->zName)); 01407 } 01408 if( pParse->nTab<=baseCur+i ){ 01409 pParse->nTab = baseCur+i; 01410 } 01411 return i-1; 01412 } 01413 01414 01415 #ifdef SQLITE_TEST 01416 /* 01417 ** The following global variable is incremented whenever the 01418 ** transfer optimization is used. This is used for testing 01419 ** purposes only - to make sure the transfer optimization really 01420 ** is happening when it is suppose to. 01421 */ 01422 int sqlite3_xferopt_count; 01423 #endif /* SQLITE_TEST */ 01424 01425 01426 #ifndef SQLITE_OMIT_XFER_OPT 01427 /* 01428 ** Check to collation names to see if they are compatible. 01429 */ 01430 static int xferCompatibleCollation(const char *z1, const char *z2){ 01431 if( z1==0 ){ 01432 return z2==0; 01433 } 01434 if( z2==0 ){ 01435 return 0; 01436 } 01437 return sqlite3StrICmp(z1, z2)==0; 01438 } 01439 01440 01441 /* 01442 ** Check to see if index pSrc is compatible as a source of data 01443 ** for index pDest in an insert transfer optimization. The rules 01444 ** for a compatible index: 01445 ** 01446 ** * The index is over the same set of columns 01447 ** * The same DESC and ASC markings occurs on all columns 01448 ** * The same onError processing (OE_Abort, OE_Ignore, etc) 01449 ** * The same collating sequence on each column 01450 */ 01451 static int xferCompatibleIndex(Index *pDest, Index *pSrc){ 01452 int i; 01453 assert( pDest && pSrc ); 01454 assert( pDest->pTable!=pSrc->pTable ); 01455 if( pDest->nColumn!=pSrc->nColumn ){ 01456 return 0; /* Different number of columns */ 01457 } 01458 if( pDest->onError!=pSrc->onError ){ 01459 return 0; /* Different conflict resolution strategies */ 01460 } 01461 for(i=0; i<pSrc->nColumn; i++){ 01462 if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){ 01463 return 0; /* Different columns indexed */ 01464 } 01465 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){ 01466 return 0; /* Different sort orders */ 01467 } 01468 if( pSrc->azColl[i]!=pDest->azColl[i] ){ 01469 return 0; /* Different collating sequences */ 01470 } 01471 } 01472 01473 /* If no test above fails then the indices must be compatible */ 01474 return 1; 01475 } 01476 01477 /* 01478 ** Attempt the transfer optimization on INSERTs of the form 01479 ** 01480 ** INSERT INTO tab1 SELECT * FROM tab2; 01481 ** 01482 ** This optimization is only attempted if 01483 ** 01484 ** (1) tab1 and tab2 have identical schemas including all the 01485 ** same indices and constraints 01486 ** 01487 ** (2) tab1 and tab2 are different tables 01488 ** 01489 ** (3) There must be no triggers on tab1 01490 ** 01491 ** (4) The result set of the SELECT statement is "*" 01492 ** 01493 ** (5) The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY, 01494 ** or LIMIT clause. 01495 ** 01496 ** (6) The SELECT statement is a simple (not a compound) select that 01497 ** contains only tab2 in its FROM clause 01498 ** 01499 ** This method for implementing the INSERT transfers raw records from 01500 ** tab2 over to tab1. The columns are not decoded. Raw records from 01501 ** the indices of tab2 are transfered to tab1 as well. In so doing, 01502 ** the resulting tab1 has much less fragmentation. 01503 ** 01504 ** This routine returns TRUE if the optimization is attempted. If any 01505 ** of the conditions above fail so that the optimization should not 01506 ** be attempted, then this routine returns FALSE. 01507 */ 01508 static int xferOptimization( 01509 Parse *pParse, /* Parser context */ 01510 Table *pDest, /* The table we are inserting into */ 01511 Select *pSelect, /* A SELECT statement to use as the data source */ 01512 int onError, /* How to handle constraint errors */ 01513 int iDbDest /* The database of pDest */ 01514 ){ 01515 ExprList *pEList; /* The result set of the SELECT */ 01516 Table *pSrc; /* The table in the FROM clause of SELECT */ 01517 Index *pSrcIdx, *pDestIdx; /* Source and destination indices */ 01518 struct SrcList_item *pItem; /* An element of pSelect->pSrc */ 01519 int i; /* Loop counter */ 01520 int iDbSrc; /* The database of pSrc */ 01521 int iSrc, iDest; /* Cursors from source and destination */ 01522 int addr1, addr2; /* Loop addresses */ 01523 int emptyDestTest; /* Address of test for empty pDest */ 01524 int emptySrcTest; /* Address of test for empty pSrc */ 01525 Vdbe *v; /* The VDBE we are building */ 01526 KeyInfo *pKey; /* Key information for an index */ 01527 int regAutoinc; /* Memory register used by AUTOINC */ 01528 int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */ 01529 int regData, regRowid; /* Registers holding data and rowid */ 01530 01531 if( pSelect==0 ){ 01532 return 0; /* Must be of the form INSERT INTO ... SELECT ... */ 01533 } 01534 if( pDest->pTrigger ){ 01535 return 0; /* tab1 must not have triggers */ 01536 } 01537 #ifndef SQLITE_OMIT_VIRTUALTABLE 01538 if( pDest->tabFlags & TF_Virtual ){ 01539 return 0; /* tab1 must not be a virtual table */ 01540 } 01541 #endif 01542 if( onError==OE_Default ){ 01543 onError = OE_Abort; 01544 } 01545 if( onError!=OE_Abort && onError!=OE_Rollback ){ 01546 return 0; /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */ 01547 } 01548 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */ 01549 if( pSelect->pSrc->nSrc!=1 ){ 01550 return 0; /* FROM clause must have exactly one term */ 01551 } 01552 if( pSelect->pSrc->a[0].pSelect ){ 01553 return 0; /* FROM clause cannot contain a subquery */ 01554 } 01555 if( pSelect->pWhere ){ 01556 return 0; /* SELECT may not have a WHERE clause */ 01557 } 01558 if( pSelect->pOrderBy ){ 01559 return 0; /* SELECT may not have an ORDER BY clause */ 01560 } 01561 /* Do not need to test for a HAVING clause. If HAVING is present but 01562 ** there is no ORDER BY, we will get an error. */ 01563 if( pSelect->pGroupBy ){ 01564 return 0; /* SELECT may not have a GROUP BY clause */ 01565 } 01566 if( pSelect->pLimit ){ 01567 return 0; /* SELECT may not have a LIMIT clause */ 01568 } 01569 assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */ 01570 if( pSelect->pPrior ){ 01571 return 0; /* SELECT may not be a compound query */ 01572 } 01573 if( pSelect->selFlags & SF_Distinct ){ 01574 return 0; /* SELECT may not be DISTINCT */ 01575 } 01576 pEList = pSelect->pEList; 01577 assert( pEList!=0 ); 01578 if( pEList->nExpr!=1 ){ 01579 return 0; /* The result set must have exactly one column */ 01580 } 01581 assert( pEList->a[0].pExpr ); 01582 if( pEList->a[0].pExpr->op!=TK_ALL ){ 01583 return 0; /* The result set must be the special operator "*" */ 01584 } 01585 01586 /* At this point we have established that the statement is of the 01587 ** correct syntactic form to participate in this optimization. Now 01588 ** we have to check the semantics. 01589 */ 01590 pItem = pSelect->pSrc->a; 01591 pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase); 01592 if( pSrc==0 ){ 01593 return 0; /* FROM clause does not contain a real table */ 01594 } 01595 if( pSrc==pDest ){ 01596 return 0; /* tab1 and tab2 may not be the same table */ 01597 } 01598 #ifndef SQLITE_OMIT_VIRTUALTABLE 01599 if( pSrc->tabFlags & TF_Virtual ){ 01600 return 0; /* tab2 must not be a virtual table */ 01601 } 01602 #endif 01603 if( pSrc->pSelect ){ 01604 return 0; /* tab2 may not be a view */ 01605 } 01606 if( pDest->nCol!=pSrc->nCol ){ 01607 return 0; /* Number of columns must be the same in tab1 and tab2 */ 01608 } 01609 if( pDest->iPKey!=pSrc->iPKey ){ 01610 return 0; /* Both tables must have the same INTEGER PRIMARY KEY */ 01611 } 01612 for(i=0; i<pDest->nCol; i++){ 01613 if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){ 01614 return 0; /* Affinity must be the same on all columns */ 01615 } 01616 if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){ 01617 return 0; /* Collating sequence must be the same on all columns */ 01618 } 01619 if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){ 01620 return 0; /* tab2 must be NOT NULL if tab1 is */ 01621 } 01622 } 01623 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ 01624 if( pDestIdx->onError!=OE_None ){ 01625 destHasUniqueIdx = 1; 01626 } 01627 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){ 01628 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; 01629 } 01630 if( pSrcIdx==0 ){ 01631 return 0; /* pDestIdx has no corresponding index in pSrc */ 01632 } 01633 } 01634 #ifndef SQLITE_OMIT_CHECK 01635 if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){ 01636 return 0; /* Tables have different CHECK constraints. Ticket #2252 */ 01637 } 01638 #endif 01639 01640 /* If we get this far, it means either: 01641 ** 01642 ** * We can always do the transfer if the table contains an 01643 ** an integer primary key 01644 ** 01645 ** * We can conditionally do the transfer if the destination 01646 ** table is empty. 01647 */ 01648 #ifdef SQLITE_TEST 01649 sqlite3_xferopt_count++; 01650 #endif 01651 iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema); 01652 v = sqlite3GetVdbe(pParse); 01653 sqlite3CodeVerifySchema(pParse, iDbSrc); 01654 iSrc = pParse->nTab++; 01655 iDest = pParse->nTab++; 01656 regAutoinc = autoIncBegin(pParse, iDbDest, pDest); 01657 sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite); 01658 if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){ 01659 /* If tables do not have an INTEGER PRIMARY KEY and there 01660 ** are indices to be copied and the destination is not empty, 01661 ** we have to disallow the transfer optimization because the 01662 ** the rowids might change which will mess up indexing. 01663 ** 01664 ** Or if the destination has a UNIQUE index and is not empty, 01665 ** we also disallow the transfer optimization because we cannot 01666 ** insure that all entries in the union of DEST and SRC will be 01667 ** unique. 01668 */ 01669 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); 01670 emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0); 01671 sqlite3VdbeJumpHere(v, addr1); 01672 }else{ 01673 emptyDestTest = 0; 01674 } 01675 sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead); 01676 emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); 01677 regData = sqlite3GetTempReg(pParse); 01678 regRowid = sqlite3GetTempReg(pParse); 01679 if( pDest->iPKey>=0 ){ 01680 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); 01681 addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid); 01682 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, 01683 "PRIMARY KEY must be unique", P4_STATIC); 01684 sqlite3VdbeJumpHere(v, addr2); 01685 autoIncStep(pParse, regAutoinc, regRowid); 01686 }else if( pDest->pIndex==0 ){ 01687 addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid); 01688 }else{ 01689 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); 01690 assert( (pDest->tabFlags & TF_Autoincrement)==0 ); 01691 } 01692 sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData); 01693 sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid); 01694 sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND); 01695 sqlite3VdbeChangeP4(v, -1, pDest->zName, 0); 01696 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); 01697 autoIncEnd(pParse, iDbDest, pDest, regAutoinc); 01698 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ 01699 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){ 01700 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; 01701 } 01702 assert( pSrcIdx ); 01703 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); 01704 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); 01705 pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx); 01706 sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc, 01707 (char*)pKey, P4_KEYINFO_HANDOFF); 01708 VdbeComment((v, "%s", pSrcIdx->zName)); 01709 pKey = sqlite3IndexKeyinfo(pParse, pDestIdx); 01710 sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest, 01711 (char*)pKey, P4_KEYINFO_HANDOFF); 01712 VdbeComment((v, "%s", pDestIdx->zName)); 01713 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); 01714 sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData); 01715 sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1); 01716 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); 01717 sqlite3VdbeJumpHere(v, addr1); 01718 } 01719 sqlite3VdbeJumpHere(v, emptySrcTest); 01720 sqlite3ReleaseTempReg(pParse, regRowid); 01721 sqlite3ReleaseTempReg(pParse, regData); 01722 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); 01723 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); 01724 if( emptyDestTest ){ 01725 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0); 01726 sqlite3VdbeJumpHere(v, emptyDestTest); 01727 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); 01728 return 0; 01729 }else{ 01730 return 1; 01731 } 01732 } 01733 #endif /* SQLITE_OMIT_XFER_OPT */ 01734 01735 /* Make sure "isView" gets undefined in case this file becomes part of 01736 ** the amalgamation - so that subsequent files do not see isView as a 01737 ** macro. */ 01738 #undef isView
ContextLogger2—ContextLogger2 Logger Daemon Internals—Generated on Mon May 2 13:49:54 2011 by Doxygen 1.6.1