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