persistentstorage/sqlite3api/SQLite/update.c
changeset 0 08ec8eefde2f
equal deleted inserted replaced
-1:000000000000 0:08ec8eefde2f
       
     1 /*
       
     2 ** 2001 September 15
       
     3 **
       
     4 ** The author disclaims copyright to this source code.  In place of
       
     5 ** a legal notice, here is a blessing:
       
     6 **
       
     7 **    May you do good and not evil.
       
     8 **    May you find forgiveness for yourself and forgive others.
       
     9 **    May you share freely, never taking more than you give.
       
    10 **
       
    11 *************************************************************************
       
    12 ** This file contains C code routines that are called by the parser
       
    13 ** to handle UPDATE statements.
       
    14 **
       
    15 ** $Id: update.c,v 1.184 2008/09/01 21:59:43 shane Exp $
       
    16 */
       
    17 #include "sqliteInt.h"
       
    18 
       
    19 #ifndef SQLITE_OMIT_VIRTUALTABLE
       
    20 /* Forward declaration */
       
    21 static void updateVirtualTable(
       
    22   Parse *pParse,       /* The parsing context */
       
    23   SrcList *pSrc,       /* The virtual table to be modified */
       
    24   Table *pTab,         /* The virtual table */
       
    25   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
       
    26   Expr *pRowidExpr,    /* Expression used to recompute the rowid */
       
    27   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
       
    28   Expr *pWhere         /* WHERE clause of the UPDATE statement */
       
    29 );
       
    30 #endif /* SQLITE_OMIT_VIRTUALTABLE */
       
    31 
       
    32 /*
       
    33 ** The most recently coded instruction was an OP_Column to retrieve the
       
    34 ** i-th column of table pTab. This routine sets the P4 parameter of the 
       
    35 ** OP_Column to the default value, if any.
       
    36 **
       
    37 ** The default value of a column is specified by a DEFAULT clause in the 
       
    38 ** column definition. This was either supplied by the user when the table
       
    39 ** was created, or added later to the table definition by an ALTER TABLE
       
    40 ** command. If the latter, then the row-records in the table btree on disk
       
    41 ** may not contain a value for the column and the default value, taken
       
    42 ** from the P4 parameter of the OP_Column instruction, is returned instead.
       
    43 ** If the former, then all row-records are guaranteed to include a value
       
    44 ** for the column and the P4 value is not required.
       
    45 **
       
    46 ** Column definitions created by an ALTER TABLE command may only have 
       
    47 ** literal default values specified: a number, null or a string. (If a more
       
    48 ** complicated default expression value was provided, it is evaluated 
       
    49 ** when the ALTER TABLE is executed and one of the literal values written
       
    50 ** into the sqlite_master table.)
       
    51 **
       
    52 ** Therefore, the P4 parameter is only required if the default value for
       
    53 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
       
    54 ** function is capable of transforming these types of expressions into
       
    55 ** sqlite3_value objects.
       
    56 */
       
    57 void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i){
       
    58   if( pTab && !pTab->pSelect ){
       
    59     sqlite3_value *pValue;
       
    60     u8 enc = ENC(sqlite3VdbeDb(v));
       
    61     Column *pCol = &pTab->aCol[i];
       
    62     VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
       
    63     assert( i<pTab->nCol );
       
    64     sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc, 
       
    65                          pCol->affinity, &pValue);
       
    66     if( pValue ){
       
    67       sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
       
    68     }
       
    69   }
       
    70 }
       
    71 
       
    72 /*
       
    73 ** Process an UPDATE statement.
       
    74 **
       
    75 **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
       
    76 **          \_______/ \________/     \______/       \________________/
       
    77 *            onError   pTabList      pChanges             pWhere
       
    78 */
       
    79 void sqlite3Update(
       
    80   Parse *pParse,         /* The parser context */
       
    81   SrcList *pTabList,     /* The table in which we should change things */
       
    82   ExprList *pChanges,    /* Things to be changed */
       
    83   Expr *pWhere,          /* The WHERE clause.  May be null */
       
    84   int onError            /* How to handle constraint errors */
       
    85 ){
       
    86   int i, j;              /* Loop counters */
       
    87   Table *pTab;           /* The table to be updated */
       
    88   int addr = 0;          /* VDBE instruction address of the start of the loop */
       
    89   WhereInfo *pWInfo;     /* Information about the WHERE clause */
       
    90   Vdbe *v;               /* The virtual database engine */
       
    91   Index *pIdx;           /* For looping over indices */
       
    92   int nIdx;              /* Number of indices that need updating */
       
    93   int iCur;              /* VDBE Cursor number of pTab */
       
    94   sqlite3 *db;           /* The database structure */
       
    95   int *aRegIdx = 0;      /* One register assigned to each index to be updated */
       
    96   int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
       
    97                          ** an expression for the i-th column of the table.
       
    98                          ** aXRef[i]==-1 if the i-th column is not changed. */
       
    99   int chngRowid;         /* True if the record number is being changed */
       
   100   Expr *pRowidExpr = 0;  /* Expression defining the new record number */
       
   101   int openAll = 0;       /* True if all indices need to be opened */
       
   102   AuthContext sContext;  /* The authorization context */
       
   103   NameContext sNC;       /* The name-context to resolve expressions in */
       
   104   int iDb;               /* Database containing the table being updated */
       
   105   int j1;                /* Addresses of jump instructions */
       
   106   int okOnePass;         /* True for one-pass algorithm without the FIFO */
       
   107 
       
   108 #ifndef SQLITE_OMIT_TRIGGER
       
   109   int isView;                  /* Trying to update a view */
       
   110   int triggers_exist = 0;      /* True if any row triggers exist */
       
   111 #endif
       
   112   int iBeginAfterTrigger;      /* Address of after trigger program */
       
   113   int iEndAfterTrigger;        /* Exit of after trigger program */
       
   114   int iBeginBeforeTrigger;     /* Address of before trigger program */
       
   115   int iEndBeforeTrigger;       /* Exit of before trigger program */
       
   116   u32 old_col_mask = 0;        /* Mask of OLD.* columns in use */
       
   117   u32 new_col_mask = 0;        /* Mask of NEW.* columns in use */
       
   118 
       
   119   int newIdx      = -1;  /* index of trigger "new" temp table       */
       
   120   int oldIdx      = -1;  /* index of trigger "old" temp table       */
       
   121 
       
   122   /* Register Allocations */
       
   123   int regRowCount = 0;   /* A count of rows changed */
       
   124   int regOldRowid;       /* The old rowid */
       
   125   int regNewRowid;       /* The new rowid */
       
   126   int regData;           /* New data for the row */
       
   127 
       
   128   sContext.pParse = 0;
       
   129   db = pParse->db;
       
   130   if( pParse->nErr || db->mallocFailed ){
       
   131     goto update_cleanup;
       
   132   }
       
   133   assert( pTabList->nSrc==1 );
       
   134 
       
   135   /* Locate the table which we want to update. 
       
   136   */
       
   137   pTab = sqlite3SrcListLookup(pParse, pTabList);
       
   138   if( pTab==0 ) goto update_cleanup;
       
   139   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
       
   140 
       
   141   /* Figure out if we have any triggers and if the table being
       
   142   ** updated is a view
       
   143   */
       
   144 #ifndef SQLITE_OMIT_TRIGGER
       
   145   triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges);
       
   146   isView = pTab->pSelect!=0;
       
   147 #else
       
   148 # define triggers_exist 0
       
   149 # define isView 0
       
   150 #endif
       
   151 #ifdef SQLITE_OMIT_VIEW
       
   152 # undef isView
       
   153 # define isView 0
       
   154 #endif
       
   155 
       
   156   if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
       
   157     goto update_cleanup;
       
   158   }
       
   159   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
       
   160     goto update_cleanup;
       
   161   }
       
   162   aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
       
   163   if( aXRef==0 ) goto update_cleanup;
       
   164   for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
       
   165 
       
   166   /* If there are FOR EACH ROW triggers, allocate cursors for the
       
   167   ** special OLD and NEW tables
       
   168   */
       
   169   if( triggers_exist ){
       
   170     newIdx = pParse->nTab++;
       
   171     oldIdx = pParse->nTab++;
       
   172   }
       
   173 
       
   174   /* Allocate a cursors for the main database table and for all indices.
       
   175   ** The index cursors might not be used, but if they are used they
       
   176   ** need to occur right after the database cursor.  So go ahead and
       
   177   ** allocate enough space, just in case.
       
   178   */
       
   179   pTabList->a[0].iCursor = iCur = pParse->nTab++;
       
   180   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
       
   181     pParse->nTab++;
       
   182   }
       
   183 
       
   184   /* Initialize the name-context */
       
   185   memset(&sNC, 0, sizeof(sNC));
       
   186   sNC.pParse = pParse;
       
   187   sNC.pSrcList = pTabList;
       
   188 
       
   189   /* Resolve the column names in all the expressions of the
       
   190   ** of the UPDATE statement.  Also find the column index
       
   191   ** for each column to be updated in the pChanges array.  For each
       
   192   ** column to be updated, make sure we have authorization to change
       
   193   ** that column.
       
   194   */
       
   195   chngRowid = 0;
       
   196   for(i=0; i<pChanges->nExpr; i++){
       
   197     if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
       
   198       goto update_cleanup;
       
   199     }
       
   200     for(j=0; j<pTab->nCol; j++){
       
   201       if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
       
   202         if( j==pTab->iPKey ){
       
   203           chngRowid = 1;
       
   204           pRowidExpr = pChanges->a[i].pExpr;
       
   205         }
       
   206         aXRef[j] = i;
       
   207         break;
       
   208       }
       
   209     }
       
   210     if( j>=pTab->nCol ){
       
   211       if( sqlite3IsRowid(pChanges->a[i].zName) ){
       
   212         chngRowid = 1;
       
   213         pRowidExpr = pChanges->a[i].pExpr;
       
   214       }else{
       
   215         sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
       
   216         goto update_cleanup;
       
   217       }
       
   218     }
       
   219 #ifndef SQLITE_OMIT_AUTHORIZATION
       
   220     {
       
   221       int rc;
       
   222       rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
       
   223                            pTab->aCol[j].zName, db->aDb[iDb].zName);
       
   224       if( rc==SQLITE_DENY ){
       
   225         goto update_cleanup;
       
   226       }else if( rc==SQLITE_IGNORE ){
       
   227         aXRef[j] = -1;
       
   228       }
       
   229     }
       
   230 #endif
       
   231   }
       
   232 
       
   233   /* Allocate memory for the array aRegIdx[].  There is one entry in the
       
   234   ** array for each index associated with table being updated.  Fill in
       
   235   ** the value with a register number for indices that are to be used
       
   236   ** and with zero for unused indices.
       
   237   */
       
   238   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
       
   239   if( nIdx>0 ){
       
   240     aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
       
   241     if( aRegIdx==0 ) goto update_cleanup;
       
   242   }
       
   243   for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
       
   244     int reg;
       
   245     if( chngRowid ){
       
   246       reg = ++pParse->nMem;
       
   247     }else{
       
   248       reg = 0;
       
   249       for(i=0; i<pIdx->nColumn; i++){
       
   250         if( aXRef[pIdx->aiColumn[i]]>=0 ){
       
   251           reg = ++pParse->nMem;
       
   252           break;
       
   253         }
       
   254       }
       
   255     }
       
   256     aRegIdx[j] = reg;
       
   257   }
       
   258 
       
   259   /* Allocate a block of register used to store the change record
       
   260   ** sent to sqlite3GenerateConstraintChecks().  There are either
       
   261   ** one or two registers for holding the rowid.  One rowid register
       
   262   ** is used if chngRowid is false and two are used if chngRowid is
       
   263   ** true.  Following these are pTab->nCol register holding column
       
   264   ** data.
       
   265   */
       
   266   regOldRowid = regNewRowid = pParse->nMem + 1;
       
   267   pParse->nMem += pTab->nCol + 1;
       
   268   if( chngRowid ){
       
   269     regNewRowid++;
       
   270     pParse->nMem++;
       
   271   }
       
   272   regData = regNewRowid+1;
       
   273  
       
   274 
       
   275   /* Begin generating code.
       
   276   */
       
   277   v = sqlite3GetVdbe(pParse);
       
   278   if( v==0 ) goto update_cleanup;
       
   279   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
       
   280   sqlite3BeginWriteOperation(pParse, 1, iDb);
       
   281 
       
   282 #ifndef SQLITE_OMIT_VIRTUALTABLE
       
   283   /* Virtual tables must be handled separately */
       
   284   if( IsVirtual(pTab) ){
       
   285     updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
       
   286                        pWhere);
       
   287     pWhere = 0;
       
   288     pTabList = 0;
       
   289     goto update_cleanup;
       
   290   }
       
   291 #endif
       
   292 
       
   293   /* Start the view context
       
   294   */
       
   295   if( isView ){
       
   296     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
       
   297   }
       
   298 
       
   299   /* Generate the code for triggers.
       
   300   */
       
   301   if( triggers_exist ){
       
   302     int iGoto;
       
   303 
       
   304     /* Create pseudo-tables for NEW and OLD
       
   305     */
       
   306     sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol);
       
   307     sqlite3VdbeAddOp2(v, OP_OpenPseudo, oldIdx, 0);
       
   308     sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol);
       
   309     sqlite3VdbeAddOp2(v, OP_OpenPseudo, newIdx, 0);
       
   310 
       
   311     iGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
       
   312     addr = sqlite3VdbeMakeLabel(v);
       
   313     iBeginBeforeTrigger = sqlite3VdbeCurrentAddr(v);
       
   314     if( sqlite3CodeRowTrigger(pParse, TK_UPDATE, pChanges, TRIGGER_BEFORE, pTab,
       
   315           newIdx, oldIdx, onError, addr, &old_col_mask, &new_col_mask) ){
       
   316       goto update_cleanup;
       
   317     }
       
   318     iEndBeforeTrigger = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
       
   319     iBeginAfterTrigger = sqlite3VdbeCurrentAddr(v);
       
   320     if( sqlite3CodeRowTrigger(pParse, TK_UPDATE, pChanges, TRIGGER_AFTER, pTab, 
       
   321           newIdx, oldIdx, onError, addr, &old_col_mask, &new_col_mask) ){
       
   322       goto update_cleanup;
       
   323     }
       
   324     iEndAfterTrigger = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
       
   325     sqlite3VdbeJumpHere(v, iGoto);
       
   326   }
       
   327 
       
   328   /* If we are trying to update a view, realize that view into
       
   329   ** a ephemeral table.
       
   330   */
       
   331 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
       
   332   if( isView ){
       
   333     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
       
   334   }
       
   335 #endif
       
   336 
       
   337   /* Resolve the column names in all the expressions in the
       
   338   ** WHERE clause.
       
   339   */
       
   340   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
       
   341     goto update_cleanup;
       
   342   }
       
   343 
       
   344   /* Begin the database scan
       
   345   */
       
   346   sqlite3VdbeAddOp2(v, OP_Null, 0, regOldRowid);
       
   347   pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0,
       
   348                              WHERE_ONEPASS_DESIRED);
       
   349   if( pWInfo==0 ) goto update_cleanup;
       
   350   okOnePass = pWInfo->okOnePass;
       
   351 
       
   352   /* Remember the rowid of every item to be updated.
       
   353   */
       
   354   sqlite3VdbeAddOp2(v, IsVirtual(pTab)?OP_VRowid:OP_Rowid, iCur, regOldRowid);
       
   355   if( !okOnePass ) sqlite3VdbeAddOp2(v, OP_FifoWrite, regOldRowid, 0);
       
   356 
       
   357   /* End the database scan loop.
       
   358   */
       
   359   sqlite3WhereEnd(pWInfo);
       
   360 
       
   361   /* Initialize the count of updated rows
       
   362   */
       
   363   if( db->flags & SQLITE_CountRows && !pParse->trigStack ){
       
   364     regRowCount = ++pParse->nMem;
       
   365     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
       
   366   }
       
   367 
       
   368   if( !isView && !IsVirtual(pTab) ){
       
   369     /* 
       
   370     ** Open every index that needs updating.  Note that if any
       
   371     ** index could potentially invoke a REPLACE conflict resolution 
       
   372     ** action, then we need to open all indices because we might need
       
   373     ** to be deleting some records.
       
   374     */
       
   375     if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite); 
       
   376     if( onError==OE_Replace ){
       
   377       openAll = 1;
       
   378     }else{
       
   379       openAll = 0;
       
   380       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
       
   381         if( pIdx->onError==OE_Replace ){
       
   382           openAll = 1;
       
   383           break;
       
   384         }
       
   385       }
       
   386     }
       
   387     for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
       
   388       if( openAll || aRegIdx[i]>0 ){
       
   389         KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
       
   390         sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
       
   391                        (char*)pKey, P4_KEYINFO_HANDOFF);
       
   392         assert( pParse->nTab>iCur+i+1 );
       
   393       }
       
   394     }
       
   395   }
       
   396   
       
   397   /* Jump back to this point if a trigger encounters an IGNORE constraint. */
       
   398   if( triggers_exist ){
       
   399     sqlite3VdbeResolveLabel(v, addr);
       
   400   }
       
   401 
       
   402   /* Top of the update loop */
       
   403   if( okOnePass ){
       
   404     int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
       
   405     addr = sqlite3VdbeAddOp0(v, OP_Goto);
       
   406     sqlite3VdbeJumpHere(v, a1);
       
   407   }else{
       
   408     addr = sqlite3VdbeAddOp2(v, OP_FifoRead, regOldRowid, 0);
       
   409   }
       
   410 
       
   411   if( triggers_exist ){
       
   412     int regRowid;
       
   413     int regRow;
       
   414     int regCols;
       
   415 
       
   416     /* Make cursor iCur point to the record that is being updated.
       
   417     */
       
   418     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
       
   419 
       
   420     /* Generate the OLD table
       
   421     */
       
   422     regRowid = sqlite3GetTempReg(pParse);
       
   423     regRow = sqlite3GetTempReg(pParse);
       
   424     sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regRowid);
       
   425     if( !old_col_mask ){
       
   426       sqlite3VdbeAddOp2(v, OP_Null, 0, regRow);
       
   427     }else{
       
   428       sqlite3VdbeAddOp2(v, OP_RowData, iCur, regRow);
       
   429     }
       
   430     sqlite3VdbeAddOp3(v, OP_Insert, oldIdx, regRow, regRowid);
       
   431 
       
   432     /* Generate the NEW table
       
   433     */
       
   434     if( chngRowid ){
       
   435       sqlite3ExprCodeAndCache(pParse, pRowidExpr, regRowid);
       
   436     }else{
       
   437       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regRowid);
       
   438     }
       
   439     regCols = sqlite3GetTempRange(pParse, pTab->nCol);
       
   440     for(i=0; i<pTab->nCol; i++){
       
   441       if( i==pTab->iPKey ){
       
   442         sqlite3VdbeAddOp2(v, OP_Null, 0, regCols+i);
       
   443         continue;
       
   444       }
       
   445       j = aXRef[i];
       
   446       if( new_col_mask&((u32)1<<i) || new_col_mask==0xffffffff ){
       
   447         if( j<0 ){
       
   448           sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regCols+i);
       
   449           sqlite3ColumnDefault(v, pTab, i);
       
   450         }else{
       
   451           sqlite3ExprCodeAndCache(pParse, pChanges->a[j].pExpr, regCols+i);
       
   452         }
       
   453       }else{
       
   454         sqlite3VdbeAddOp2(v, OP_Null, 0, regCols+i);
       
   455       }
       
   456     }
       
   457     sqlite3VdbeAddOp3(v, OP_MakeRecord, regCols, pTab->nCol, regRow);
       
   458     if( !isView ){
       
   459       sqlite3TableAffinityStr(v, pTab);
       
   460       sqlite3ExprCacheAffinityChange(pParse, regCols, pTab->nCol);
       
   461     }
       
   462     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol);
       
   463     /* if( pParse->nErr ) goto update_cleanup; */
       
   464     sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRow, regRowid);
       
   465     sqlite3ReleaseTempReg(pParse, regRowid);
       
   466     sqlite3ReleaseTempReg(pParse, regRow);
       
   467 
       
   468     sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginBeforeTrigger);
       
   469     sqlite3VdbeJumpHere(v, iEndBeforeTrigger);
       
   470   }
       
   471 
       
   472   if( !isView && !IsVirtual(pTab) ){
       
   473     /* Loop over every record that needs updating.  We have to load
       
   474     ** the old data for each record to be updated because some columns
       
   475     ** might not change and we will need to copy the old value.
       
   476     ** Also, the old data is needed to delete the old index entries.
       
   477     ** So make the cursor point at the old record.
       
   478     */
       
   479     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
       
   480 
       
   481     /* If the record number will change, push the record number as it
       
   482     ** will be after the update. (The old record number is currently
       
   483     ** on top of the stack.)
       
   484     */
       
   485     if( chngRowid ){
       
   486       sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
       
   487       sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
       
   488     }
       
   489 
       
   490     /* Compute new data for this record.  
       
   491     */
       
   492     for(i=0; i<pTab->nCol; i++){
       
   493       if( i==pTab->iPKey ){
       
   494         sqlite3VdbeAddOp2(v, OP_Null, 0, regData+i);
       
   495         continue;
       
   496       }
       
   497       j = aXRef[i];
       
   498       if( j<0 ){
       
   499         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regData+i);
       
   500         sqlite3ColumnDefault(v, pTab, i);
       
   501       }else{
       
   502         sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regData+i);
       
   503       }
       
   504     }
       
   505 
       
   506     /* Do constraint checks
       
   507     */
       
   508     sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
       
   509                                     aRegIdx, chngRowid, 1,
       
   510                                     onError, addr);
       
   511 
       
   512     /* Delete the old indices for the current record.
       
   513     */
       
   514     j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
       
   515     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
       
   516 
       
   517     /* If changing the record number, delete the old record.
       
   518     */
       
   519     if( chngRowid ){
       
   520       sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
       
   521     }
       
   522     sqlite3VdbeJumpHere(v, j1);
       
   523 
       
   524     /* Create the new index entries and the new record.
       
   525     */
       
   526     sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, 
       
   527                              aRegIdx, chngRowid, 1, -1, 0);
       
   528   }
       
   529 
       
   530   /* Increment the row counter 
       
   531   */
       
   532   if( db->flags & SQLITE_CountRows && !pParse->trigStack){
       
   533     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
       
   534   }
       
   535 
       
   536   /* If there are triggers, close all the cursors after each iteration
       
   537   ** through the loop.  The fire the after triggers.
       
   538   */
       
   539   if( triggers_exist ){
       
   540     sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginAfterTrigger);
       
   541     sqlite3VdbeJumpHere(v, iEndAfterTrigger);
       
   542   }
       
   543 
       
   544   /* Repeat the above with the next record to be updated, until
       
   545   ** all record selected by the WHERE clause have been updated.
       
   546   */
       
   547   sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
       
   548   sqlite3VdbeJumpHere(v, addr);
       
   549 
       
   550   /* Close all tables */
       
   551   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
       
   552     if( openAll || aRegIdx[i]>0 ){
       
   553       sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
       
   554     }
       
   555   }
       
   556   sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
       
   557   if( triggers_exist ){
       
   558     sqlite3VdbeAddOp2(v, OP_Close, newIdx, 0);
       
   559     sqlite3VdbeAddOp2(v, OP_Close, oldIdx, 0);
       
   560   }
       
   561 
       
   562   /*
       
   563   ** Return the number of rows that were changed. If this routine is 
       
   564   ** generating code because of a call to sqlite3NestedParse(), do not
       
   565   ** invoke the callback function.
       
   566   */
       
   567   if( db->flags & SQLITE_CountRows && !pParse->trigStack && pParse->nested==0 ){
       
   568     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
       
   569     sqlite3VdbeSetNumCols(v, 1);
       
   570     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", P4_STATIC);
       
   571   }
       
   572 
       
   573 update_cleanup:
       
   574   sqlite3AuthContextPop(&sContext);
       
   575   sqlite3DbFree(db, aRegIdx);
       
   576   sqlite3DbFree(db, aXRef);
       
   577   sqlite3SrcListDelete(db, pTabList);
       
   578   sqlite3ExprListDelete(db, pChanges);
       
   579   sqlite3ExprDelete(db, pWhere);
       
   580   return;
       
   581 }
       
   582 
       
   583 #ifndef SQLITE_OMIT_VIRTUALTABLE
       
   584 /*
       
   585 ** Generate code for an UPDATE of a virtual table.
       
   586 **
       
   587 ** The strategy is that we create an ephemerial table that contains
       
   588 ** for each row to be changed:
       
   589 **
       
   590 **   (A)  The original rowid of that row.
       
   591 **   (B)  The revised rowid for the row. (note1)
       
   592 **   (C)  The content of every column in the row.
       
   593 **
       
   594 ** Then we loop over this ephemeral table and for each row in
       
   595 ** the ephermeral table call VUpdate.
       
   596 **
       
   597 ** When finished, drop the ephemeral table.
       
   598 **
       
   599 ** (note1) Actually, if we know in advance that (A) is always the same
       
   600 ** as (B) we only store (A), then duplicate (A) when pulling
       
   601 ** it out of the ephemeral table before calling VUpdate.
       
   602 */
       
   603 static void updateVirtualTable(
       
   604   Parse *pParse,       /* The parsing context */
       
   605   SrcList *pSrc,       /* The virtual table to be modified */
       
   606   Table *pTab,         /* The virtual table */
       
   607   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
       
   608   Expr *pRowid,        /* Expression used to recompute the rowid */
       
   609   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
       
   610   Expr *pWhere         /* WHERE clause of the UPDATE statement */
       
   611 ){
       
   612   Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
       
   613   ExprList *pEList = 0;     /* The result set of the SELECT statement */
       
   614   Select *pSelect = 0;      /* The SELECT statement */
       
   615   Expr *pExpr;              /* Temporary expression */
       
   616   int ephemTab;             /* Table holding the result of the SELECT */
       
   617   int i;                    /* Loop counter */
       
   618   int addr;                 /* Address of top of loop */
       
   619   int iReg;                 /* First register in set passed to OP_VUpdate */
       
   620   sqlite3 *db = pParse->db; /* Database connection */
       
   621   const char *pVtab = (const char*)pTab->pVtab;
       
   622   SelectDest dest;
       
   623 
       
   624   /* Construct the SELECT statement that will find the new values for
       
   625   ** all updated rows. 
       
   626   */
       
   627   pEList = sqlite3ExprListAppend(pParse, 0, 
       
   628                                  sqlite3CreateIdExpr(pParse, "_rowid_"), 0);
       
   629   if( pRowid ){
       
   630     pEList = sqlite3ExprListAppend(pParse, pEList,
       
   631                                    sqlite3ExprDup(db, pRowid), 0);
       
   632   }
       
   633   assert( pTab->iPKey<0 );
       
   634   for(i=0; i<pTab->nCol; i++){
       
   635     if( aXRef[i]>=0 ){
       
   636       pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr);
       
   637     }else{
       
   638       pExpr = sqlite3CreateIdExpr(pParse, pTab->aCol[i].zName);
       
   639     }
       
   640     pEList = sqlite3ExprListAppend(pParse, pEList, pExpr, 0);
       
   641   }
       
   642   pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
       
   643   
       
   644   /* Create the ephemeral table into which the update results will
       
   645   ** be stored.
       
   646   */
       
   647   assert( v );
       
   648   ephemTab = pParse->nTab++;
       
   649   sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
       
   650 
       
   651   /* fill the ephemeral table 
       
   652   */
       
   653   sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
       
   654   sqlite3Select(pParse, pSelect, &dest);
       
   655 
       
   656   /* Generate code to scan the ephemeral table and call VUpdate. */
       
   657   iReg = ++pParse->nMem;
       
   658   pParse->nMem += pTab->nCol+1;
       
   659   sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
       
   660   addr = sqlite3VdbeCurrentAddr(v);
       
   661   sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
       
   662   sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
       
   663   for(i=0; i<pTab->nCol; i++){
       
   664     sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
       
   665   }
       
   666   sqlite3VtabMakeWritable(pParse, pTab);
       
   667   sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVtab, P4_VTAB);
       
   668   sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr);
       
   669   sqlite3VdbeJumpHere(v, addr-1);
       
   670   sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
       
   671 
       
   672   /* Cleanup */
       
   673   sqlite3SelectDelete(db, pSelect);  
       
   674 }
       
   675 #endif /* SQLITE_OMIT_VIRTUALTABLE */
       
   676 
       
   677 /* Make sure "isView" gets undefined in case this file becomes part of
       
   678 ** the amalgamation - so that subsequent files do not see isView as a
       
   679 ** macro. */
       
   680 #undef isView