update.c
上传用户:sunhongbo
上传日期:2022-01-25
资源大小:3010k
文件大小:23k
源码类别:

数据库系统

开发平台:

C/C++

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