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