Back to index

lightning-sunbird  0.9+nobinonly
update.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 UPDATE statements.
00014 **
00015 ** $Id: update.c,v 1.123 2006/02/24 02:53:50 drh Exp $
00016 */
00017 #include "sqliteInt.h"
00018 
00019 /*
00020 ** The most recently coded instruction was an OP_Column to retrieve the
00021 ** i-th column of table pTab. This routine sets the P3 parameter of the 
00022 ** OP_Column to the default value, if any.
00023 **
00024 ** The default value of a column is specified by a DEFAULT clause in the 
00025 ** column definition. This was either supplied by the user when the table
00026 ** was created, or added later to the table definition by an ALTER TABLE
00027 ** command. If the latter, then the row-records in the table btree on disk
00028 ** may not contain a value for the column and the default value, taken
00029 ** from the P3 parameter of the OP_Column instruction, is returned instead.
00030 ** If the former, then all row-records are guaranteed to include a value
00031 ** for the column and the P3 value is not required.
00032 **
00033 ** Column definitions created by an ALTER TABLE command may only have 
00034 ** literal default values specified: a number, null or a string. (If a more
00035 ** complicated default expression value was provided, it is evaluated 
00036 ** when the ALTER TABLE is executed and one of the literal values written
00037 ** into the sqlite_master table.)
00038 **
00039 ** Therefore, the P3 parameter is only required if the default value for
00040 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
00041 ** function is capable of transforming these types of expressions into
00042 ** sqlite3_value objects.
00043 */
00044 void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i){
00045   if( pTab && !pTab->pSelect ){
00046     sqlite3_value *pValue;
00047     u8 enc = ENC(sqlite3VdbeDb(v));
00048     Column *pCol = &pTab->aCol[i];
00049     sqlite3ValueFromExpr(pCol->pDflt, enc, pCol->affinity, &pValue);
00050     if( pValue ){
00051       sqlite3VdbeChangeP3(v, -1, (const char *)pValue, P3_MEM);
00052     }else{
00053       VdbeComment((v, "# %s.%s", pTab->zName, pCol->zName));
00054     }
00055   }
00056 }
00057 
00058 /*
00059 ** Process an UPDATE statement.
00060 **
00061 **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
00062 **          \_______/ \________/     \______/       \________________/
00063 *            onError   pTabList      pChanges             pWhere
00064 */
00065 void sqlite3Update(
00066   Parse *pParse,         /* The parser context */
00067   SrcList *pTabList,     /* The table in which we should change things */
00068   ExprList *pChanges,    /* Things to be changed */
00069   Expr *pWhere,          /* The WHERE clause.  May be null */
00070   int onError            /* How to handle constraint errors */
00071 ){
00072   int i, j;              /* Loop counters */
00073   Table *pTab;           /* The table to be updated */
00074   int addr = 0;          /* VDBE instruction address of the start of the loop */
00075   WhereInfo *pWInfo;     /* Information about the WHERE clause */
00076   Vdbe *v;               /* The virtual database engine */
00077   Index *pIdx;           /* For looping over indices */
00078   int nIdx;              /* Number of indices that need updating */
00079   int nIdxTotal;         /* Total number of indices */
00080   int iCur;              /* VDBE Cursor number of pTab */
00081   sqlite3 *db;           /* The database structure */
00082   Index **apIdx = 0;     /* An array of indices that need updating too */
00083   char *aIdxUsed = 0;    /* aIdxUsed[i]==1 if the i-th index is used */
00084   int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
00085                          ** an expression for the i-th column of the table.
00086                          ** aXRef[i]==-1 if the i-th column is not changed. */
00087   int chngRowid;         /* True if the record number is being changed */
00088   Expr *pRowidExpr = 0;  /* Expression defining the new record number */
00089   int openAll = 0;       /* True if all indices need to be opened */
00090   AuthContext sContext;  /* The authorization context */
00091   NameContext sNC;       /* The name-context to resolve expressions in */
00092   int iDb;               /* Database containing the table being updated */
00093 
00094 #ifndef SQLITE_OMIT_TRIGGER
00095   int isView;                  /* Trying to update a view */
00096   int triggers_exist = 0;      /* True if any row triggers exist */
00097 #endif
00098 
00099   int newIdx      = -1;  /* index of trigger "new" temp table       */
00100   int oldIdx      = -1;  /* index of trigger "old" temp table       */
00101 
00102   sContext.pParse = 0;
00103   if( pParse->nErr || sqlite3MallocFailed() ){
00104     goto update_cleanup;
00105   }
00106   db = pParse->db;
00107   assert( pTabList->nSrc==1 );
00108 
00109   /* Locate the table which we want to update. 
00110   */
00111   pTab = sqlite3SrcListLookup(pParse, pTabList);
00112   if( pTab==0 ) goto update_cleanup;
00113   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
00114 
00115   /* Figure out if we have any triggers and if the table being
00116   ** updated is a view
00117   */
00118 #ifndef SQLITE_OMIT_TRIGGER
00119   triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges);
00120   isView = pTab->pSelect!=0;
00121 #else
00122 # define triggers_exist 0
00123 # define isView 0
00124 #endif
00125 #ifdef SQLITE_OMIT_VIEW
00126 # undef isView
00127 # define isView 0
00128 #endif
00129 
00130   if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
00131     goto update_cleanup;
00132   }
00133   if( isView ){
00134     if( sqlite3ViewGetColumnNames(pParse, pTab) ){
00135       goto update_cleanup;
00136     }
00137   }
00138   aXRef = sqliteMallocRaw( sizeof(int) * pTab->nCol );
00139   if( aXRef==0 ) goto update_cleanup;
00140   for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
00141 
00142   /* If there are FOR EACH ROW triggers, allocate cursors for the
00143   ** special OLD and NEW tables
00144   */
00145   if( triggers_exist ){
00146     newIdx = pParse->nTab++;
00147     oldIdx = pParse->nTab++;
00148   }
00149 
00150   /* Allocate a cursors for the main database table and for all indices.
00151   ** The index cursors might not be used, but if they are used they
00152   ** need to occur right after the database cursor.  So go ahead and
00153   ** allocate enough space, just in case.
00154   */
00155   pTabList->a[0].iCursor = iCur = pParse->nTab++;
00156   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
00157     pParse->nTab++;
00158   }
00159 
00160   /* Initialize the name-context */
00161   memset(&sNC, 0, sizeof(sNC));
00162   sNC.pParse = pParse;
00163   sNC.pSrcList = pTabList;
00164 
00165   /* Resolve the column names in all the expressions of the
00166   ** of the UPDATE statement.  Also find the column index
00167   ** for each column to be updated in the pChanges array.  For each
00168   ** column to be updated, make sure we have authorization to change
00169   ** that column.
00170   */
00171   chngRowid = 0;
00172   for(i=0; i<pChanges->nExpr; i++){
00173     if( sqlite3ExprResolveNames(&sNC, pChanges->a[i].pExpr) ){
00174       goto update_cleanup;
00175     }
00176     for(j=0; j<pTab->nCol; j++){
00177       if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
00178         if( j==pTab->iPKey ){
00179           chngRowid = 1;
00180           pRowidExpr = pChanges->a[i].pExpr;
00181         }
00182         aXRef[j] = i;
00183         break;
00184       }
00185     }
00186     if( j>=pTab->nCol ){
00187       if( sqlite3IsRowid(pChanges->a[i].zName) ){
00188         chngRowid = 1;
00189         pRowidExpr = pChanges->a[i].pExpr;
00190       }else{
00191         sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
00192         goto update_cleanup;
00193       }
00194     }
00195 #ifndef SQLITE_OMIT_AUTHORIZATION
00196     {
00197       int rc;
00198       rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
00199                            pTab->aCol[j].zName, db->aDb[iDb].zName);
00200       if( rc==SQLITE_DENY ){
00201         goto update_cleanup;
00202       }else if( rc==SQLITE_IGNORE ){
00203         aXRef[j] = -1;
00204       }
00205     }
00206 #endif
00207   }
00208 
00209   /* Allocate memory for the array apIdx[] and fill it with pointers to every
00210   ** index that needs to be updated.  Indices only need updating if their
00211   ** key includes one of the columns named in pChanges or if the record
00212   ** number of the original table entry is changing.
00213   */
00214   for(nIdx=nIdxTotal=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdxTotal++){
00215     if( chngRowid ){
00216       i = 0;
00217     }else {
00218       for(i=0; i<pIdx->nColumn; i++){
00219         if( aXRef[pIdx->aiColumn[i]]>=0 ) break;
00220       }
00221     }
00222     if( i<pIdx->nColumn ) nIdx++;
00223   }
00224   if( nIdxTotal>0 ){
00225     apIdx = sqliteMallocRaw( sizeof(Index*) * nIdx + nIdxTotal );
00226     if( apIdx==0 ) goto update_cleanup;
00227     aIdxUsed = (char*)&apIdx[nIdx];
00228   }
00229   for(nIdx=j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
00230     if( chngRowid ){
00231       i = 0;
00232     }else{
00233       for(i=0; i<pIdx->nColumn; i++){
00234         if( aXRef[pIdx->aiColumn[i]]>=0 ) break;
00235       }
00236     }
00237     if( i<pIdx->nColumn ){
00238       apIdx[nIdx++] = pIdx;
00239       aIdxUsed[j] = 1;
00240     }else{
00241       aIdxUsed[j] = 0;
00242     }
00243   }
00244 
00245   /* Resolve the column names in all the expressions in the
00246   ** WHERE clause.
00247   */
00248   if( sqlite3ExprResolveNames(&sNC, pWhere) ){
00249     goto update_cleanup;
00250   }
00251 
00252   /* Start the view context
00253   */
00254   if( isView ){
00255     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
00256   }
00257 
00258   /* Begin generating code.
00259   */
00260   v = sqlite3GetVdbe(pParse);
00261   if( v==0 ) goto update_cleanup;
00262   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
00263   sqlite3BeginWriteOperation(pParse, 1, iDb);
00264 
00265   /* If we are trying to update a view, realize that view into
00266   ** a ephemeral table.
00267   */
00268   if( isView ){
00269     Select *pView;
00270     pView = sqlite3SelectDup(pTab->pSelect);
00271     sqlite3Select(pParse, pView, SRT_VirtualTab, iCur, 0, 0, 0, 0);
00272     sqlite3SelectDelete(pView);
00273   }
00274 
00275   /* Begin the database scan
00276   */
00277   pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0);
00278   if( pWInfo==0 ) goto update_cleanup;
00279 
00280   /* Remember the index of every item to be updated.
00281   */
00282   sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
00283   sqlite3VdbeAddOp(v, OP_FifoWrite, 0, 0);
00284 
00285   /* End the database scan loop.
00286   */
00287   sqlite3WhereEnd(pWInfo);
00288 
00289   /* Initialize the count of updated rows
00290   */
00291   if( db->flags & SQLITE_CountRows && !pParse->trigStack ){
00292     sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
00293   }
00294 
00295   if( triggers_exist ){
00296     /* Create pseudo-tables for NEW and OLD
00297     */
00298     sqlite3VdbeAddOp(v, OP_OpenPseudo, oldIdx, 0);
00299     sqlite3VdbeAddOp(v, OP_SetNumColumns, oldIdx, pTab->nCol);
00300     sqlite3VdbeAddOp(v, OP_OpenPseudo, newIdx, 0);
00301     sqlite3VdbeAddOp(v, OP_SetNumColumns, newIdx, pTab->nCol);
00302 
00303     /* The top of the update loop for when there are triggers.
00304     */
00305     addr = sqlite3VdbeAddOp(v, OP_FifoRead, 0, 0);
00306 
00307     if( !isView ){
00308       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
00309       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
00310       /* Open a cursor and make it point to the record that is
00311       ** being updated.
00312       */
00313       sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
00314     }
00315     sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
00316 
00317     /* Generate the OLD table
00318     */
00319     sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
00320     sqlite3VdbeAddOp(v, OP_RowData, iCur, 0);
00321     sqlite3VdbeAddOp(v, OP_Insert, oldIdx, 0);
00322 
00323     /* Generate the NEW table
00324     */
00325     if( chngRowid ){
00326       sqlite3ExprCodeAndCache(pParse, pRowidExpr);
00327     }else{
00328       sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
00329     }
00330     for(i=0; i<pTab->nCol; i++){
00331       if( i==pTab->iPKey ){
00332         sqlite3VdbeAddOp(v, OP_Null, 0, 0);
00333         continue;
00334       }
00335       j = aXRef[i];
00336       if( j<0 ){
00337         sqlite3VdbeAddOp(v, OP_Column, iCur, i);
00338         sqlite3ColumnDefault(v, pTab, i);
00339       }else{
00340         sqlite3ExprCodeAndCache(pParse, pChanges->a[j].pExpr);
00341       }
00342     }
00343     sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
00344     if( !isView ){
00345       sqlite3TableAffinityStr(v, pTab);
00346     }
00347     if( pParse->nErr ) goto update_cleanup;
00348     sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0);
00349     if( !isView ){
00350       sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
00351     }
00352 
00353     /* Fire the BEFORE and INSTEAD OF triggers
00354     */
00355     if( sqlite3CodeRowTrigger(pParse, TK_UPDATE, pChanges, TRIGGER_BEFORE, pTab,
00356           newIdx, oldIdx, onError, addr) ){
00357       goto update_cleanup;
00358     }
00359   }
00360 
00361   if( !isView ){
00362     /* 
00363     ** Open every index that needs updating.  Note that if any
00364     ** index could potentially invoke a REPLACE conflict resolution 
00365     ** action, then we need to open all indices because we might need
00366     ** to be deleting some records.
00367     */
00368     sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite); 
00369     if( onError==OE_Replace ){
00370       openAll = 1;
00371     }else{
00372       openAll = 0;
00373       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
00374         if( pIdx->onError==OE_Replace ){
00375           openAll = 1;
00376           break;
00377         }
00378       }
00379     }
00380     for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
00381       if( openAll || aIdxUsed[i] ){
00382         KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
00383         sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
00384         sqlite3VdbeOp3(v, OP_OpenWrite, iCur+i+1, pIdx->tnum,
00385                        (char*)pKey, P3_KEYINFO_HANDOFF);
00386         assert( pParse->nTab>iCur+i+1 );
00387       }
00388     }
00389 
00390     /* Loop over every record that needs updating.  We have to load
00391     ** the old data for each record to be updated because some columns
00392     ** might not change and we will need to copy the old value.
00393     ** Also, the old data is needed to delete the old index entires.
00394     ** So make the cursor point at the old record.
00395     */
00396     if( !triggers_exist ){
00397       addr = sqlite3VdbeAddOp(v, OP_FifoRead, 0, 0);
00398       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
00399     }
00400     sqlite3VdbeAddOp(v, OP_NotExists, iCur, addr);
00401 
00402     /* If the record number will change, push the record number as it
00403     ** will be after the update. (The old record number is currently
00404     ** on top of the stack.)
00405     */
00406     if( chngRowid ){
00407       sqlite3ExprCode(pParse, pRowidExpr);
00408       sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
00409     }
00410 
00411     /* Compute new data for this record.  
00412     */
00413     for(i=0; i<pTab->nCol; i++){
00414       if( i==pTab->iPKey ){
00415         sqlite3VdbeAddOp(v, OP_Null, 0, 0);
00416         continue;
00417       }
00418       j = aXRef[i];
00419       if( j<0 ){
00420         sqlite3VdbeAddOp(v, OP_Column, iCur, i);
00421         sqlite3ColumnDefault(v, pTab, i);
00422       }else{
00423         sqlite3ExprCode(pParse, pChanges->a[j].pExpr);
00424       }
00425     }
00426 
00427     /* Do constraint checks
00428     */
00429     sqlite3GenerateConstraintChecks(pParse, pTab, iCur, aIdxUsed, chngRowid, 1,
00430                                    onError, addr);
00431 
00432     /* Delete the old indices for the current record.
00433     */
00434     sqlite3GenerateRowIndexDelete(v, pTab, iCur, aIdxUsed);
00435 
00436     /* If changing the record number, delete the old record.
00437     */
00438     if( chngRowid ){
00439       sqlite3VdbeAddOp(v, OP_Delete, iCur, 0);
00440     }
00441 
00442     /* Create the new index entries and the new record.
00443     */
00444     sqlite3CompleteInsertion(pParse, pTab, iCur, aIdxUsed, chngRowid, 1, -1);
00445   }
00446 
00447   /* Increment the row counter 
00448   */
00449   if( db->flags & SQLITE_CountRows && !pParse->trigStack){
00450     sqlite3VdbeAddOp(v, OP_AddImm, 1, 0);
00451   }
00452 
00453   /* If there are triggers, close all the cursors after each iteration
00454   ** through the loop.  The fire the after triggers.
00455   */
00456   if( triggers_exist ){
00457     if( !isView ){
00458       for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
00459         if( openAll || aIdxUsed[i] )
00460           sqlite3VdbeAddOp(v, OP_Close, iCur+i+1, 0);
00461       }
00462       sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
00463     }
00464     if( sqlite3CodeRowTrigger(pParse, TK_UPDATE, pChanges, TRIGGER_AFTER, pTab, 
00465           newIdx, oldIdx, onError, addr) ){
00466       goto update_cleanup;
00467     }
00468   }
00469 
00470   /* Repeat the above with the next record to be updated, until
00471   ** all record selected by the WHERE clause have been updated.
00472   */
00473   sqlite3VdbeAddOp(v, OP_Goto, 0, addr);
00474   sqlite3VdbeJumpHere(v, addr);
00475 
00476   /* Close all tables if there were no FOR EACH ROW triggers */
00477   if( !triggers_exist ){
00478     for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
00479       if( openAll || aIdxUsed[i] ){
00480         sqlite3VdbeAddOp(v, OP_Close, iCur+i+1, 0);
00481       }
00482     }
00483     sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
00484   }else{
00485     sqlite3VdbeAddOp(v, OP_Close, newIdx, 0);
00486     sqlite3VdbeAddOp(v, OP_Close, oldIdx, 0);
00487   }
00488 
00489   /*
00490   ** Return the number of rows that were changed. If this routine is 
00491   ** generating code because of a call to sqlite3NestedParse(), do not
00492   ** invoke the callback function.
00493   */
00494   if( db->flags & SQLITE_CountRows && !pParse->trigStack && pParse->nested==0 ){
00495     sqlite3VdbeAddOp(v, OP_Callback, 1, 0);
00496     sqlite3VdbeSetNumCols(v, 1);
00497     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", P3_STATIC);
00498   }
00499 
00500 update_cleanup:
00501   sqlite3AuthContextPop(&sContext);
00502   sqliteFree(apIdx);
00503   sqliteFree(aXRef);
00504   sqlite3SrcListDelete(pTabList);
00505   sqlite3ExprListDelete(pChanges);
00506   sqlite3ExprDelete(pWhere);
00507   return;
00508 }