xref: /sqlite-3.40.0/src/update.c (revision 7894b854)
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 #include "sqliteInt.h"
16 
17 #ifndef SQLITE_OMIT_VIRTUALTABLE
18 /* Forward declaration */
19 static void updateVirtualTable(
20   Parse *pParse,       /* The parsing context */
21   SrcList *pSrc,       /* The virtual table to be modified */
22   Table *pTab,         /* The virtual table */
23   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
24   Expr *pRowidExpr,    /* Expression used to recompute the rowid */
25   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
26   Expr *pWhere,        /* WHERE clause of the UPDATE statement */
27   int onError          /* ON CONFLICT strategy */
28 );
29 #endif /* SQLITE_OMIT_VIRTUALTABLE */
30 
31 /*
32 ** The most recently coded instruction was an OP_Column to retrieve the
33 ** i-th column of table pTab. This routine sets the P4 parameter of the
34 ** OP_Column to the default value, if any.
35 **
36 ** The default value of a column is specified by a DEFAULT clause in the
37 ** column definition. This was either supplied by the user when the table
38 ** was created, or added later to the table definition by an ALTER TABLE
39 ** command. If the latter, then the row-records in the table btree on disk
40 ** may not contain a value for the column and the default value, taken
41 ** from the P4 parameter of the OP_Column instruction, is returned instead.
42 ** If the former, then all row-records are guaranteed to include a value
43 ** for the column and the P4 value is not required.
44 **
45 ** Column definitions created by an ALTER TABLE command may only have
46 ** literal default values specified: a number, null or a string. (If a more
47 ** complicated default expression value was provided, it is evaluated
48 ** when the ALTER TABLE is executed and one of the literal values written
49 ** into the sqlite_master table.)
50 **
51 ** Therefore, the P4 parameter is only required if the default value for
52 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
53 ** function is capable of transforming these types of expressions into
54 ** sqlite3_value objects.
55 **
56 ** If parameter iReg is not negative, code an OP_RealAffinity instruction
57 ** on register iReg. This is used when an equivalent integer value is
58 ** stored in place of an 8-byte floating point value in order to save
59 ** space.
60 */
61 void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
62   assert( pTab!=0 );
63   if( !pTab->pSelect ){
64     sqlite3_value *pValue = 0;
65     u8 enc = ENC(sqlite3VdbeDb(v));
66     Column *pCol = &pTab->aCol[i];
67     VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
68     assert( i<pTab->nCol );
69     sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
70                          pCol->affinity, &pValue);
71     if( pValue ){
72       sqlite3VdbeAppendP4(v, pValue, P4_MEM);
73     }
74   }
75 #ifndef SQLITE_OMIT_FLOATING_POINT
76   if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
77     sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
78   }
79 #endif
80 }
81 
82 /*
83 ** Process an UPDATE statement.
84 **
85 **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
86 **          \_______/ \________/     \______/       \________________/
87 *            onError   pTabList      pChanges             pWhere
88 */
89 void sqlite3Update(
90   Parse *pParse,         /* The parser context */
91   SrcList *pTabList,     /* The table in which we should change things */
92   ExprList *pChanges,    /* Things to be changed */
93   Expr *pWhere,          /* The WHERE clause.  May be null */
94   int onError,           /* How to handle constraint errors */
95   ExprList *pOrderBy,    /* ORDER BY clause. May be null */
96   Expr *pLimit,          /* LIMIT clause. May be null */
97   Upsert *pUpsert        /* ON CONFLICT clause, or null */
98 ){
99   int i, j;              /* Loop counters */
100   Table *pTab;           /* The table to be updated */
101   int addrTop = 0;       /* VDBE instruction address of the start of the loop */
102   WhereInfo *pWInfo;     /* Information about the WHERE clause */
103   Vdbe *v;               /* The virtual database engine */
104   Index *pIdx;           /* For looping over indices */
105   Index *pPk;            /* The PRIMARY KEY index for WITHOUT ROWID tables */
106   int nIdx;              /* Number of indices that need updating */
107   int iBaseCur;          /* Base cursor number */
108   int iDataCur;          /* Cursor for the canonical data btree */
109   int iIdxCur;           /* Cursor for the first index */
110   sqlite3 *db;           /* The database structure */
111   int *aRegIdx = 0;      /* First register in array assigned to each index */
112   int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
113                          ** an expression for the i-th column of the table.
114                          ** aXRef[i]==-1 if the i-th column is not changed. */
115   u8 *aToOpen;           /* 1 for tables and indices to be opened */
116   u8 chngPk;             /* PRIMARY KEY changed in a WITHOUT ROWID table */
117   u8 chngRowid;          /* Rowid changed in a normal table */
118   u8 chngKey;            /* Either chngPk or chngRowid */
119   Expr *pRowidExpr = 0;  /* Expression defining the new record number */
120   AuthContext sContext;  /* The authorization context */
121   NameContext sNC;       /* The name-context to resolve expressions in */
122   int iDb;               /* Database containing the table being updated */
123   int eOnePass;          /* ONEPASS_XXX value from where.c */
124   int hasFK;             /* True if foreign key processing is required */
125   int labelBreak;        /* Jump here to break out of UPDATE loop */
126   int labelContinue;     /* Jump here to continue next step of UPDATE loop */
127   int flags;             /* Flags for sqlite3WhereBegin() */
128 
129 #ifndef SQLITE_OMIT_TRIGGER
130   int isView;            /* True when updating a view (INSTEAD OF trigger) */
131   Trigger *pTrigger;     /* List of triggers on pTab, if required */
132   int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
133 #endif
134   int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
135   int iEph = 0;          /* Ephemeral table holding all primary key values */
136   int nKey = 0;          /* Number of elements in regKey for WITHOUT ROWID */
137   int aiCurOnePass[2];   /* The write cursors opened by WHERE_ONEPASS */
138   int addrOpen = 0;      /* Address of OP_OpenEphemeral */
139   int iPk = 0;           /* First of nPk cells holding PRIMARY KEY value */
140   i16 nPk = 0;           /* Number of components of the PRIMARY KEY */
141   int bReplace = 0;      /* True if REPLACE conflict resolution might happen */
142 
143   /* Register Allocations */
144   int regRowCount = 0;   /* A count of rows changed */
145   int regOldRowid = 0;   /* The old rowid */
146   int regNewRowid = 0;   /* The new rowid */
147   int regNew = 0;        /* Content of the NEW.* table in triggers */
148   int regOld = 0;        /* Content of OLD.* table in triggers */
149   int regRowSet = 0;     /* Rowset of rows to be updated */
150   int regKey = 0;        /* composite PRIMARY KEY value */
151 
152   memset(&sContext, 0, sizeof(sContext));
153   db = pParse->db;
154   if( pParse->nErr || db->mallocFailed ){
155     goto update_cleanup;
156   }
157   assert( pTabList->nSrc==1 );
158 
159   /* Locate the table which we want to update.
160   */
161   pTab = sqlite3SrcListLookup(pParse, pTabList);
162   if( pTab==0 ) goto update_cleanup;
163   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
164 
165   /* Figure out if we have any triggers and if the table being
166   ** updated is a view.
167   */
168 #ifndef SQLITE_OMIT_TRIGGER
169   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
170   isView = pTab->pSelect!=0;
171   assert( pTrigger || tmask==0 );
172 #else
173 # define pTrigger 0
174 # define isView 0
175 # define tmask 0
176 #endif
177 #ifdef SQLITE_OMIT_VIEW
178 # undef isView
179 # define isView 0
180 #endif
181 
182 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
183   if( !isView ){
184     pWhere = sqlite3LimitWhere(
185         pParse, pTabList, pWhere, pOrderBy, pLimit, "UPDATE"
186     );
187     pOrderBy = 0;
188     pLimit = 0;
189   }
190 #endif
191 
192   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
193     goto update_cleanup;
194   }
195   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
196     goto update_cleanup;
197   }
198 
199   /* Allocate a cursors for the main database table and for all indices.
200   ** The index cursors might not be used, but if they are used they
201   ** need to occur right after the database cursor.  So go ahead and
202   ** allocate enough space, just in case.
203   */
204   iBaseCur = iDataCur = pParse->nTab++;
205   iIdxCur = iDataCur+1;
206   pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
207   testcase( pPk!=0 && pPk!=pTab->pIndex );
208   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
209     if( pPk==pIdx ){
210       iDataCur = pParse->nTab;
211     }
212     pParse->nTab++;
213   }
214   if( pUpsert ){
215     /* On an UPSERT, reuse the same cursors already opened by INSERT */
216     iDataCur = pUpsert->iDataCur;
217     iIdxCur = pUpsert->iIdxCur;
218     pParse->nTab = iBaseCur;
219   }
220   pTabList->a[0].iCursor = iDataCur;
221 
222   /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].
223   ** Initialize aXRef[] and aToOpen[] to their default values.
224   */
225   aXRef = sqlite3DbMallocRawNN(db, sizeof(int) * (pTab->nCol+nIdx) + nIdx+2 );
226   if( aXRef==0 ) goto update_cleanup;
227   aRegIdx = aXRef+pTab->nCol;
228   aToOpen = (u8*)(aRegIdx+nIdx);
229   memset(aToOpen, 1, nIdx+1);
230   aToOpen[nIdx+1] = 0;
231   for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
232 
233   /* Initialize the name-context */
234   memset(&sNC, 0, sizeof(sNC));
235   sNC.pParse = pParse;
236   sNC.pSrcList = pTabList;
237   sNC.uNC.pUpsert = pUpsert;
238   sNC.ncFlags = NC_UUpsert;
239 
240   /* Resolve the column names in all the expressions of the
241   ** of the UPDATE statement.  Also find the column index
242   ** for each column to be updated in the pChanges array.  For each
243   ** column to be updated, make sure we have authorization to change
244   ** that column.
245   */
246   chngRowid = chngPk = 0;
247   for(i=0; i<pChanges->nExpr; i++){
248     if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
249       goto update_cleanup;
250     }
251     for(j=0; j<pTab->nCol; j++){
252       if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
253         if( j==pTab->iPKey ){
254           chngRowid = 1;
255           pRowidExpr = pChanges->a[i].pExpr;
256         }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
257           chngPk = 1;
258         }
259         aXRef[j] = i;
260         break;
261       }
262     }
263     if( j>=pTab->nCol ){
264       if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){
265         j = -1;
266         chngRowid = 1;
267         pRowidExpr = pChanges->a[i].pExpr;
268       }else{
269         sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
270         pParse->checkSchema = 1;
271         goto update_cleanup;
272       }
273     }
274 #ifndef SQLITE_OMIT_AUTHORIZATION
275     {
276       int rc;
277       rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
278                             j<0 ? "ROWID" : pTab->aCol[j].zName,
279                             db->aDb[iDb].zDbSName);
280       if( rc==SQLITE_DENY ){
281         goto update_cleanup;
282       }else if( rc==SQLITE_IGNORE ){
283         aXRef[j] = -1;
284       }
285     }
286 #endif
287   }
288   assert( (chngRowid & chngPk)==0 );
289   assert( chngRowid==0 || chngRowid==1 );
290   assert( chngPk==0 || chngPk==1 );
291   chngKey = chngRowid + chngPk;
292 
293   /* The SET expressions are not actually used inside the WHERE loop.
294   ** So reset the colUsed mask. Unless this is a virtual table. In that
295   ** case, set all bits of the colUsed mask (to ensure that the virtual
296   ** table implementation makes all columns available).
297   */
298   pTabList->a[0].colUsed = IsVirtual(pTab) ? ALLBITS : 0;
299 
300   hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
301 
302   /* There is one entry in the aRegIdx[] array for each index on the table
303   ** being updated.  Fill in aRegIdx[] with a register number that will hold
304   ** the key for accessing each index.
305   **
306   ** FIXME:  Be smarter about omitting indexes that use expressions.
307   */
308   for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
309     int reg;
310     if( chngKey || hasFK>1 || pIdx->pPartIdxWhere || pIdx==pPk ){
311       reg = ++pParse->nMem;
312       pParse->nMem += pIdx->nColumn;
313     }else{
314       reg = 0;
315       for(i=0; i<pIdx->nKeyCol; i++){
316         i16 iIdxCol = pIdx->aiColumn[i];
317         if( iIdxCol<0 || aXRef[iIdxCol]>=0 ){
318           reg = ++pParse->nMem;
319           pParse->nMem += pIdx->nColumn;
320           if( (onError==OE_Replace)
321            || (onError==OE_Default && pIdx->onError==OE_Replace)
322           ){
323             bReplace = 1;
324           }
325           break;
326         }
327       }
328     }
329     if( reg==0 ) aToOpen[j+1] = 0;
330     aRegIdx[j] = reg;
331   }
332   if( bReplace ){
333     /* If REPLACE conflict resolution might be invoked, open cursors on all
334     ** indexes in case they are needed to delete records.  */
335     memset(aToOpen, 1, nIdx+1);
336   }
337 
338   /* Begin generating code. */
339   v = sqlite3GetVdbe(pParse);
340   if( v==0 ) goto update_cleanup;
341   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
342   sqlite3BeginWriteOperation(pParse, pTrigger || hasFK, iDb);
343 
344   /* Allocate required registers. */
345   if( !IsVirtual(pTab) ){
346     regRowSet = ++pParse->nMem;
347     regOldRowid = regNewRowid = ++pParse->nMem;
348     if( chngPk || pTrigger || hasFK ){
349       regOld = pParse->nMem + 1;
350       pParse->nMem += pTab->nCol;
351     }
352     if( chngKey || pTrigger || hasFK ){
353       regNewRowid = ++pParse->nMem;
354     }
355     regNew = pParse->nMem + 1;
356     pParse->nMem += pTab->nCol;
357   }
358 
359   /* Start the view context. */
360   if( isView ){
361     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
362   }
363 
364   /* If we are trying to update a view, realize that view into
365   ** an ephemeral table.
366   */
367 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
368   if( isView ){
369     sqlite3MaterializeView(pParse, pTab,
370         pWhere, pOrderBy, pLimit, iDataCur
371     );
372     pOrderBy = 0;
373     pLimit = 0;
374   }
375 #endif
376 
377   /* Resolve the column names in all the expressions in the
378   ** WHERE clause.
379   */
380   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
381     goto update_cleanup;
382   }
383 
384 #ifndef SQLITE_OMIT_VIRTUALTABLE
385   /* Virtual tables must be handled separately */
386   if( IsVirtual(pTab) ){
387     updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
388                        pWhere, onError);
389     goto update_cleanup;
390   }
391 #endif
392 
393   /* Jump to labelBreak to abandon further processing of this UPDATE */
394   labelContinue = labelBreak = sqlite3VdbeMakeLabel(v);
395 
396   /* Not an UPSERT.  Normal processing.  Begin by
397   ** initialize the count of updated rows */
398   if( (db->flags&SQLITE_CountRows)!=0
399    && !pParse->pTriggerTab
400    && !pParse->nested
401    && pUpsert==0
402   ){
403     regRowCount = ++pParse->nMem;
404     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
405   }
406 
407   if( HasRowid(pTab) ){
408     sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
409   }else{
410     assert( pPk!=0 );
411     nPk = pPk->nKeyCol;
412     iPk = pParse->nMem+1;
413     pParse->nMem += nPk;
414     regKey = ++pParse->nMem;
415     if( pUpsert==0 ){
416       iEph = pParse->nTab++;
417         sqlite3VdbeAddOp3(v, OP_Null, 0, iPk, iPk+nPk-1);
418       addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk);
419       sqlite3VdbeSetP4KeyInfo(pParse, pPk);
420     }
421   }
422 
423   if( pUpsert ){
424     /* If this is an UPSERT, then all cursors have already been opened by
425     ** the outer INSERT and the data cursor should be pointing at the row
426     ** that is to be updated.  So bypass the code that searches for the
427     ** row(s) to be updated.
428     */
429     pWInfo = 0;
430     eOnePass = ONEPASS_SINGLE;
431     sqlite3ExprIfFalse(pParse, pWhere, labelBreak, SQLITE_JUMPIFNULL);
432   }else{
433     /* Begin the database scan.
434     **
435     ** Do not consider a single-pass strategy for a multi-row update if
436     ** there are any triggers or foreign keys to process, or rows may
437     ** be deleted as a result of REPLACE conflict handling. Any of these
438     ** things might disturb a cursor being used to scan through the table
439     ** or index, causing a single-pass approach to malfunction.  */
440     flags = WHERE_ONEPASS_DESIRED|WHERE_SEEK_UNIQ_TABLE;
441     if( !pParse->nested && !pTrigger && !hasFK && !chngKey && !bReplace ){
442       flags |= WHERE_ONEPASS_MULTIROW;
443     }
444     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, flags, iIdxCur);
445     if( pWInfo==0 ) goto update_cleanup;
446 
447     /* A one-pass strategy that might update more than one row may not
448     ** be used if any column of the index used for the scan is being
449     ** updated. Otherwise, if there is an index on "b", statements like
450     ** the following could create an infinite loop:
451     **
452     **   UPDATE t1 SET b=b+1 WHERE b>?
453     **
454     ** Fall back to ONEPASS_OFF if where.c has selected a ONEPASS_MULTI
455     ** strategy that uses an index for which one or more columns are being
456     ** updated.  */
457     eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
458     if( eOnePass!=ONEPASS_SINGLE ){
459       sqlite3MultiWrite(pParse);
460       if( eOnePass==ONEPASS_MULTI ){
461         int iCur = aiCurOnePass[1];
462         if( iCur>=0 && iCur!=iDataCur && aToOpen[iCur-iBaseCur] ){
463           eOnePass = ONEPASS_OFF;
464         }
465         assert( iCur!=iDataCur || !HasRowid(pTab) );
466       }
467     }
468   }
469 
470   if( HasRowid(pTab) ){
471     /* Read the rowid of the current row of the WHERE scan. In ONEPASS_OFF
472     ** mode, write the rowid into the FIFO. In either of the one-pass modes,
473     ** leave it in register regOldRowid.  */
474     sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
475     if( eOnePass==ONEPASS_OFF ){
476       sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
477     }
478   }else{
479     /* Read the PK of the current row into an array of registers. In
480     ** ONEPASS_OFF mode, serialize the array into a record and store it in
481     ** the ephemeral table. Or, in ONEPASS_SINGLE or MULTI mode, change
482     ** the OP_OpenEphemeral instruction to a Noop (the ephemeral table
483     ** is not required) and leave the PK fields in the array of registers.  */
484     for(i=0; i<nPk; i++){
485       assert( pPk->aiColumn[i]>=0 );
486       sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur,pPk->aiColumn[i],iPk+i);
487     }
488     if( eOnePass ){
489       if( addrOpen ) sqlite3VdbeChangeToNoop(v, addrOpen);
490       nKey = nPk;
491       regKey = iPk;
492     }else{
493       sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
494                         sqlite3IndexAffinityStr(db, pPk), nPk);
495       sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEph, regKey, iPk, nPk);
496     }
497   }
498 
499   if( pUpsert==0 ){
500     if( eOnePass!=ONEPASS_MULTI ){
501       sqlite3WhereEnd(pWInfo);
502     }
503 
504     if( !isView ){
505       int addrOnce = 0;
506 
507       /* Open every index that needs updating. */
508       if( eOnePass!=ONEPASS_OFF ){
509         if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
510         if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
511       }
512 
513       if( eOnePass==ONEPASS_MULTI && (nIdx-(aiCurOnePass[1]>=0))>0 ){
514         addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
515       }
516       sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, iBaseCur,
517                                  aToOpen, 0, 0);
518       if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
519     }
520 
521     /* Top of the update loop */
522     if( eOnePass!=ONEPASS_OFF ){
523       if( !isView && aiCurOnePass[0]!=iDataCur && aiCurOnePass[1]!=iDataCur ){
524         assert( pPk );
525         sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey,nKey);
526         VdbeCoverage(v);
527       }
528       if( eOnePass!=ONEPASS_SINGLE ){
529         labelContinue = sqlite3VdbeMakeLabel(v);
530       }
531       sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
532       VdbeCoverageIf(v, pPk==0);
533       VdbeCoverageIf(v, pPk!=0);
534     }else if( pPk ){
535       labelContinue = sqlite3VdbeMakeLabel(v);
536       sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
537       addrTop = sqlite3VdbeAddOp2(v, OP_RowData, iEph, regKey);
538       sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0);
539       VdbeCoverage(v);
540     }else{
541       labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet,labelBreak,
542                                regOldRowid);
543       VdbeCoverage(v);
544       sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
545       VdbeCoverage(v);
546     }
547   }
548 
549   /* If the rowid value will change, set register regNewRowid to
550   ** contain the new value. If the rowid is not being modified,
551   ** then regNewRowid is the same register as regOldRowid, which is
552   ** already populated.  */
553   assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
554   if( chngRowid ){
555     sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
556     sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
557   }
558 
559   /* Compute the old pre-UPDATE content of the row being changed, if that
560   ** information is needed */
561   if( chngPk || hasFK || pTrigger ){
562     u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
563     oldmask |= sqlite3TriggerColmask(pParse,
564         pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
565     );
566     for(i=0; i<pTab->nCol; i++){
567       if( oldmask==0xffffffff
568        || (i<32 && (oldmask & MASKBIT32(i))!=0)
569        || (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
570       ){
571         testcase(  oldmask!=0xffffffff && i==31 );
572         sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i);
573       }else{
574         sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
575       }
576     }
577     if( chngRowid==0 && pPk==0 ){
578       sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
579     }
580   }
581 
582   /* Populate the array of registers beginning at regNew with the new
583   ** row data. This array is used to check constants, create the new
584   ** table and index records, and as the values for any new.* references
585   ** made by triggers.
586   **
587   ** If there are one or more BEFORE triggers, then do not populate the
588   ** registers associated with columns that are (a) not modified by
589   ** this UPDATE statement and (b) not accessed by new.* references. The
590   ** values for registers not modified by the UPDATE must be reloaded from
591   ** the database after the BEFORE triggers are fired anyway (as the trigger
592   ** may have modified them). So not loading those that are not going to
593   ** be used eliminates some redundant opcodes.
594   */
595   newmask = sqlite3TriggerColmask(
596       pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
597   );
598   for(i=0; i<pTab->nCol; i++){
599     if( i==pTab->iPKey ){
600       sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
601     }else{
602       j = aXRef[i];
603       if( j>=0 ){
604         sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
605       }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
606         /* This branch loads the value of a column that will not be changed
607         ** into a register. This is done if there are no BEFORE triggers, or
608         ** if there are one or more BEFORE triggers that use this value via
609         ** a new.* reference in a trigger program.
610         */
611         testcase( i==31 );
612         testcase( i==32 );
613         sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
614       }else{
615         sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
616       }
617     }
618   }
619 
620   /* Fire any BEFORE UPDATE triggers. This happens before constraints are
621   ** verified. One could argue that this is wrong.
622   */
623   if( tmask&TRIGGER_BEFORE ){
624     sqlite3TableAffinity(v, pTab, regNew);
625     sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
626         TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
627 
628     /* The row-trigger may have deleted the row being updated. In this
629     ** case, jump to the next row. No updates or AFTER triggers are
630     ** required. This behavior - what happens when the row being updated
631     ** is deleted or renamed by a BEFORE trigger - is left undefined in the
632     ** documentation.
633     */
634     if( pPk ){
635       sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey);
636       VdbeCoverage(v);
637     }else{
638       sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
639       VdbeCoverage(v);
640     }
641 
642     /* After-BEFORE-trigger-reload-loop:
643     ** If it did not delete it, the BEFORE trigger may still have modified
644     ** some of the columns of the row being updated. Load the values for
645     ** all columns not modified by the update statement into their registers
646     ** in case this has happened. Only unmodified columns are reloaded.
647     ** The values computed for modified columns use the values before the
648     ** BEFORE trigger runs.  See test case trigger1-18.0 (added 2018-04-26)
649     ** for an example.
650     */
651     for(i=0; i<pTab->nCol; i++){
652       if( aXRef[i]<0 && i!=pTab->iPKey ){
653         sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
654       }
655     }
656   }
657 
658   if( !isView ){
659     int addr1 = 0;        /* Address of jump instruction */
660 
661     /* Do constraint checks. */
662     assert( regOldRowid>0 );
663     sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
664         regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace,
665         aXRef, 0);
666 
667     /* Do FK constraint checks. */
668     if( hasFK ){
669       sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);
670     }
671 
672     /* Delete the index entries associated with the current record.  */
673     if( bReplace || chngKey ){
674       if( pPk ){
675         addr1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey);
676       }else{
677         addr1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid);
678       }
679       VdbeCoverageNeverTaken(v);
680     }
681     sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx, -1);
682 
683     /* If changing the rowid value, or if there are foreign key constraints
684     ** to process, delete the old record. Otherwise, add a noop OP_Delete
685     ** to invoke the pre-update hook.
686     **
687     ** That (regNew==regnewRowid+1) is true is also important for the
688     ** pre-update hook. If the caller invokes preupdate_new(), the returned
689     ** value is copied from memory cell (regNewRowid+1+iCol), where iCol
690     ** is the column index supplied by the user.
691     */
692     assert( regNew==regNewRowid+1 );
693 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
694     sqlite3VdbeAddOp3(v, OP_Delete, iDataCur,
695         OPFLAG_ISUPDATE | ((hasFK>1 || chngKey) ? 0 : OPFLAG_ISNOOP),
696         regNewRowid
697     );
698     if( eOnePass==ONEPASS_MULTI ){
699       assert( hasFK==0 && chngKey==0 );
700       sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
701     }
702     if( !pParse->nested ){
703       sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
704     }
705 #else
706     if( hasFK>1 || chngKey ){
707       sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
708     }
709 #endif
710     if( bReplace || chngKey ){
711       sqlite3VdbeJumpHere(v, addr1);
712     }
713 
714     if( hasFK ){
715       sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
716     }
717 
718     /* Insert the new index entries and the new record. */
719     sqlite3CompleteInsertion(
720         pParse, pTab, iDataCur, iIdxCur, regNewRowid, aRegIdx,
721         OPFLAG_ISUPDATE | (eOnePass==ONEPASS_MULTI ? OPFLAG_SAVEPOSITION : 0),
722         0, 0
723     );
724 
725     /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
726     ** handle rows (possibly in other tables) that refer via a foreign key
727     ** to the row just updated. */
728     if( hasFK ){
729       sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
730     }
731   }
732 
733   /* Increment the row counter
734   */
735   if( regRowCount ){
736     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
737   }
738 
739   sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
740       TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
741 
742   /* Repeat the above with the next record to be updated, until
743   ** all record selected by the WHERE clause have been updated.
744   */
745   if( eOnePass==ONEPASS_SINGLE ){
746     /* Nothing to do at end-of-loop for a single-pass */
747   }else if( eOnePass==ONEPASS_MULTI ){
748     sqlite3VdbeResolveLabel(v, labelContinue);
749     sqlite3WhereEnd(pWInfo);
750   }else if( pPk ){
751     sqlite3VdbeResolveLabel(v, labelContinue);
752     sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
753   }else{
754     sqlite3VdbeGoto(v, labelContinue);
755   }
756   sqlite3VdbeResolveLabel(v, labelBreak);
757 
758   /* Update the sqlite_sequence table by storing the content of the
759   ** maximum rowid counter values recorded while inserting into
760   ** autoincrement tables.
761   */
762   if( pParse->nested==0 && pParse->pTriggerTab==0 && pUpsert==0 ){
763     sqlite3AutoincrementEnd(pParse);
764   }
765 
766   /*
767   ** Return the number of rows that were changed, if we are tracking
768   ** that information.
769   */
770   if( regRowCount ){
771     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
772     sqlite3VdbeSetNumCols(v, 1);
773     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
774   }
775 
776 update_cleanup:
777   sqlite3AuthContextPop(&sContext);
778   sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */
779   sqlite3SrcListDelete(db, pTabList);
780   sqlite3ExprListDelete(db, pChanges);
781   sqlite3ExprDelete(db, pWhere);
782 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
783   sqlite3ExprListDelete(db, pOrderBy);
784   sqlite3ExprDelete(db, pLimit);
785 #endif
786   return;
787 }
788 /* Make sure "isView" and other macros defined above are undefined. Otherwise
789 ** they may interfere with compilation of other functions in this file
790 ** (or in another file, if this file becomes part of the amalgamation).  */
791 #ifdef isView
792  #undef isView
793 #endif
794 #ifdef pTrigger
795  #undef pTrigger
796 #endif
797 
798 #ifndef SQLITE_OMIT_VIRTUALTABLE
799 /*
800 ** Generate code for an UPDATE of a virtual table.
801 **
802 ** There are two possible strategies - the default and the special
803 ** "onepass" strategy. Onepass is only used if the virtual table
804 ** implementation indicates that pWhere may match at most one row.
805 **
806 ** The default strategy is to create an ephemeral table that contains
807 ** for each row to be changed:
808 **
809 **   (A)  The original rowid of that row.
810 **   (B)  The revised rowid for the row.
811 **   (C)  The content of every column in the row.
812 **
813 ** Then loop through the contents of this ephemeral table executing a
814 ** VUpdate for each row. When finished, drop the ephemeral table.
815 **
816 ** The "onepass" strategy does not use an ephemeral table. Instead, it
817 ** stores the same values (A, B and C above) in a register array and
818 ** makes a single invocation of VUpdate.
819 */
820 static void updateVirtualTable(
821   Parse *pParse,       /* The parsing context */
822   SrcList *pSrc,       /* The virtual table to be modified */
823   Table *pTab,         /* The virtual table */
824   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
825   Expr *pRowid,        /* Expression used to recompute the rowid */
826   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
827   Expr *pWhere,        /* WHERE clause of the UPDATE statement */
828   int onError          /* ON CONFLICT strategy */
829 ){
830   Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
831   int ephemTab;             /* Table holding the result of the SELECT */
832   int i;                    /* Loop counter */
833   sqlite3 *db = pParse->db; /* Database connection */
834   const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
835   WhereInfo *pWInfo;
836   int nArg = 2 + pTab->nCol;      /* Number of arguments to VUpdate */
837   int regArg;                     /* First register in VUpdate arg array */
838   int regRec;                     /* Register in which to assemble record */
839   int regRowid;                   /* Register for ephem table rowid */
840   int iCsr = pSrc->a[0].iCursor;  /* Cursor used for virtual table scan */
841   int aDummy[2];                  /* Unused arg for sqlite3WhereOkOnePass() */
842   int eOnePass;                   /* True to use onepass strategy */
843   int addr;                       /* Address of OP_OpenEphemeral */
844 
845   /* Allocate nArg registers in which to gather the arguments for VUpdate. Then
846   ** create and open the ephemeral table in which the records created from
847   ** these arguments will be temporarily stored. */
848   assert( v );
849   ephemTab = pParse->nTab++;
850   addr= sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, nArg);
851   regArg = pParse->nMem + 1;
852   pParse->nMem += nArg;
853   regRec = ++pParse->nMem;
854   regRowid = ++pParse->nMem;
855 
856   /* Start scanning the virtual table */
857   pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0,0,WHERE_ONEPASS_DESIRED,0);
858   if( pWInfo==0 ) return;
859 
860   /* Populate the argument registers. */
861   for(i=0; i<pTab->nCol; i++){
862     if( aXRef[i]>=0 ){
863       sqlite3ExprCode(pParse, pChanges->a[aXRef[i]].pExpr, regArg+2+i);
864     }else{
865       sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, i, regArg+2+i);
866       sqlite3VdbeChangeP5(v, 1); /* Enable sqlite3_vtab_nochange() */
867     }
868   }
869   if( HasRowid(pTab) ){
870     sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg);
871     if( pRowid ){
872       sqlite3ExprCode(pParse, pRowid, regArg+1);
873     }else{
874       sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg+1);
875     }
876   }else{
877     Index *pPk;   /* PRIMARY KEY index */
878     i16 iPk;      /* PRIMARY KEY column */
879     pPk = sqlite3PrimaryKeyIndex(pTab);
880     assert( pPk!=0 );
881     assert( pPk->nKeyCol==1 );
882     iPk = pPk->aiColumn[0];
883     sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, iPk, regArg);
884     sqlite3VdbeAddOp2(v, OP_SCopy, regArg+2+iPk, regArg+1);
885   }
886 
887   eOnePass = sqlite3WhereOkOnePass(pWInfo, aDummy);
888 
889   /* There is no ONEPASS_MULTI on virtual tables */
890   assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );
891 
892   if( eOnePass ){
893     /* If using the onepass strategy, no-op out the OP_OpenEphemeral coded
894     ** above. */
895     sqlite3VdbeChangeToNoop(v, addr);
896     sqlite3VdbeAddOp1(v, OP_Close, iCsr);
897   }else{
898     /* Create a record from the argument register contents and insert it into
899     ** the ephemeral table. */
900     sqlite3MultiWrite(pParse);
901     sqlite3VdbeAddOp3(v, OP_MakeRecord, regArg, nArg, regRec);
902 #ifdef SQLITE_DEBUG
903     /* Signal an assert() within OP_MakeRecord that it is allowed to
904     ** accept no-change records with serial_type 10 */
905     sqlite3VdbeChangeP5(v, OPFLAG_NOCHNG_MAGIC);
906 #endif
907     sqlite3VdbeAddOp2(v, OP_NewRowid, ephemTab, regRowid);
908     sqlite3VdbeAddOp3(v, OP_Insert, ephemTab, regRec, regRowid);
909   }
910 
911 
912   if( eOnePass==ONEPASS_OFF ){
913     /* End the virtual table scan */
914     sqlite3WhereEnd(pWInfo);
915 
916     /* Begin scannning through the ephemeral table. */
917     addr = sqlite3VdbeAddOp1(v, OP_Rewind, ephemTab); VdbeCoverage(v);
918 
919     /* Extract arguments from the current row of the ephemeral table and
920     ** invoke the VUpdate method.  */
921     for(i=0; i<nArg; i++){
922       sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i, regArg+i);
923     }
924   }
925   sqlite3VtabMakeWritable(pParse, pTab);
926   sqlite3VdbeAddOp4(v, OP_VUpdate, 0, nArg, regArg, pVTab, P4_VTAB);
927   sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
928   sqlite3MayAbort(pParse);
929 
930   /* End of the ephemeral table scan. Or, if using the onepass strategy,
931   ** jump to here if the scan visited zero rows. */
932   if( eOnePass==ONEPASS_OFF ){
933     sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
934     sqlite3VdbeJumpHere(v, addr);
935     sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
936   }else{
937     sqlite3WhereEnd(pWInfo);
938   }
939 }
940 #endif /* SQLITE_OMIT_VIRTUALTABLE */
941