Back to index

lightning-sunbird  0.9+nobinonly
insert.c
Go to the documentation of this file.
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.164 2006/03/15 16:26:10 drh Exp $
00016 */
00017 #include "sqliteInt.h"
00018 
00019 /*
00020 ** Set P3 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 void sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
00033   if( !pIdx->zColAff ){
00034     /* The first time a column affinity string for a particular index is
00035     ** required, it is allocated and populated here. It is then stored as
00036     ** a member of the Index structure for subsequent use.
00037     **
00038     ** The column affinity string will eventually be deleted by
00039     ** sqliteDeleteIndex() when the Index structure itself is cleaned
00040     ** up.
00041     */
00042     int n;
00043     Table *pTab = pIdx->pTable;
00044     pIdx->zColAff = (char *)sqliteMalloc(pIdx->nColumn+1);
00045     if( !pIdx->zColAff ){
00046       return;
00047     }
00048     for(n=0; n<pIdx->nColumn; n++){
00049       pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
00050     }
00051     pIdx->zColAff[pIdx->nColumn] = '\0';
00052   }
00053  
00054   sqlite3VdbeChangeP3(v, -1, pIdx->zColAff, 0);
00055 }
00056 
00057 /*
00058 ** Set P3 of the most recently inserted opcode to a column affinity
00059 ** string for table pTab. A column affinity string has one character
00060 ** for each column indexed by the index, according to the affinity of the
00061 ** column:
00062 **
00063 **  Character      Column affinity
00064 **  ------------------------------
00065 **  'a'            TEXT
00066 **  'b'            NONE
00067 **  'c'            NUMERIC
00068 **  'd'            INTEGER
00069 **  'e'            REAL
00070 */
00071 void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
00072   /* The first time a column affinity string for a particular table
00073   ** is required, it is allocated and populated here. It is then 
00074   ** stored as a member of the Table structure for subsequent use.
00075   **
00076   ** The column affinity string will eventually be deleted by
00077   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
00078   */
00079   if( !pTab->zColAff ){
00080     char *zColAff;
00081     int i;
00082 
00083     zColAff = (char *)sqliteMalloc(pTab->nCol+1);
00084     if( !zColAff ){
00085       return;
00086     }
00087 
00088     for(i=0; i<pTab->nCol; i++){
00089       zColAff[i] = pTab->aCol[i].affinity;
00090     }
00091     zColAff[pTab->nCol] = '\0';
00092 
00093     pTab->zColAff = zColAff;
00094   }
00095 
00096   sqlite3VdbeChangeP3(v, -1, pTab->zColAff, 0);
00097 }
00098 
00099 /*
00100 ** Return non-zero if SELECT statement p opens the table with rootpage
00101 ** iTab in database iDb.  This is used to see if a statement of the form 
00102 ** "INSERT INTO <iDb, iTab> SELECT ..." can run without using temporary
00103 ** table for the results of the SELECT. 
00104 **
00105 ** No checking is done for sub-selects that are part of expressions.
00106 */
00107 static int selectReadsTable(Select *p, Schema *pSchema, int iTab){
00108   int i;
00109   struct SrcList_item *pItem;
00110   if( p->pSrc==0 ) return 0;
00111   for(i=0, pItem=p->pSrc->a; i<p->pSrc->nSrc; i++, pItem++){
00112     if( pItem->pSelect ){
00113       if( selectReadsTable(pItem->pSelect, pSchema, iTab) ) return 1;
00114     }else{
00115       if( pItem->pTab->pSchema==pSchema && pItem->pTab->tnum==iTab ) return 1;
00116     }
00117   }
00118   return 0;
00119 }
00120 
00121 /*
00122 ** This routine is call to handle SQL of the following forms:
00123 **
00124 **    insert into TABLE (IDLIST) values(EXPRLIST)
00125 **    insert into TABLE (IDLIST) select
00126 **
00127 ** The IDLIST following the table name is always optional.  If omitted,
00128 ** then a list of all columns for the table is substituted.  The IDLIST
00129 ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
00130 **
00131 ** The pList parameter holds EXPRLIST in the first form of the INSERT
00132 ** statement above, and pSelect is NULL.  For the second form, pList is
00133 ** NULL and pSelect is a pointer to the select statement used to generate
00134 ** data for the insert.
00135 **
00136 ** The code generated follows one of three templates.  For a simple
00137 ** select with data coming from a VALUES clause, the code executes
00138 ** once straight down through.  The template looks like this:
00139 **
00140 **         open write cursor to <table> and its indices
00141 **         puts VALUES clause expressions onto the stack
00142 **         write the resulting record into <table>
00143 **         cleanup
00144 **
00145 ** If the statement is of the form
00146 **
00147 **   INSERT INTO <table> SELECT ...
00148 **
00149 ** And the SELECT clause does not read from <table> at any time, then
00150 ** the generated code follows this template:
00151 **
00152 **         goto B
00153 **      A: setup for the SELECT
00154 **         loop over the tables in the SELECT
00155 **           gosub C
00156 **         end loop
00157 **         cleanup after the SELECT
00158 **         goto D
00159 **      B: open write cursor to <table> and its indices
00160 **         goto A
00161 **      C: insert the select result into <table>
00162 **         return
00163 **      D: cleanup
00164 **
00165 ** The third template is used if the insert statement takes its
00166 ** values from a SELECT but the data is being inserted into a table
00167 ** that is also read as part of the SELECT.  In the third form,
00168 ** we have to use a intermediate table to store the results of
00169 ** the select.  The template is like this:
00170 **
00171 **         goto B
00172 **      A: setup for the SELECT
00173 **         loop over the tables in the SELECT
00174 **           gosub C
00175 **         end loop
00176 **         cleanup after the SELECT
00177 **         goto D
00178 **      C: insert the select result into the intermediate table
00179 **         return
00180 **      B: open a cursor to an intermediate table
00181 **         goto A
00182 **      D: open write cursor to <table> and its indices
00183 **         loop over the intermediate table
00184 **           transfer values form intermediate table into <table>
00185 **         end the loop
00186 **         cleanup
00187 */
00188 void sqlite3Insert(
00189   Parse *pParse,        /* Parser context */
00190   SrcList *pTabList,    /* Name of table into which we are inserting */
00191   ExprList *pList,      /* List of values to be inserted */
00192   Select *pSelect,      /* A SELECT statement to use as the data source */
00193   IdList *pColumn,      /* Column names corresponding to IDLIST. */
00194   int onError           /* How to handle constraint errors */
00195 ){
00196   Table *pTab;          /* The table to insert into */
00197   char *zTab;           /* Name of the table into which we are inserting */
00198   const char *zDb;      /* Name of the database holding this table */
00199   int i, j, idx;        /* Loop counters */
00200   Vdbe *v;              /* Generate code into this virtual machine */
00201   Index *pIdx;          /* For looping over indices of the table */
00202   int nColumn;          /* Number of columns in the data */
00203   int base = 0;         /* VDBE Cursor number for pTab */
00204   int iCont=0,iBreak=0; /* Beginning and end of the loop over srcTab */
00205   sqlite3 *db;          /* The main database structure */
00206   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
00207   int endOfLoop;        /* Label for the end of the insertion loop */
00208   int useTempTable = 0; /* Store SELECT results in intermediate table */
00209   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
00210   int iSelectLoop = 0;  /* Address of code that implements the SELECT */
00211   int iCleanup = 0;     /* Address of the cleanup code */
00212   int iInsertBlock = 0; /* Address of the subroutine used to insert data */
00213   int iCntMem = 0;      /* Memory cell used for the row counter */
00214   int newIdx = -1;      /* Cursor for the NEW table */
00215   Db *pDb;              /* The database containing table being inserted into */
00216   int counterMem = 0;   /* Memory cell holding AUTOINCREMENT counter */
00217   int iDb;
00218 
00219 #ifndef SQLITE_OMIT_TRIGGER
00220   int isView;                 /* True if attempting to insert into a view */
00221   int triggers_exist = 0;     /* True if there are FOR EACH ROW triggers */
00222 #endif
00223 
00224 #ifndef SQLITE_OMIT_AUTOINCREMENT
00225   int counterRowid = 0;  /* Memory cell holding rowid of autoinc counter */
00226 #endif
00227 
00228   if( pParse->nErr || sqlite3MallocFailed() ){
00229     goto insert_cleanup;
00230   }
00231   db = pParse->db;
00232 
00233   /* Locate the table into which we will be inserting new information.
00234   */
00235   assert( pTabList->nSrc==1 );
00236   zTab = pTabList->a[0].zName;
00237   if( zTab==0 ) goto insert_cleanup;
00238   pTab = sqlite3SrcListLookup(pParse, pTabList);
00239   if( pTab==0 ){
00240     goto insert_cleanup;
00241   }
00242   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
00243   assert( iDb<db->nDb );
00244   pDb = &db->aDb[iDb];
00245   zDb = pDb->zName;
00246   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
00247     goto insert_cleanup;
00248   }
00249 
00250   /* Figure out if we have any triggers and if the table being
00251   ** inserted into is a view
00252   */
00253 #ifndef SQLITE_OMIT_TRIGGER
00254   triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0);
00255   isView = pTab->pSelect!=0;
00256 #else
00257 # define triggers_exist 0
00258 # define isView 0
00259 #endif
00260 #ifdef SQLITE_OMIT_VIEW
00261 # undef isView
00262 # define isView 0
00263 #endif
00264 
00265   /* Ensure that:
00266   *  (a) the table is not read-only, 
00267   *  (b) that if it is a view then ON INSERT triggers exist
00268   */
00269   if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
00270     goto insert_cleanup;
00271   }
00272   assert( pTab!=0 );
00273 
00274   /* If pTab is really a view, make sure it has been initialized.
00275   */
00276   if( isView && sqlite3ViewGetColumnNames(pParse, pTab) ){
00277     goto insert_cleanup;
00278   }
00279 
00280   /* Allocate a VDBE
00281   */
00282   v = sqlite3GetVdbe(pParse);
00283   if( v==0 ) goto insert_cleanup;
00284   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
00285   sqlite3BeginWriteOperation(pParse, pSelect || triggers_exist, iDb);
00286 
00287   /* if there are row triggers, allocate a temp table for new.* references. */
00288   if( triggers_exist ){
00289     newIdx = pParse->nTab++;
00290   }
00291 
00292 #ifndef SQLITE_OMIT_AUTOINCREMENT
00293   /* If this is an AUTOINCREMENT table, look up the sequence number in the
00294   ** sqlite_sequence table and store it in memory cell counterMem.  Also
00295   ** remember the rowid of the sqlite_sequence table entry in memory cell
00296   ** counterRowid.
00297   */
00298   if( pTab->autoInc ){
00299     int iCur = pParse->nTab;
00300     int addr = sqlite3VdbeCurrentAddr(v);
00301     counterRowid = pParse->nMem++;
00302     counterMem = pParse->nMem++;
00303     sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
00304     sqlite3VdbeAddOp(v, OP_Rewind, iCur, addr+13);
00305     sqlite3VdbeAddOp(v, OP_Column, iCur, 0);
00306     sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0);
00307     sqlite3VdbeAddOp(v, OP_Ne, 0x100, addr+12);
00308     sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
00309     sqlite3VdbeAddOp(v, OP_MemStore, counterRowid, 1);
00310     sqlite3VdbeAddOp(v, OP_Column, iCur, 1);
00311     sqlite3VdbeAddOp(v, OP_MemStore, counterMem, 1);
00312     sqlite3VdbeAddOp(v, OP_Goto, 0, addr+13);
00313     sqlite3VdbeAddOp(v, OP_Next, iCur, addr+4);
00314     sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
00315   }
00316 #endif /* SQLITE_OMIT_AUTOINCREMENT */
00317 
00318   /* Figure out how many columns of data are supplied.  If the data
00319   ** is coming from a SELECT statement, then this step also generates
00320   ** all the code to implement the SELECT statement and invoke a subroutine
00321   ** to process each row of the result. (Template 2.) If the SELECT
00322   ** statement uses the the table that is being inserted into, then the
00323   ** subroutine is also coded here.  That subroutine stores the SELECT
00324   ** results in a temporary table. (Template 3.)
00325   */
00326   if( pSelect ){
00327     /* Data is coming from a SELECT.  Generate code to implement that SELECT
00328     */
00329     int rc, iInitCode;
00330     iInitCode = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
00331     iSelectLoop = sqlite3VdbeCurrentAddr(v);
00332     iInsertBlock = sqlite3VdbeMakeLabel(v);
00333 
00334     /* Resolve the expressions in the SELECT statement and execute it. */
00335     rc = sqlite3Select(pParse, pSelect, SRT_Subroutine, iInsertBlock,0,0,0,0);
00336     if( rc || pParse->nErr || sqlite3MallocFailed() ){
00337       goto insert_cleanup;
00338     }
00339 
00340     iCleanup = sqlite3VdbeMakeLabel(v);
00341     sqlite3VdbeAddOp(v, OP_Goto, 0, iCleanup);
00342     assert( pSelect->pEList );
00343     nColumn = pSelect->pEList->nExpr;
00344 
00345     /* Set useTempTable to TRUE if the result of the SELECT statement
00346     ** should be written into a temporary table.  Set to FALSE if each
00347     ** row of the SELECT can be written directly into the result table.
00348     **
00349     ** A temp table must be used if the table being updated is also one
00350     ** of the tables being read by the SELECT statement.  Also use a 
00351     ** temp table in the case of row triggers.
00352     */
00353     if( triggers_exist || selectReadsTable(pSelect,pTab->pSchema,pTab->tnum) ){
00354       useTempTable = 1;
00355     }
00356 
00357     if( useTempTable ){
00358       /* Generate the subroutine that SELECT calls to process each row of
00359       ** the result.  Store the result in a temporary table
00360       */
00361       srcTab = pParse->nTab++;
00362       sqlite3VdbeResolveLabel(v, iInsertBlock);
00363       sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
00364       sqlite3VdbeAddOp(v, OP_NewRowid, srcTab, 0);
00365       sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
00366       sqlite3VdbeAddOp(v, OP_Insert, srcTab, 0);
00367       sqlite3VdbeAddOp(v, OP_Return, 0, 0);
00368 
00369       /* The following code runs first because the GOTO at the very top
00370       ** of the program jumps to it.  Create the temporary table, then jump
00371       ** back up and execute the SELECT code above.
00372       */
00373       sqlite3VdbeJumpHere(v, iInitCode);
00374       sqlite3VdbeAddOp(v, OP_OpenVirtual, srcTab, 0);
00375       sqlite3VdbeAddOp(v, OP_SetNumColumns, srcTab, nColumn);
00376       sqlite3VdbeAddOp(v, OP_Goto, 0, iSelectLoop);
00377       sqlite3VdbeResolveLabel(v, iCleanup);
00378     }else{
00379       sqlite3VdbeJumpHere(v, iInitCode);
00380     }
00381   }else{
00382     /* This is the case if the data for the INSERT is coming from a VALUES
00383     ** clause
00384     */
00385     NameContext sNC;
00386     memset(&sNC, 0, sizeof(sNC));
00387     sNC.pParse = pParse;
00388     assert( pList!=0 );
00389     srcTab = -1;
00390     useTempTable = 0;
00391     assert( pList );
00392     nColumn = pList->nExpr;
00393     for(i=0; i<nColumn; i++){
00394       if( sqlite3ExprResolveNames(&sNC, pList->a[i].pExpr) ){
00395         goto insert_cleanup;
00396       }
00397     }
00398   }
00399 
00400   /* Make sure the number of columns in the source data matches the number
00401   ** of columns to be inserted into the table.
00402   */
00403   if( pColumn==0 && nColumn!=pTab->nCol ){
00404     sqlite3ErrorMsg(pParse, 
00405        "table %S has %d columns but %d values were supplied",
00406        pTabList, 0, pTab->nCol, nColumn);
00407     goto insert_cleanup;
00408   }
00409   if( pColumn!=0 && nColumn!=pColumn->nId ){
00410     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
00411     goto insert_cleanup;
00412   }
00413 
00414   /* If the INSERT statement included an IDLIST term, then make sure
00415   ** all elements of the IDLIST really are columns of the table and 
00416   ** remember the column indices.
00417   **
00418   ** If the table has an INTEGER PRIMARY KEY column and that column
00419   ** is named in the IDLIST, then record in the keyColumn variable
00420   ** the index into IDLIST of the primary key column.  keyColumn is
00421   ** the index of the primary key as it appears in IDLIST, not as
00422   ** is appears in the original table.  (The index of the primary
00423   ** key in the original table is pTab->iPKey.)
00424   */
00425   if( pColumn ){
00426     for(i=0; i<pColumn->nId; i++){
00427       pColumn->a[i].idx = -1;
00428     }
00429     for(i=0; i<pColumn->nId; i++){
00430       for(j=0; j<pTab->nCol; j++){
00431         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
00432           pColumn->a[i].idx = j;
00433           if( j==pTab->iPKey ){
00434             keyColumn = i;
00435           }
00436           break;
00437         }
00438       }
00439       if( j>=pTab->nCol ){
00440         if( sqlite3IsRowid(pColumn->a[i].zName) ){
00441           keyColumn = i;
00442         }else{
00443           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
00444               pTabList, 0, pColumn->a[i].zName);
00445           pParse->nErr++;
00446           goto insert_cleanup;
00447         }
00448       }
00449     }
00450   }
00451 
00452   /* If there is no IDLIST term but the table has an integer primary
00453   ** key, the set the keyColumn variable to the primary key column index
00454   ** in the original table definition.
00455   */
00456   if( pColumn==0 ){
00457     keyColumn = pTab->iPKey;
00458   }
00459 
00460   /* Open the temp table for FOR EACH ROW triggers
00461   */
00462   if( triggers_exist ){
00463     sqlite3VdbeAddOp(v, OP_OpenPseudo, newIdx, 0);
00464     sqlite3VdbeAddOp(v, OP_SetNumColumns, newIdx, pTab->nCol);
00465   }
00466     
00467   /* Initialize the count of rows to be inserted
00468   */
00469   if( db->flags & SQLITE_CountRows ){
00470     iCntMem = pParse->nMem++;
00471     sqlite3VdbeAddOp(v, OP_MemInt, 0, iCntMem);
00472   }
00473 
00474   /* Open tables and indices if there are no row triggers */
00475   if( !triggers_exist ){
00476     base = pParse->nTab;
00477     sqlite3OpenTableAndIndices(pParse, pTab, base, OP_OpenWrite);
00478   }
00479 
00480   /* If the data source is a temporary table, then we have to create
00481   ** a loop because there might be multiple rows of data.  If the data
00482   ** source is a subroutine call from the SELECT statement, then we need
00483   ** to launch the SELECT statement processing.
00484   */
00485   if( useTempTable ){
00486     iBreak = sqlite3VdbeMakeLabel(v);
00487     sqlite3VdbeAddOp(v, OP_Rewind, srcTab, iBreak);
00488     iCont = sqlite3VdbeCurrentAddr(v);
00489   }else if( pSelect ){
00490     sqlite3VdbeAddOp(v, OP_Goto, 0, iSelectLoop);
00491     sqlite3VdbeResolveLabel(v, iInsertBlock);
00492   }
00493 
00494   /* Run the BEFORE and INSTEAD OF triggers, if there are any
00495   */
00496   endOfLoop = sqlite3VdbeMakeLabel(v);
00497   if( triggers_exist & TRIGGER_BEFORE ){
00498 
00499     /* build the NEW.* reference row.  Note that if there is an INTEGER
00500     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
00501     ** translated into a unique ID for the row.  But on a BEFORE trigger,
00502     ** we do not know what the unique ID will be (because the insert has
00503     ** not happened yet) so we substitute a rowid of -1
00504     */
00505     if( keyColumn<0 ){
00506       sqlite3VdbeAddOp(v, OP_Integer, -1, 0);
00507     }else if( useTempTable ){
00508       sqlite3VdbeAddOp(v, OP_Column, srcTab, keyColumn);
00509     }else{
00510       assert( pSelect==0 );  /* Otherwise useTempTable is true */
00511       sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr);
00512       sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
00513       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
00514       sqlite3VdbeAddOp(v, OP_Integer, -1, 0);
00515       sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
00516     }
00517 
00518     /* Create the new column data
00519     */
00520     for(i=0; i<pTab->nCol; i++){
00521       if( pColumn==0 ){
00522         j = i;
00523       }else{
00524         for(j=0; j<pColumn->nId; j++){
00525           if( pColumn->a[j].idx==i ) break;
00526         }
00527       }
00528       if( pColumn && j>=pColumn->nId ){
00529         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
00530       }else if( useTempTable ){
00531         sqlite3VdbeAddOp(v, OP_Column, srcTab, j); 
00532       }else{
00533         assert( pSelect==0 ); /* Otherwise useTempTable is true */
00534         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr);
00535       }
00536     }
00537     sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
00538 
00539     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
00540     ** do not attempt any conversions before assembling the record.
00541     ** If this is a real table, attempt conversions as required by the
00542     ** table column affinities.
00543     */
00544     if( !isView ){
00545       sqlite3TableAffinityStr(v, pTab);
00546     }
00547     sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0);
00548 
00549     /* Fire BEFORE or INSTEAD OF triggers */
00550     if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_BEFORE, pTab, 
00551         newIdx, -1, onError, endOfLoop) ){
00552       goto insert_cleanup;
00553     }
00554   }
00555 
00556   /* If any triggers exists, the opening of tables and indices is deferred
00557   ** until now.
00558   */
00559   if( triggers_exist && !isView ){
00560     base = pParse->nTab;
00561     sqlite3OpenTableAndIndices(pParse, pTab, base, OP_OpenWrite);
00562   }
00563 
00564   /* Push the record number for the new entry onto the stack.  The
00565   ** record number is a randomly generate integer created by NewRowid
00566   ** except when the table has an INTEGER PRIMARY KEY column, in which
00567   ** case the record number is the same as that column. 
00568   */
00569   if( !isView ){
00570     if( keyColumn>=0 ){
00571       if( useTempTable ){
00572         sqlite3VdbeAddOp(v, OP_Column, srcTab, keyColumn);
00573       }else if( pSelect ){
00574         sqlite3VdbeAddOp(v, OP_Dup, nColumn - keyColumn - 1, 1);
00575       }else{
00576         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr);
00577       }
00578       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
00579       ** to generate a unique primary key value.
00580       */
00581       sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
00582       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
00583       sqlite3VdbeAddOp(v, OP_NewRowid, base, counterMem);
00584       sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
00585     }else{
00586       sqlite3VdbeAddOp(v, OP_NewRowid, base, counterMem);
00587     }
00588 #ifndef SQLITE_OMIT_AUTOINCREMENT
00589     if( pTab->autoInc ){
00590       sqlite3VdbeAddOp(v, OP_MemMax, counterMem, 0);
00591     }
00592 #endif /* SQLITE_OMIT_AUTOINCREMENT */
00593 
00594     /* Push onto the stack, data for all columns of the new entry, beginning
00595     ** with the first column.
00596     */
00597     for(i=0; i<pTab->nCol; i++){
00598       if( i==pTab->iPKey ){
00599         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
00600         ** Whenever this column is read, the record number will be substituted
00601         ** in its place.  So will fill this column with a NULL to avoid
00602         ** taking up data space with information that will never be used. */
00603         sqlite3VdbeAddOp(v, OP_Null, 0, 0);
00604         continue;
00605       }
00606       if( pColumn==0 ){
00607         j = i;
00608       }else{
00609         for(j=0; j<pColumn->nId; j++){
00610           if( pColumn->a[j].idx==i ) break;
00611         }
00612       }
00613       if( pColumn && j>=pColumn->nId ){
00614         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
00615       }else if( useTempTable ){
00616         sqlite3VdbeAddOp(v, OP_Column, srcTab, j); 
00617       }else if( pSelect ){
00618         sqlite3VdbeAddOp(v, OP_Dup, i+nColumn-j, 1);
00619       }else{
00620         sqlite3ExprCode(pParse, pList->a[j].pExpr);
00621       }
00622     }
00623 
00624     /* Generate code to check constraints and generate index keys and
00625     ** do the insertion.
00626     */
00627     sqlite3GenerateConstraintChecks(pParse, pTab, base, 0, keyColumn>=0,
00628                                    0, onError, endOfLoop);
00629     sqlite3CompleteInsertion(pParse, pTab, base, 0,0,0,
00630                             (triggers_exist & TRIGGER_AFTER)!=0 ? newIdx : -1);
00631   }
00632 
00633   /* Update the count of rows that are inserted
00634   */
00635   if( (db->flags & SQLITE_CountRows)!=0 ){
00636     sqlite3VdbeAddOp(v, OP_MemIncr, 1, iCntMem);
00637   }
00638 
00639   if( triggers_exist ){
00640     /* Close all tables opened */
00641     if( !isView ){
00642       sqlite3VdbeAddOp(v, OP_Close, base, 0);
00643       for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
00644         sqlite3VdbeAddOp(v, OP_Close, idx+base, 0);
00645       }
00646     }
00647 
00648     /* Code AFTER triggers */
00649     if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_AFTER, pTab,
00650           newIdx, -1, onError, endOfLoop) ){
00651       goto insert_cleanup;
00652     }
00653   }
00654 
00655   /* The bottom of the loop, if the data source is a SELECT statement
00656   */
00657   sqlite3VdbeResolveLabel(v, endOfLoop);
00658   if( useTempTable ){
00659     sqlite3VdbeAddOp(v, OP_Next, srcTab, iCont);
00660     sqlite3VdbeResolveLabel(v, iBreak);
00661     sqlite3VdbeAddOp(v, OP_Close, srcTab, 0);
00662   }else if( pSelect ){
00663     sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
00664     sqlite3VdbeAddOp(v, OP_Return, 0, 0);
00665     sqlite3VdbeResolveLabel(v, iCleanup);
00666   }
00667 
00668   if( !triggers_exist ){
00669     /* Close all tables opened */
00670     sqlite3VdbeAddOp(v, OP_Close, base, 0);
00671     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
00672       sqlite3VdbeAddOp(v, OP_Close, idx+base, 0);
00673     }
00674   }
00675 
00676 #ifndef SQLITE_OMIT_AUTOINCREMENT
00677   /* Update the sqlite_sequence table by storing the content of the
00678   ** counter value in memory counterMem back into the sqlite_sequence
00679   ** table.
00680   */
00681   if( pTab->autoInc ){
00682     int iCur = pParse->nTab;
00683     int addr = sqlite3VdbeCurrentAddr(v);
00684     sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
00685     sqlite3VdbeAddOp(v, OP_MemLoad, counterRowid, 0);
00686     sqlite3VdbeAddOp(v, OP_NotNull, -1, addr+7);
00687     sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
00688     sqlite3VdbeAddOp(v, OP_NewRowid, iCur, 0);
00689     sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0);
00690     sqlite3VdbeAddOp(v, OP_MemLoad, counterMem, 0);
00691     sqlite3VdbeAddOp(v, OP_MakeRecord, 2, 0);
00692     sqlite3VdbeAddOp(v, OP_Insert, iCur, 0);
00693     sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
00694   }
00695 #endif
00696 
00697   /*
00698   ** Return the number of rows inserted. If this routine is 
00699   ** generating code because of a call to sqlite3NestedParse(), do not
00700   ** invoke the callback function.
00701   */
00702   if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
00703     sqlite3VdbeAddOp(v, OP_MemLoad, iCntMem, 0);
00704     sqlite3VdbeAddOp(v, OP_Callback, 1, 0);
00705     sqlite3VdbeSetNumCols(v, 1);
00706     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", P3_STATIC);
00707   }
00708 
00709 insert_cleanup:
00710   sqlite3SrcListDelete(pTabList);
00711   sqlite3ExprListDelete(pList);
00712   sqlite3SelectDelete(pSelect);
00713   sqlite3IdListDelete(pColumn);
00714 }
00715 
00716 /*
00717 ** Generate code to do a constraint check prior to an INSERT or an UPDATE.
00718 **
00719 ** When this routine is called, the stack contains (from bottom to top)
00720 ** the following values:
00721 **
00722 **    1.  The rowid of the row to be updated before the update.  This
00723 **        value is omitted unless we are doing an UPDATE that involves a
00724 **        change to the record number.
00725 **
00726 **    2.  The rowid of the row after the update.
00727 **
00728 **    3.  The data in the first column of the entry after the update.
00729 **
00730 **    i.  Data from middle columns...
00731 **
00732 **    N.  The data in the last column of the entry after the update.
00733 **
00734 ** The old rowid shown as entry (1) above is omitted unless both isUpdate
00735 ** and rowidChng are 1.  isUpdate is true for UPDATEs and false for
00736 ** INSERTs and rowidChng is true if the record number is being changed.
00737 **
00738 ** The code generated by this routine pushes additional entries onto
00739 ** the stack which are the keys for new index entries for the new record.
00740 ** The order of index keys is the same as the order of the indices on
00741 ** the pTable->pIndex list.  A key is only created for index i if 
00742 ** aIdxUsed!=0 and aIdxUsed[i]!=0.
00743 **
00744 ** This routine also generates code to check constraints.  NOT NULL,
00745 ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
00746 ** then the appropriate action is performed.  There are five possible
00747 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
00748 **
00749 **  Constraint type  Action       What Happens
00750 **  ---------------  ----------   ----------------------------------------
00751 **  any              ROLLBACK     The current transaction is rolled back and
00752 **                                sqlite3_exec() returns immediately with a
00753 **                                return code of SQLITE_CONSTRAINT.
00754 **
00755 **  any              ABORT        Back out changes from the current command
00756 **                                only (do not do a complete rollback) then
00757 **                                cause sqlite3_exec() to return immediately
00758 **                                with SQLITE_CONSTRAINT.
00759 **
00760 **  any              FAIL         Sqlite_exec() returns immediately with a
00761 **                                return code of SQLITE_CONSTRAINT.  The
00762 **                                transaction is not rolled back and any
00763 **                                prior changes are retained.
00764 **
00765 **  any              IGNORE       The record number and data is popped from
00766 **                                the stack and there is an immediate jump
00767 **                                to label ignoreDest.
00768 **
00769 **  NOT NULL         REPLACE      The NULL value is replace by the default
00770 **                                value for that column.  If the default value
00771 **                                is NULL, the action is the same as ABORT.
00772 **
00773 **  UNIQUE           REPLACE      The other row that conflicts with the row
00774 **                                being inserted is removed.
00775 **
00776 **  CHECK            REPLACE      Illegal.  The results in an exception.
00777 **
00778 ** Which action to take is determined by the overrideError parameter.
00779 ** Or if overrideError==OE_Default, then the pParse->onError parameter
00780 ** is used.  Or if pParse->onError==OE_Default then the onError value
00781 ** for the constraint is used.
00782 **
00783 ** The calling routine must open a read/write cursor for pTab with
00784 ** cursor number "base".  All indices of pTab must also have open
00785 ** read/write cursors with cursor number base+i for the i-th cursor.
00786 ** Except, if there is no possibility of a REPLACE action then
00787 ** cursors do not need to be open for indices where aIdxUsed[i]==0.
00788 **
00789 ** If the isUpdate flag is true, it means that the "base" cursor is
00790 ** initially pointing to an entry that is being updated.  The isUpdate
00791 ** flag causes extra code to be generated so that the "base" cursor
00792 ** is still pointing at the same entry after the routine returns.
00793 ** Without the isUpdate flag, the "base" cursor might be moved.
00794 */
00795 void sqlite3GenerateConstraintChecks(
00796   Parse *pParse,      /* The parser context */
00797   Table *pTab,        /* the table into which we are inserting */
00798   int base,           /* Index of a read/write cursor pointing at pTab */
00799   char *aIdxUsed,     /* Which indices are used.  NULL means all are used */
00800   int rowidChng,      /* True if the record number will change */
00801   int isUpdate,       /* True for UPDATE, False for INSERT */
00802   int overrideError,  /* Override onError to this if not OE_Default */
00803   int ignoreDest      /* Jump to this label on an OE_Ignore resolution */
00804 ){
00805   int i;
00806   Vdbe *v;
00807   int nCol;
00808   int onError;
00809   int addr;
00810   int extra;
00811   int iCur;
00812   Index *pIdx;
00813   int seenReplace = 0;
00814   int jumpInst1=0, jumpInst2;
00815   int hasTwoRowids = (isUpdate && rowidChng);
00816 
00817   v = sqlite3GetVdbe(pParse);
00818   assert( v!=0 );
00819   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
00820   nCol = pTab->nCol;
00821 
00822   /* Test all NOT NULL constraints.
00823   */
00824   for(i=0; i<nCol; i++){
00825     if( i==pTab->iPKey ){
00826       continue;
00827     }
00828     onError = pTab->aCol[i].notNull;
00829     if( onError==OE_None ) continue;
00830     if( overrideError!=OE_Default ){
00831       onError = overrideError;
00832     }else if( onError==OE_Default ){
00833       onError = OE_Abort;
00834     }
00835     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
00836       onError = OE_Abort;
00837     }
00838     sqlite3VdbeAddOp(v, OP_Dup, nCol-1-i, 1);
00839     addr = sqlite3VdbeAddOp(v, OP_NotNull, 1, 0);
00840     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
00841         || onError==OE_Ignore || onError==OE_Replace );
00842     switch( onError ){
00843       case OE_Rollback:
00844       case OE_Abort:
00845       case OE_Fail: {
00846         char *zMsg = 0;
00847         sqlite3VdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
00848         sqlite3SetString(&zMsg, pTab->zName, ".", pTab->aCol[i].zName,
00849                         " may not be NULL", (char*)0);
00850         sqlite3VdbeChangeP3(v, -1, zMsg, P3_DYNAMIC);
00851         break;
00852       }
00853       case OE_Ignore: {
00854         sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
00855         sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
00856         break;
00857       }
00858       case OE_Replace: {
00859         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
00860         sqlite3VdbeAddOp(v, OP_Push, nCol-i, 0);
00861         break;
00862       }
00863     }
00864     sqlite3VdbeJumpHere(v, addr);
00865   }
00866 
00867   /* Test all CHECK constraints
00868   */
00869 #ifndef SQLITE_OMIT_CHECK
00870   if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
00871     int allOk = sqlite3VdbeMakeLabel(v);
00872     assert( pParse->ckOffset==0 );
00873     pParse->ckOffset = nCol;
00874     sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, 1);
00875     assert( pParse->ckOffset==nCol );
00876     pParse->ckOffset = 0;
00877     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
00878     if( onError==OE_Ignore || onError==OE_Replace ){
00879       sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
00880       sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
00881     }else{
00882       sqlite3VdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
00883     }
00884     sqlite3VdbeResolveLabel(v, allOk);
00885   }
00886 #endif /* !defined(SQLITE_OMIT_CHECK) */
00887 
00888   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
00889   ** of the new record does not previously exist.  Except, if this
00890   ** is an UPDATE and the primary key is not changing, that is OK.
00891   */
00892   if( rowidChng ){
00893     onError = pTab->keyConf;
00894     if( overrideError!=OE_Default ){
00895       onError = overrideError;
00896     }else if( onError==OE_Default ){
00897       onError = OE_Abort;
00898     }
00899     
00900     if( isUpdate ){
00901       sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
00902       sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
00903       jumpInst1 = sqlite3VdbeAddOp(v, OP_Eq, 0, 0);
00904     }
00905     sqlite3VdbeAddOp(v, OP_Dup, nCol, 1);
00906     jumpInst2 = sqlite3VdbeAddOp(v, OP_NotExists, base, 0);
00907     switch( onError ){
00908       default: {
00909         onError = OE_Abort;
00910         /* Fall thru into the next case */
00911       }
00912       case OE_Rollback:
00913       case OE_Abort:
00914       case OE_Fail: {
00915         sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError,
00916                          "PRIMARY KEY must be unique", P3_STATIC);
00917         break;
00918       }
00919       case OE_Replace: {
00920         sqlite3GenerateRowIndexDelete(v, pTab, base, 0);
00921         if( isUpdate ){
00922           sqlite3VdbeAddOp(v, OP_Dup, nCol+hasTwoRowids, 1);
00923           sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
00924         }
00925         seenReplace = 1;
00926         break;
00927       }
00928       case OE_Ignore: {
00929         assert( seenReplace==0 );
00930         sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
00931         sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
00932         break;
00933       }
00934     }
00935     sqlite3VdbeJumpHere(v, jumpInst2);
00936     if( isUpdate ){
00937       sqlite3VdbeJumpHere(v, jumpInst1);
00938       sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
00939       sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
00940     }
00941   }
00942 
00943   /* Test all UNIQUE constraints by creating entries for each UNIQUE
00944   ** index and making sure that duplicate entries do not already exist.
00945   ** Add the new records to the indices as we go.
00946   */
00947   extra = -1;
00948   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
00949     if( aIdxUsed && aIdxUsed[iCur]==0 ) continue;  /* Skip unused indices */
00950     extra++;
00951 
00952     /* Create a key for accessing the index entry */
00953     sqlite3VdbeAddOp(v, OP_Dup, nCol+extra, 1);
00954     for(i=0; i<pIdx->nColumn; i++){
00955       int idx = pIdx->aiColumn[i];
00956       if( idx==pTab->iPKey ){
00957         sqlite3VdbeAddOp(v, OP_Dup, i+extra+nCol+1, 1);
00958       }else{
00959         sqlite3VdbeAddOp(v, OP_Dup, i+extra+nCol-idx, 1);
00960       }
00961     }
00962     jumpInst1 = sqlite3VdbeAddOp(v, OP_MakeIdxRec, pIdx->nColumn, 0);
00963     sqlite3IndexAffinityStr(v, pIdx);
00964 
00965     /* Find out what action to take in case there is an indexing conflict */
00966     onError = pIdx->onError;
00967     if( onError==OE_None ) continue;  /* pIdx is not a UNIQUE index */
00968     if( overrideError!=OE_Default ){
00969       onError = overrideError;
00970     }else if( onError==OE_Default ){
00971       onError = OE_Abort;
00972     }
00973     if( seenReplace ){
00974       if( onError==OE_Ignore ) onError = OE_Replace;
00975       else if( onError==OE_Fail ) onError = OE_Abort;
00976     }
00977     
00978 
00979     /* Check to see if the new index entry will be unique */
00980     sqlite3VdbeAddOp(v, OP_Dup, extra+nCol+1+hasTwoRowids, 1);
00981     jumpInst2 = sqlite3VdbeAddOp(v, OP_IsUnique, base+iCur+1, 0);
00982 
00983     /* Generate code that executes if the new index entry is not unique */
00984     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
00985         || onError==OE_Ignore || onError==OE_Replace );
00986     switch( onError ){
00987       case OE_Rollback:
00988       case OE_Abort:
00989       case OE_Fail: {
00990         int j, n1, n2;
00991         char zErrMsg[200];
00992         strcpy(zErrMsg, pIdx->nColumn>1 ? "columns " : "column ");
00993         n1 = strlen(zErrMsg);
00994         for(j=0; j<pIdx->nColumn && n1<sizeof(zErrMsg)-30; j++){
00995           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
00996           n2 = strlen(zCol);
00997           if( j>0 ){
00998             strcpy(&zErrMsg[n1], ", ");
00999             n1 += 2;
01000           }
01001           if( n1+n2>sizeof(zErrMsg)-30 ){
01002             strcpy(&zErrMsg[n1], "...");
01003             n1 += 3;
01004             break;
01005           }else{
01006             strcpy(&zErrMsg[n1], zCol);
01007             n1 += n2;
01008           }
01009         }
01010         strcpy(&zErrMsg[n1], 
01011             pIdx->nColumn>1 ? " are not unique" : " is not unique");
01012         sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError, zErrMsg, 0);
01013         break;
01014       }
01015       case OE_Ignore: {
01016         assert( seenReplace==0 );
01017         sqlite3VdbeAddOp(v, OP_Pop, nCol+extra+3+hasTwoRowids, 0);
01018         sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
01019         break;
01020       }
01021       case OE_Replace: {
01022         sqlite3GenerateRowDelete(pParse->db, v, pTab, base, 0);
01023         if( isUpdate ){
01024           sqlite3VdbeAddOp(v, OP_Dup, nCol+extra+1+hasTwoRowids, 1);
01025           sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
01026         }
01027         seenReplace = 1;
01028         break;
01029       }
01030     }
01031 #if NULL_DISTINCT_FOR_UNIQUE
01032     sqlite3VdbeJumpHere(v, jumpInst1);
01033 #endif
01034     sqlite3VdbeJumpHere(v, jumpInst2);
01035   }
01036 }
01037 
01038 /*
01039 ** This routine generates code to finish the INSERT or UPDATE operation
01040 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
01041 ** The stack must contain keys for all active indices followed by data
01042 ** and the rowid for the new entry.  This routine creates the new
01043 ** entries in all indices and in the main table.
01044 **
01045 ** The arguments to this routine should be the same as the first six
01046 ** arguments to sqlite3GenerateConstraintChecks.
01047 */
01048 void sqlite3CompleteInsertion(
01049   Parse *pParse,      /* The parser context */
01050   Table *pTab,        /* the table into which we are inserting */
01051   int base,           /* Index of a read/write cursor pointing at pTab */
01052   char *aIdxUsed,     /* Which indices are used.  NULL means all are used */
01053   int rowidChng,      /* True if the record number will change */
01054   int isUpdate,       /* True for UPDATE, False for INSERT */
01055   int newIdx          /* Index of NEW table for triggers.  -1 if none */
01056 ){
01057   int i;
01058   Vdbe *v;
01059   int nIdx;
01060   Index *pIdx;
01061   int pik_flags;
01062 
01063   v = sqlite3GetVdbe(pParse);
01064   assert( v!=0 );
01065   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
01066   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
01067   for(i=nIdx-1; i>=0; i--){
01068     if( aIdxUsed && aIdxUsed[i]==0 ) continue;
01069     sqlite3VdbeAddOp(v, OP_IdxInsert, base+i+1, 0);
01070   }
01071   sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
01072   sqlite3TableAffinityStr(v, pTab);
01073 #ifndef SQLITE_OMIT_TRIGGER
01074   if( newIdx>=0 ){
01075     sqlite3VdbeAddOp(v, OP_Dup, 1, 0);
01076     sqlite3VdbeAddOp(v, OP_Dup, 1, 0);
01077     sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0);
01078   }
01079 #endif
01080   if( pParse->nested ){
01081     pik_flags = 0;
01082   }else{
01083     pik_flags = OPFLAG_NCHANGE;
01084     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
01085   }
01086   sqlite3VdbeAddOp(v, OP_Insert, base, pik_flags);
01087   if( !pParse->nested ){
01088     sqlite3VdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
01089   }
01090   
01091   if( isUpdate && rowidChng ){
01092     sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
01093   }
01094 }
01095 
01096 /*
01097 ** Generate code that will open cursors for a table and for all
01098 ** indices of that table.  The "base" parameter is the cursor number used
01099 ** for the table.  Indices are opened on subsequent cursors.
01100 */
01101 void sqlite3OpenTableAndIndices(
01102   Parse *pParse,   /* Parsing context */
01103   Table *pTab,     /* Table to be opened */
01104   int base,        /* Cursor number assigned to the table */
01105   int op           /* OP_OpenRead or OP_OpenWrite */
01106 ){
01107   int i;
01108   int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
01109   Index *pIdx;
01110   Vdbe *v = sqlite3GetVdbe(pParse);
01111   assert( v!=0 );
01112   sqlite3OpenTable(pParse, base, iDb, pTab, op);
01113   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
01114     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
01115     assert( pIdx->pSchema==pTab->pSchema );
01116     sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
01117     VdbeComment((v, "# %s", pIdx->zName));
01118     sqlite3VdbeOp3(v, op, i+base, pIdx->tnum, (char*)pKey, P3_KEYINFO_HANDOFF);
01119   }
01120   if( pParse->nTab<=base+i ){
01121     pParse->nTab = base+i;
01122   }
01123 }