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