xref: /sqlite-3.40.0/src/update.c (revision 17adf4e5)
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_schema 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 column as REAL affinity and the table is an ordinary b-tree table
57 ** (not a virtual table) then the value might have been stored as an
58 ** integer.  In that case, add an OP_RealAffinity opcode to make sure
59 ** it has been converted into REAL.
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 && !IsVirtual(pTab) ){
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 ** Allocate and return a pointer to an expression of type TK_ROW with
135 ** Expr.iColumn set to value (iCol+1). The resolver will modify the
136 ** expression to be a TK_COLUMN reading column iCol of the first
137 ** table in the source-list (pSrc->a[0]).
138 */
139 static Expr *exprRowColumn(Parse *pParse, int iCol){
140   Expr *pRet = sqlite3PExpr(pParse, TK_ROW, 0, 0);
141   if( pRet ) pRet->iColumn = iCol+1;
142   return pRet;
143 }
144 
145 /*
146 ** Assuming both the pLimit and pOrderBy parameters are NULL, this function
147 ** generates VM code to run the query:
148 **
149 **   SELECT <other-columns>, pChanges FROM pTabList WHERE pWhere
150 **
151 ** and write the results to the ephemeral table already opened as cursor
152 ** iEph. None of pChanges, pTabList or pWhere are modified or consumed by
153 ** this function, they must be deleted by the caller.
154 **
155 ** Or, if pLimit and pOrderBy are not NULL, and pTab is not a view:
156 **
157 **   SELECT <other-columns>, pChanges FROM pTabList
158 **   WHERE pWhere
159 **   GROUP BY <other-columns>
160 **   ORDER BY pOrderBy LIMIT pLimit
161 **
162 ** If pTab is a view, the GROUP BY clause is omitted.
163 **
164 ** Exactly how results are written to table iEph, and exactly what
165 ** the <other-columns> in the query above are is determined by the type
166 ** of table pTabList->a[0].pTab.
167 **
168 ** If the table is a WITHOUT ROWID table, then argument pPk must be its
169 ** PRIMARY KEY. In this case <other-columns> are the primary key columns
170 ** of the table, in order. The results of the query are written to ephemeral
171 ** table iEph as index keys, using OP_IdxInsert.
172 **
173 ** If the table is actually a view, then <other-columns> are all columns of
174 ** the view. The results are written to the ephemeral table iEph as records
175 ** with automatically assigned integer keys.
176 **
177 ** If the table is a virtual or ordinary intkey table, then <other-columns>
178 ** is its rowid. For a virtual table, the results are written to iEph as
179 ** records with automatically assigned integer keys For intkey tables, the
180 ** rowid value in <other-columns> is used as the integer key, and the
181 ** remaining fields make up the table record.
182 */
183 static void updateFromSelect(
184   Parse *pParse,                  /* Parse context */
185   int iEph,                       /* Cursor for open eph. table */
186   Index *pPk,                     /* PK if table 0 is WITHOUT ROWID */
187   ExprList *pChanges,             /* List of expressions to return */
188   SrcList *pTabList,              /* List of tables to select from */
189   Expr *pWhere,                   /* WHERE clause for query */
190   ExprList *pOrderBy,             /* ORDER BY clause */
191   Expr *pLimit                    /* LIMIT clause */
192 ){
193   int i;
194   SelectDest dest;
195   Select *pSelect = 0;
196   ExprList *pList = 0;
197   ExprList *pGrp = 0;
198   Expr *pLimit2 = 0;
199   ExprList *pOrderBy2 = 0;
200   sqlite3 *db = pParse->db;
201   Table *pTab = pTabList->a[0].pTab;
202   SrcList *pSrc;
203   Expr *pWhere2;
204   int eDest;
205 
206 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
207   if( pOrderBy && pLimit==0 ) {
208     sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on UPDATE");
209     return;
210   }
211   pOrderBy2 = sqlite3ExprListDup(db, pOrderBy, 0);
212   pLimit2 = sqlite3ExprDup(db, pLimit, 0);
213 #else
214   UNUSED_PARAMETER(pOrderBy);
215   UNUSED_PARAMETER(pLimit);
216 #endif
217 
218   pSrc = sqlite3SrcListDup(db, pTabList, 0);
219   pWhere2 = sqlite3ExprDup(db, pWhere, 0);
220 
221   assert( pTabList->nSrc>1 );
222   if( pSrc ){
223     pSrc->a[0].fg.notCte = 1;
224     pSrc->a[0].iCursor = -1;
225     pSrc->a[0].pTab->nTabRef--;
226     pSrc->a[0].pTab = 0;
227   }
228   if( pPk ){
229     for(i=0; i<pPk->nKeyCol; i++){
230       Expr *pNew = exprRowColumn(pParse, pPk->aiColumn[i]);
231 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
232       if( pLimit ){
233         pGrp = sqlite3ExprListAppend(pParse, pGrp, sqlite3ExprDup(db, pNew, 0));
234       }
235 #endif
236       pList = sqlite3ExprListAppend(pParse, pList, pNew);
237     }
238     eDest = IsVirtual(pTab) ? SRT_Table : SRT_Upfrom;
239   }else if( pTab->pSelect ){
240     for(i=0; i<pTab->nCol; i++){
241       pList = sqlite3ExprListAppend(pParse, pList, exprRowColumn(pParse, i));
242     }
243     eDest = SRT_Table;
244   }else{
245     eDest = IsVirtual(pTab) ? SRT_Table : SRT_Upfrom;
246     pList = sqlite3ExprListAppend(pParse, 0, sqlite3PExpr(pParse,TK_ROW,0,0));
247 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
248     if( pLimit ){
249       pGrp = sqlite3ExprListAppend(pParse, 0, sqlite3PExpr(pParse,TK_ROW,0,0));
250     }
251 #endif
252   }
253   assert( pChanges!=0 || pParse->db->mallocFailed );
254   if( pChanges ){
255     for(i=0; i<pChanges->nExpr; i++){
256       pList = sqlite3ExprListAppend(pParse, pList,
257           sqlite3ExprDup(db, pChanges->a[i].pExpr, 0)
258       );
259     }
260   }
261   pSelect = sqlite3SelectNew(pParse, pList,
262       pSrc, pWhere2, pGrp, 0, pOrderBy2, SF_UpdateFrom|SF_IncludeHidden, pLimit2
263   );
264   sqlite3SelectDestInit(&dest, eDest, iEph);
265   dest.iSDParm2 = (pPk ? pPk->nKeyCol : -1);
266   sqlite3Select(pParse, pSelect, &dest);
267   sqlite3SelectDelete(db, pSelect);
268 }
269 
270 /*
271 ** Process an UPDATE statement.
272 **
273 **   UPDATE OR IGNORE tbl SET a=b, c=d FROM tbl2... WHERE e<5 AND f NOT NULL;
274 **          \_______/ \_/     \______/      \_____/       \________________/
275 **           onError   |      pChanges         |                pWhere
276 **                     \_______________________/
277 **                               pTabList
278 */
279 void sqlite3Update(
280   Parse *pParse,         /* The parser context */
281   SrcList *pTabList,     /* The table in which we should change things */
282   ExprList *pChanges,    /* Things to be changed */
283   Expr *pWhere,          /* The WHERE clause.  May be null */
284   int onError,           /* How to handle constraint errors */
285   ExprList *pOrderBy,    /* ORDER BY clause. May be null */
286   Expr *pLimit,          /* LIMIT clause. May be null */
287   Upsert *pUpsert        /* ON CONFLICT clause, or null */
288 ){
289   int i, j, k;           /* Loop counters */
290   Table *pTab;           /* The table to be updated */
291   int addrTop = 0;       /* VDBE instruction address of the start of the loop */
292   WhereInfo *pWInfo = 0; /* Information about the WHERE clause */
293   Vdbe *v;               /* The virtual database engine */
294   Index *pIdx;           /* For looping over indices */
295   Index *pPk;            /* The PRIMARY KEY index for WITHOUT ROWID tables */
296   int nIdx;              /* Number of indices that need updating */
297   int nAllIdx;           /* Total number of indexes */
298   int iBaseCur;          /* Base cursor number */
299   int iDataCur;          /* Cursor for the canonical data btree */
300   int iIdxCur;           /* Cursor for the first index */
301   sqlite3 *db;           /* The database structure */
302   int *aRegIdx = 0;      /* Registers for to each index and the main table */
303   int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
304                          ** an expression for the i-th column of the table.
305                          ** aXRef[i]==-1 if the i-th column is not changed. */
306   u8 *aToOpen;           /* 1 for tables and indices to be opened */
307   u8 chngPk;             /* PRIMARY KEY changed in a WITHOUT ROWID table */
308   u8 chngRowid;          /* Rowid changed in a normal table */
309   u8 chngKey;            /* Either chngPk or chngRowid */
310   Expr *pRowidExpr = 0;  /* Expression defining the new record number */
311   int iRowidExpr = -1;   /* Index of "rowid=" (or IPK) assignment in pChanges */
312   AuthContext sContext;  /* The authorization context */
313   NameContext sNC;       /* The name-context to resolve expressions in */
314   int iDb;               /* Database containing the table being updated */
315   int eOnePass;          /* ONEPASS_XXX value from where.c */
316   int hasFK;             /* True if foreign key processing is required */
317   int labelBreak;        /* Jump here to break out of UPDATE loop */
318   int labelContinue;     /* Jump here to continue next step of UPDATE loop */
319   int flags;             /* Flags for sqlite3WhereBegin() */
320 
321 #ifndef SQLITE_OMIT_TRIGGER
322   int isView;            /* True when updating a view (INSTEAD OF trigger) */
323   Trigger *pTrigger;     /* List of triggers on pTab, if required */
324   int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
325 #endif
326   int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
327   int iEph = 0;          /* Ephemeral table holding all primary key values */
328   int nKey = 0;          /* Number of elements in regKey for WITHOUT ROWID */
329   int aiCurOnePass[2];   /* The write cursors opened by WHERE_ONEPASS */
330   int addrOpen = 0;      /* Address of OP_OpenEphemeral */
331   int iPk = 0;           /* First of nPk cells holding PRIMARY KEY value */
332   i16 nPk = 0;           /* Number of components of the PRIMARY KEY */
333   int bReplace = 0;      /* True if REPLACE conflict resolution might happen */
334   int bFinishSeek = 1;   /* The OP_FinishSeek opcode is needed */
335   int nChangeFrom = 0;   /* If there is a FROM, pChanges->nExpr, else 0 */
336 
337   /* Register Allocations */
338   int regRowCount = 0;   /* A count of rows changed */
339   int regOldRowid = 0;   /* The old rowid */
340   int regNewRowid = 0;   /* The new rowid */
341   int regNew = 0;        /* Content of the NEW.* table in triggers */
342   int regOld = 0;        /* Content of OLD.* table in triggers */
343   int regRowSet = 0;     /* Rowset of rows to be updated */
344   int regKey = 0;        /* composite PRIMARY KEY value */
345 
346   memset(&sContext, 0, sizeof(sContext));
347   db = pParse->db;
348   if( pParse->nErr || db->mallocFailed ){
349     goto update_cleanup;
350   }
351 
352   /* Locate the table which we want to update.
353   */
354   pTab = sqlite3SrcListLookup(pParse, pTabList);
355   if( pTab==0 ) goto update_cleanup;
356   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
357 
358   /* Figure out if we have any triggers and if the table being
359   ** updated is a view.
360   */
361 #ifndef SQLITE_OMIT_TRIGGER
362   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
363   isView = pTab->pSelect!=0;
364   assert( pTrigger || tmask==0 );
365 #else
366 # define pTrigger 0
367 # define isView 0
368 # define tmask 0
369 #endif
370 #ifdef SQLITE_OMIT_VIEW
371 # undef isView
372 # define isView 0
373 #endif
374 
375   /* If there was a FROM clause, set nChangeFrom to the number of expressions
376   ** in the change-list. Otherwise, set it to 0. There cannot be a FROM
377   ** clause if this function is being called to generate code for part of
378   ** an UPSERT statement.  */
379   nChangeFrom = (pTabList->nSrc>1) ? pChanges->nExpr : 0;
380   assert( nChangeFrom==0 || pUpsert==0 );
381 
382 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
383   if( !isView && nChangeFrom==0 ){
384     pWhere = sqlite3LimitWhere(
385         pParse, pTabList, pWhere, pOrderBy, pLimit, "UPDATE"
386     );
387     pOrderBy = 0;
388     pLimit = 0;
389   }
390 #endif
391 
392   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
393     goto update_cleanup;
394   }
395   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
396     goto update_cleanup;
397   }
398 
399   /* Allocate a cursors for the main database table and for all indices.
400   ** The index cursors might not be used, but if they are used they
401   ** need to occur right after the database cursor.  So go ahead and
402   ** allocate enough space, just in case.
403   */
404   iBaseCur = iDataCur = pParse->nTab++;
405   iIdxCur = iDataCur+1;
406   pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
407   testcase( pPk!=0 && pPk!=pTab->pIndex );
408   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
409     if( pPk==pIdx ){
410       iDataCur = pParse->nTab;
411     }
412     pParse->nTab++;
413   }
414   if( pUpsert ){
415     /* On an UPSERT, reuse the same cursors already opened by INSERT */
416     iDataCur = pUpsert->iDataCur;
417     iIdxCur = pUpsert->iIdxCur;
418     pParse->nTab = iBaseCur;
419   }
420   pTabList->a[0].iCursor = iDataCur;
421 
422   /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].
423   ** Initialize aXRef[] and aToOpen[] to their default values.
424   */
425   aXRef = sqlite3DbMallocRawNN(db, sizeof(int) * (pTab->nCol+nIdx+1) + nIdx+2 );
426   if( aXRef==0 ) goto update_cleanup;
427   aRegIdx = aXRef+pTab->nCol;
428   aToOpen = (u8*)(aRegIdx+nIdx+1);
429   memset(aToOpen, 1, nIdx+1);
430   aToOpen[nIdx+1] = 0;
431   for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
432 
433   /* Initialize the name-context */
434   memset(&sNC, 0, sizeof(sNC));
435   sNC.pParse = pParse;
436   sNC.pSrcList = pTabList;
437   sNC.uNC.pUpsert = pUpsert;
438   sNC.ncFlags = NC_UUpsert;
439 
440   /* Begin generating code. */
441   v = sqlite3GetVdbe(pParse);
442   if( v==0 ) goto update_cleanup;
443 
444   /* Resolve the column names in all the expressions of the
445   ** of the UPDATE statement.  Also find the column index
446   ** for each column to be updated in the pChanges array.  For each
447   ** column to be updated, make sure we have authorization to change
448   ** that column.
449   */
450   chngRowid = chngPk = 0;
451   for(i=0; i<pChanges->nExpr; i++){
452     /* If this is an UPDATE with a FROM clause, do not resolve expressions
453     ** here. The call to sqlite3Select() below will do that. */
454     if( nChangeFrom==0 && sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
455       goto update_cleanup;
456     }
457     for(j=0; j<pTab->nCol; j++){
458       if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zEName)==0 ){
459         if( j==pTab->iPKey ){
460           chngRowid = 1;
461           pRowidExpr = pChanges->a[i].pExpr;
462           iRowidExpr = i;
463         }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
464           chngPk = 1;
465         }
466 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
467         else if( pTab->aCol[j].colFlags & COLFLAG_GENERATED ){
468           testcase( pTab->aCol[j].colFlags & COLFLAG_VIRTUAL );
469           testcase( pTab->aCol[j].colFlags & COLFLAG_STORED );
470           sqlite3ErrorMsg(pParse,
471              "cannot UPDATE generated column \"%s\"",
472              pTab->aCol[j].zName);
473           goto update_cleanup;
474         }
475 #endif
476         aXRef[j] = i;
477         break;
478       }
479     }
480     if( j>=pTab->nCol ){
481       if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zEName) ){
482         j = -1;
483         chngRowid = 1;
484         pRowidExpr = pChanges->a[i].pExpr;
485         iRowidExpr = i;
486       }else{
487         sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zEName);
488         pParse->checkSchema = 1;
489         goto update_cleanup;
490       }
491     }
492 #ifndef SQLITE_OMIT_AUTHORIZATION
493     {
494       int rc;
495       rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
496                             j<0 ? "ROWID" : pTab->aCol[j].zName,
497                             db->aDb[iDb].zDbSName);
498       if( rc==SQLITE_DENY ){
499         goto update_cleanup;
500       }else if( rc==SQLITE_IGNORE ){
501         aXRef[j] = -1;
502       }
503     }
504 #endif
505   }
506   assert( (chngRowid & chngPk)==0 );
507   assert( chngRowid==0 || chngRowid==1 );
508   assert( chngPk==0 || chngPk==1 );
509   chngKey = chngRowid + chngPk;
510 
511 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
512   /* Mark generated columns as changing if their generator expressions
513   ** reference any changing column.  The actual aXRef[] value for
514   ** generated expressions is not used, other than to check to see that it
515   ** is non-negative, so the value of aXRef[] for generated columns can be
516   ** set to any non-negative number.  We use 99999 so that the value is
517   ** obvious when looking at aXRef[] in a symbolic debugger.
518   */
519   if( pTab->tabFlags & TF_HasGenerated ){
520     int bProgress;
521     testcase( pTab->tabFlags & TF_HasVirtual );
522     testcase( pTab->tabFlags & TF_HasStored );
523     do{
524       bProgress = 0;
525       for(i=0; i<pTab->nCol; i++){
526         if( aXRef[i]>=0 ) continue;
527         if( (pTab->aCol[i].colFlags & COLFLAG_GENERATED)==0 ) continue;
528         if( sqlite3ExprReferencesUpdatedColumn(pTab->aCol[i].pDflt,
529                                                aXRef, chngRowid) ){
530           aXRef[i] = 99999;
531           bProgress = 1;
532         }
533       }
534     }while( bProgress );
535   }
536 #endif
537 
538   /* The SET expressions are not actually used inside the WHERE loop.
539   ** So reset the colUsed mask. Unless this is a virtual table. In that
540   ** case, set all bits of the colUsed mask (to ensure that the virtual
541   ** table implementation makes all columns available).
542   */
543   pTabList->a[0].colUsed = IsVirtual(pTab) ? ALLBITS : 0;
544 
545   hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
546 
547   /* There is one entry in the aRegIdx[] array for each index on the table
548   ** being updated.  Fill in aRegIdx[] with a register number that will hold
549   ** the key for accessing each index.
550   */
551   if( onError==OE_Replace ) bReplace = 1;
552   for(nAllIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nAllIdx++){
553     int reg;
554     if( chngKey || hasFK>1 || pIdx==pPk
555      || indexWhereClauseMightChange(pIdx,aXRef,chngRowid)
556     ){
557       reg = ++pParse->nMem;
558       pParse->nMem += pIdx->nColumn;
559     }else{
560       reg = 0;
561       for(i=0; i<pIdx->nKeyCol; i++){
562         if( indexColumnIsBeingUpdated(pIdx, i, aXRef, chngRowid) ){
563           reg = ++pParse->nMem;
564           pParse->nMem += pIdx->nColumn;
565           if( onError==OE_Default && pIdx->onError==OE_Replace ){
566             bReplace = 1;
567           }
568           break;
569         }
570       }
571     }
572     if( reg==0 ) aToOpen[nAllIdx+1] = 0;
573     aRegIdx[nAllIdx] = reg;
574   }
575   aRegIdx[nAllIdx] = ++pParse->nMem;  /* Register storing the table record */
576   if( bReplace ){
577     /* If REPLACE conflict resolution might be invoked, open cursors on all
578     ** indexes in case they are needed to delete records.  */
579     memset(aToOpen, 1, nIdx+1);
580   }
581 
582   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
583   sqlite3BeginWriteOperation(pParse, pTrigger || hasFK, iDb);
584 
585   /* Allocate required registers. */
586   if( !IsVirtual(pTab) ){
587     /* For now, regRowSet and aRegIdx[nAllIdx] share the same register.
588     ** If regRowSet turns out to be needed, then aRegIdx[nAllIdx] will be
589     ** reallocated.  aRegIdx[nAllIdx] is the register in which the main
590     ** table record is written.  regRowSet holds the RowSet for the
591     ** two-pass update algorithm. */
592     assert( aRegIdx[nAllIdx]==pParse->nMem );
593     regRowSet = aRegIdx[nAllIdx];
594     regOldRowid = regNewRowid = ++pParse->nMem;
595     if( chngPk || pTrigger || hasFK ){
596       regOld = pParse->nMem + 1;
597       pParse->nMem += pTab->nCol;
598     }
599     if( chngKey || pTrigger || hasFK ){
600       regNewRowid = ++pParse->nMem;
601     }
602     regNew = pParse->nMem + 1;
603     pParse->nMem += pTab->nCol;
604   }
605 
606   /* Start the view context. */
607   if( isView ){
608     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
609   }
610 
611   /* If we are trying to update a view, realize that view into
612   ** an ephemeral table.
613   */
614 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
615   if( nChangeFrom==0 && isView ){
616     sqlite3MaterializeView(pParse, pTab,
617         pWhere, pOrderBy, pLimit, iDataCur
618     );
619     pOrderBy = 0;
620     pLimit = 0;
621   }
622 #endif
623 
624   /* Resolve the column names in all the expressions in the
625   ** WHERE clause.
626   */
627   if( nChangeFrom==0 && sqlite3ResolveExprNames(&sNC, pWhere) ){
628     goto update_cleanup;
629   }
630 
631 #ifndef SQLITE_OMIT_VIRTUALTABLE
632   /* Virtual tables must be handled separately */
633   if( IsVirtual(pTab) ){
634     updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
635                        pWhere, onError);
636     goto update_cleanup;
637   }
638 #endif
639 
640   /* Jump to labelBreak to abandon further processing of this UPDATE */
641   labelContinue = labelBreak = sqlite3VdbeMakeLabel(pParse);
642 
643   /* Not an UPSERT.  Normal processing.  Begin by
644   ** initialize the count of updated rows */
645   if( (db->flags&SQLITE_CountRows)!=0
646    && !pParse->pTriggerTab
647    && !pParse->nested
648    && !pParse->bReturning
649    && pUpsert==0
650   ){
651     regRowCount = ++pParse->nMem;
652     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
653   }
654 
655   if( nChangeFrom==0 && HasRowid(pTab) ){
656     sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
657     iEph = pParse->nTab++;
658     addrOpen = sqlite3VdbeAddOp3(v, OP_OpenEphemeral, iEph, 0, regRowSet);
659   }else{
660     assert( pPk!=0 || HasRowid(pTab) );
661     nPk = pPk ? pPk->nKeyCol : 0;
662     iPk = pParse->nMem+1;
663     pParse->nMem += nPk;
664     pParse->nMem += nChangeFrom;
665     regKey = ++pParse->nMem;
666     if( pUpsert==0 ){
667       int nEphCol = nPk + nChangeFrom + (isView ? pTab->nCol : 0);
668       iEph = pParse->nTab++;
669       if( pPk ) sqlite3VdbeAddOp3(v, OP_Null, 0, iPk, iPk+nPk-1);
670       addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nEphCol);
671       if( pPk ){
672         KeyInfo *pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pPk);
673         if( pKeyInfo ){
674           pKeyInfo->nAllField = nEphCol;
675           sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
676         }
677       }
678       if( nChangeFrom ){
679         updateFromSelect(
680             pParse, iEph, pPk, pChanges, pTabList, pWhere, pOrderBy, pLimit
681         );
682 #ifndef SQLITE_OMIT_SUBQUERY
683         if( isView ) iDataCur = iEph;
684 #endif
685       }
686     }
687   }
688 
689   if( nChangeFrom ){
690     sqlite3MultiWrite(pParse);
691     eOnePass = ONEPASS_OFF;
692     nKey = nPk;
693     regKey = iPk;
694   }else{
695     if( pUpsert ){
696       /* If this is an UPSERT, then all cursors have already been opened by
697       ** the outer INSERT and the data cursor should be pointing at the row
698       ** that is to be updated.  So bypass the code that searches for the
699       ** row(s) to be updated.
700       */
701       pWInfo = 0;
702       eOnePass = ONEPASS_SINGLE;
703       sqlite3ExprIfFalse(pParse, pWhere, labelBreak, SQLITE_JUMPIFNULL);
704       bFinishSeek = 0;
705     }else{
706       /* Begin the database scan.
707       **
708       ** Do not consider a single-pass strategy for a multi-row update if
709       ** there are any triggers or foreign keys to process, or rows may
710       ** be deleted as a result of REPLACE conflict handling. Any of these
711       ** things might disturb a cursor being used to scan through the table
712       ** or index, causing a single-pass approach to malfunction.  */
713       flags = WHERE_ONEPASS_DESIRED;
714       if( !pParse->nested && !pTrigger && !hasFK && !chngKey && !bReplace ){
715         flags |= WHERE_ONEPASS_MULTIROW;
716       }
717       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, flags,iIdxCur);
718       if( pWInfo==0 ) goto update_cleanup;
719 
720       /* A one-pass strategy that might update more than one row may not
721       ** be used if any column of the index used for the scan is being
722       ** updated. Otherwise, if there is an index on "b", statements like
723       ** the following could create an infinite loop:
724       **
725       **   UPDATE t1 SET b=b+1 WHERE b>?
726       **
727       ** Fall back to ONEPASS_OFF if where.c has selected a ONEPASS_MULTI
728       ** strategy that uses an index for which one or more columns are being
729       ** updated.  */
730       eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
731       bFinishSeek = sqlite3WhereUsesDeferredSeek(pWInfo);
732       if( eOnePass!=ONEPASS_SINGLE ){
733         sqlite3MultiWrite(pParse);
734         if( eOnePass==ONEPASS_MULTI ){
735           int iCur = aiCurOnePass[1];
736           if( iCur>=0 && iCur!=iDataCur && aToOpen[iCur-iBaseCur] ){
737             eOnePass = ONEPASS_OFF;
738           }
739           assert( iCur!=iDataCur || !HasRowid(pTab) );
740         }
741       }
742     }
743 
744     if( HasRowid(pTab) ){
745       /* Read the rowid of the current row of the WHERE scan. In ONEPASS_OFF
746       ** mode, write the rowid into the FIFO. In either of the one-pass modes,
747       ** leave it in register regOldRowid.  */
748       sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
749       if( eOnePass==ONEPASS_OFF ){
750         aRegIdx[nAllIdx] = ++pParse->nMem;
751         sqlite3VdbeAddOp3(v, OP_Insert, iEph, regRowSet, regOldRowid);
752       }else{
753         if( ALWAYS(addrOpen) ) sqlite3VdbeChangeToNoop(v, addrOpen);
754       }
755     }else{
756       /* Read the PK of the current row into an array of registers. In
757       ** ONEPASS_OFF mode, serialize the array into a record and store it in
758       ** the ephemeral table. Or, in ONEPASS_SINGLE or MULTI mode, change
759       ** the OP_OpenEphemeral instruction to a Noop (the ephemeral table
760       ** is not required) and leave the PK fields in the array of registers.  */
761       for(i=0; i<nPk; i++){
762         assert( pPk->aiColumn[i]>=0 );
763         sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur,
764                                         pPk->aiColumn[i], iPk+i);
765       }
766       if( eOnePass ){
767         if( addrOpen ) sqlite3VdbeChangeToNoop(v, addrOpen);
768         nKey = nPk;
769         regKey = iPk;
770       }else{
771         sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
772                           sqlite3IndexAffinityStr(db, pPk), nPk);
773         sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEph, regKey, iPk, nPk);
774       }
775     }
776   }
777 
778   if( pUpsert==0 ){
779     if( nChangeFrom==0 && eOnePass!=ONEPASS_MULTI ){
780       sqlite3WhereEnd(pWInfo);
781     }
782 
783     if( !isView ){
784       int addrOnce = 0;
785 
786       /* Open every index that needs updating. */
787       if( eOnePass!=ONEPASS_OFF ){
788         if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
789         if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
790       }
791 
792       if( eOnePass==ONEPASS_MULTI && (nIdx-(aiCurOnePass[1]>=0))>0 ){
793         addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
794       }
795       sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, iBaseCur,
796                                  aToOpen, 0, 0);
797       if( addrOnce ){
798         sqlite3VdbeJumpHereOrPopInst(v, addrOnce);
799       }
800     }
801 
802     /* Top of the update loop */
803     if( eOnePass!=ONEPASS_OFF ){
804       if( aiCurOnePass[0]!=iDataCur
805        && aiCurOnePass[1]!=iDataCur
806 #ifdef SQLITE_ALLOW_ROWID_IN_VIEW
807        && !isView
808 #endif
809       ){
810         assert( pPk );
811         sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey,nKey);
812         VdbeCoverage(v);
813       }
814       if( eOnePass!=ONEPASS_SINGLE ){
815         labelContinue = sqlite3VdbeMakeLabel(pParse);
816       }
817       sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
818       VdbeCoverageIf(v, pPk==0);
819       VdbeCoverageIf(v, pPk!=0);
820     }else if( pPk || nChangeFrom ){
821       labelContinue = sqlite3VdbeMakeLabel(pParse);
822       sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
823       addrTop = sqlite3VdbeCurrentAddr(v);
824       if( nChangeFrom ){
825         if( !isView ){
826           if( pPk ){
827             for(i=0; i<nPk; i++){
828               sqlite3VdbeAddOp3(v, OP_Column, iEph, i, iPk+i);
829             }
830             sqlite3VdbeAddOp4Int(
831                 v, OP_NotFound, iDataCur, labelContinue, iPk, nPk
832             ); VdbeCoverage(v);
833           }else{
834             sqlite3VdbeAddOp2(v, OP_Rowid, iEph, regOldRowid);
835             sqlite3VdbeAddOp3(
836                 v, OP_NotExists, iDataCur, labelContinue, regOldRowid
837             ); VdbeCoverage(v);
838           }
839         }
840       }else{
841         sqlite3VdbeAddOp2(v, OP_RowData, iEph, regKey);
842         sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey,0);
843         VdbeCoverage(v);
844       }
845     }else{
846       sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
847       labelContinue = sqlite3VdbeMakeLabel(pParse);
848       addrTop = sqlite3VdbeAddOp2(v, OP_Rowid, iEph, regOldRowid);
849       VdbeCoverage(v);
850       sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
851       VdbeCoverage(v);
852     }
853   }
854 
855   /* If the rowid value will change, set register regNewRowid to
856   ** contain the new value. If the rowid is not being modified,
857   ** then regNewRowid is the same register as regOldRowid, which is
858   ** already populated.  */
859   assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
860   if( chngRowid ){
861     assert( iRowidExpr>=0 );
862     if( nChangeFrom==0 ){
863       sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
864     }else{
865       sqlite3VdbeAddOp3(v, OP_Column, iEph, iRowidExpr, regNewRowid);
866     }
867     sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
868   }
869 
870   /* Compute the old pre-UPDATE content of the row being changed, if that
871   ** information is needed */
872   if( chngPk || hasFK || pTrigger ){
873     u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
874     oldmask |= sqlite3TriggerColmask(pParse,
875         pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
876     );
877     for(i=0; i<pTab->nCol; i++){
878       u32 colFlags = pTab->aCol[i].colFlags;
879       k = sqlite3TableColumnToStorage(pTab, i) + regOld;
880       if( oldmask==0xffffffff
881        || (i<32 && (oldmask & MASKBIT32(i))!=0)
882        || (colFlags & COLFLAG_PRIMKEY)!=0
883       ){
884         testcase(  oldmask!=0xffffffff && i==31 );
885         sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, k);
886       }else{
887         sqlite3VdbeAddOp2(v, OP_Null, 0, k);
888       }
889     }
890     if( chngRowid==0 && pPk==0 ){
891       sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
892     }
893   }
894 
895   /* Populate the array of registers beginning at regNew with the new
896   ** row data. This array is used to check constants, create the new
897   ** table and index records, and as the values for any new.* references
898   ** made by triggers.
899   **
900   ** If there are one or more BEFORE triggers, then do not populate the
901   ** registers associated with columns that are (a) not modified by
902   ** this UPDATE statement and (b) not accessed by new.* references. The
903   ** values for registers not modified by the UPDATE must be reloaded from
904   ** the database after the BEFORE triggers are fired anyway (as the trigger
905   ** may have modified them). So not loading those that are not going to
906   ** be used eliminates some redundant opcodes.
907   */
908   newmask = sqlite3TriggerColmask(
909       pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
910   );
911   for(i=0, k=regNew; i<pTab->nCol; i++, k++){
912     if( i==pTab->iPKey ){
913       sqlite3VdbeAddOp2(v, OP_Null, 0, k);
914     }else if( (pTab->aCol[i].colFlags & COLFLAG_GENERATED)!=0 ){
915       if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ) k--;
916     }else{
917       j = aXRef[i];
918       if( j>=0 ){
919         if( nChangeFrom ){
920           int nOff = (isView ? pTab->nCol : nPk);
921           assert( eOnePass==ONEPASS_OFF );
922           sqlite3VdbeAddOp3(v, OP_Column, iEph, nOff+j, k);
923         }else{
924           sqlite3ExprCode(pParse, pChanges->a[j].pExpr, k);
925         }
926       }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
927         /* This branch loads the value of a column that will not be changed
928         ** into a register. This is done if there are no BEFORE triggers, or
929         ** if there are one or more BEFORE triggers that use this value via
930         ** a new.* reference in a trigger program.
931         */
932         testcase( i==31 );
933         testcase( i==32 );
934         sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, k);
935         bFinishSeek = 0;
936       }else{
937         sqlite3VdbeAddOp2(v, OP_Null, 0, k);
938       }
939     }
940   }
941 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
942   if( pTab->tabFlags & TF_HasGenerated ){
943     testcase( pTab->tabFlags & TF_HasVirtual );
944     testcase( pTab->tabFlags & TF_HasStored );
945     sqlite3ComputeGeneratedColumns(pParse, regNew, pTab);
946   }
947 #endif
948 
949   /* Fire any BEFORE UPDATE triggers. This happens before constraints are
950   ** verified. One could argue that this is wrong.
951   */
952   if( tmask&TRIGGER_BEFORE ){
953     sqlite3TableAffinity(v, pTab, regNew);
954     sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
955         TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
956 
957     if( !isView ){
958       /* The row-trigger may have deleted the row being updated. In this
959       ** case, jump to the next row. No updates or AFTER triggers are
960       ** required. This behavior - what happens when the row being updated
961       ** is deleted or renamed by a BEFORE trigger - is left undefined in the
962       ** documentation.
963       */
964       if( pPk ){
965         sqlite3VdbeAddOp4Int(v, OP_NotFound,iDataCur,labelContinue,regKey,nKey);
966         VdbeCoverage(v);
967       }else{
968         sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue,regOldRowid);
969         VdbeCoverage(v);
970       }
971 
972       /* After-BEFORE-trigger-reload-loop:
973       ** If it did not delete it, the BEFORE trigger may still have modified
974       ** some of the columns of the row being updated. Load the values for
975       ** all columns not modified by the update statement into their registers
976       ** in case this has happened. Only unmodified columns are reloaded.
977       ** The values computed for modified columns use the values before the
978       ** BEFORE trigger runs.  See test case trigger1-18.0 (added 2018-04-26)
979       ** for an example.
980       */
981       for(i=0, k=regNew; i<pTab->nCol; i++, k++){
982         if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){
983           if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ) k--;
984         }else if( aXRef[i]<0 && i!=pTab->iPKey ){
985           sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, k);
986         }
987       }
988 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
989       if( pTab->tabFlags & TF_HasGenerated ){
990         testcase( pTab->tabFlags & TF_HasVirtual );
991         testcase( pTab->tabFlags & TF_HasStored );
992         sqlite3ComputeGeneratedColumns(pParse, regNew, pTab);
993       }
994 #endif
995     }
996   }
997 
998   if( !isView ){
999     /* Do constraint checks. */
1000     assert( regOldRowid>0 );
1001     sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
1002         regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace,
1003         aXRef, 0);
1004 
1005     /* If REPLACE conflict handling may have been used, or if the PK of the
1006     ** row is changing, then the GenerateConstraintChecks() above may have
1007     ** moved cursor iDataCur. Reseek it. */
1008     if( bReplace || chngKey ){
1009       if( pPk ){
1010         sqlite3VdbeAddOp4Int(v, OP_NotFound,iDataCur,labelContinue,regKey,nKey);
1011       }else{
1012         sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue,regOldRowid);
1013       }
1014       VdbeCoverageNeverTaken(v);
1015     }
1016 
1017     /* Do FK constraint checks. */
1018     if( hasFK ){
1019       sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);
1020     }
1021 
1022     /* Delete the index entries associated with the current record.  */
1023     sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx, -1);
1024 
1025     /* We must run the OP_FinishSeek opcode to resolve a prior
1026     ** OP_DeferredSeek if there is any possibility that there have been
1027     ** no OP_Column opcodes since the OP_DeferredSeek was issued.  But
1028     ** we want to avoid the OP_FinishSeek if possible, as running it
1029     ** costs CPU cycles. */
1030     if( bFinishSeek ){
1031       sqlite3VdbeAddOp1(v, OP_FinishSeek, iDataCur);
1032     }
1033 
1034     /* If changing the rowid value, or if there are foreign key constraints
1035     ** to process, delete the old record. Otherwise, add a noop OP_Delete
1036     ** to invoke the pre-update hook.
1037     **
1038     ** That (regNew==regnewRowid+1) is true is also important for the
1039     ** pre-update hook. If the caller invokes preupdate_new(), the returned
1040     ** value is copied from memory cell (regNewRowid+1+iCol), where iCol
1041     ** is the column index supplied by the user.
1042     */
1043     assert( regNew==regNewRowid+1 );
1044 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
1045     sqlite3VdbeAddOp3(v, OP_Delete, iDataCur,
1046         OPFLAG_ISUPDATE | ((hasFK>1 || chngKey) ? 0 : OPFLAG_ISNOOP),
1047         regNewRowid
1048     );
1049     if( eOnePass==ONEPASS_MULTI ){
1050       assert( hasFK==0 && chngKey==0 );
1051       sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
1052     }
1053     if( !pParse->nested ){
1054       sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
1055     }
1056 #else
1057     if( hasFK>1 || chngKey ){
1058       sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
1059     }
1060 #endif
1061 
1062     if( hasFK ){
1063       sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
1064     }
1065 
1066     /* Insert the new index entries and the new record. */
1067     sqlite3CompleteInsertion(
1068         pParse, pTab, iDataCur, iIdxCur, regNewRowid, aRegIdx,
1069         OPFLAG_ISUPDATE | (eOnePass==ONEPASS_MULTI ? OPFLAG_SAVEPOSITION : 0),
1070         0, 0
1071     );
1072 
1073     /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
1074     ** handle rows (possibly in other tables) that refer via a foreign key
1075     ** to the row just updated. */
1076     if( hasFK ){
1077       sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
1078     }
1079   }
1080 
1081   /* Increment the row counter
1082   */
1083   if( regRowCount ){
1084     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
1085   }
1086 
1087   sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
1088       TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
1089 
1090   /* Repeat the above with the next record to be updated, until
1091   ** all record selected by the WHERE clause have been updated.
1092   */
1093   if( eOnePass==ONEPASS_SINGLE ){
1094     /* Nothing to do at end-of-loop for a single-pass */
1095   }else if( eOnePass==ONEPASS_MULTI ){
1096     sqlite3VdbeResolveLabel(v, labelContinue);
1097     sqlite3WhereEnd(pWInfo);
1098   }else{
1099     sqlite3VdbeResolveLabel(v, labelContinue);
1100     sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
1101   }
1102   sqlite3VdbeResolveLabel(v, labelBreak);
1103 
1104   /* Update the sqlite_sequence table by storing the content of the
1105   ** maximum rowid counter values recorded while inserting into
1106   ** autoincrement tables.
1107   */
1108   if( pParse->nested==0 && pParse->pTriggerTab==0 && pUpsert==0 ){
1109     sqlite3AutoincrementEnd(pParse);
1110   }
1111 
1112   /*
1113   ** Return the number of rows that were changed, if we are tracking
1114   ** that information.
1115   */
1116   if( regRowCount ){
1117     sqlite3VdbeAddOp2(v, OP_ChngCntRow, regRowCount, 1);
1118     sqlite3VdbeSetNumCols(v, 1);
1119     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
1120   }
1121 
1122 update_cleanup:
1123   sqlite3AuthContextPop(&sContext);
1124   sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */
1125   sqlite3SrcListDelete(db, pTabList);
1126   sqlite3ExprListDelete(db, pChanges);
1127   sqlite3ExprDelete(db, pWhere);
1128 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
1129   sqlite3ExprListDelete(db, pOrderBy);
1130   sqlite3ExprDelete(db, pLimit);
1131 #endif
1132   return;
1133 }
1134 /* Make sure "isView" and other macros defined above are undefined. Otherwise
1135 ** they may interfere with compilation of other functions in this file
1136 ** (or in another file, if this file becomes part of the amalgamation).  */
1137 #ifdef isView
1138  #undef isView
1139 #endif
1140 #ifdef pTrigger
1141  #undef pTrigger
1142 #endif
1143 
1144 #ifndef SQLITE_OMIT_VIRTUALTABLE
1145 /*
1146 ** Generate code for an UPDATE of a virtual table.
1147 **
1148 ** There are two possible strategies - the default and the special
1149 ** "onepass" strategy. Onepass is only used if the virtual table
1150 ** implementation indicates that pWhere may match at most one row.
1151 **
1152 ** The default strategy is to create an ephemeral table that contains
1153 ** for each row to be changed:
1154 **
1155 **   (A)  The original rowid of that row.
1156 **   (B)  The revised rowid for the row.
1157 **   (C)  The content of every column in the row.
1158 **
1159 ** Then loop through the contents of this ephemeral table executing a
1160 ** VUpdate for each row. When finished, drop the ephemeral table.
1161 **
1162 ** The "onepass" strategy does not use an ephemeral table. Instead, it
1163 ** stores the same values (A, B and C above) in a register array and
1164 ** makes a single invocation of VUpdate.
1165 */
1166 static void updateVirtualTable(
1167   Parse *pParse,       /* The parsing context */
1168   SrcList *pSrc,       /* The virtual table to be modified */
1169   Table *pTab,         /* The virtual table */
1170   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
1171   Expr *pRowid,        /* Expression used to recompute the rowid */
1172   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
1173   Expr *pWhere,        /* WHERE clause of the UPDATE statement */
1174   int onError          /* ON CONFLICT strategy */
1175 ){
1176   Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
1177   int ephemTab;             /* Table holding the result of the SELECT */
1178   int i;                    /* Loop counter */
1179   sqlite3 *db = pParse->db; /* Database connection */
1180   const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
1181   WhereInfo *pWInfo = 0;
1182   int nArg = 2 + pTab->nCol;      /* Number of arguments to VUpdate */
1183   int regArg;                     /* First register in VUpdate arg array */
1184   int regRec;                     /* Register in which to assemble record */
1185   int regRowid;                   /* Register for ephem table rowid */
1186   int iCsr = pSrc->a[0].iCursor;  /* Cursor used for virtual table scan */
1187   int aDummy[2];                  /* Unused arg for sqlite3WhereOkOnePass() */
1188   int eOnePass;                   /* True to use onepass strategy */
1189   int addr;                       /* Address of OP_OpenEphemeral */
1190 
1191   /* Allocate nArg registers in which to gather the arguments for VUpdate. Then
1192   ** create and open the ephemeral table in which the records created from
1193   ** these arguments will be temporarily stored. */
1194   assert( v );
1195   ephemTab = pParse->nTab++;
1196   addr= sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, nArg);
1197   regArg = pParse->nMem + 1;
1198   pParse->nMem += nArg;
1199   if( pSrc->nSrc>1 ){
1200     Index *pPk = 0;
1201     Expr *pRow;
1202     ExprList *pList;
1203     if( HasRowid(pTab) ){
1204       if( pRowid ){
1205         pRow = sqlite3ExprDup(db, pRowid, 0);
1206       }else{
1207         pRow = sqlite3PExpr(pParse, TK_ROW, 0, 0);
1208       }
1209     }else{
1210       i16 iPk;      /* PRIMARY KEY column */
1211       pPk = sqlite3PrimaryKeyIndex(pTab);
1212       assert( pPk!=0 );
1213       assert( pPk->nKeyCol==1 );
1214       iPk = pPk->aiColumn[0];
1215       if( aXRef[iPk]>=0 ){
1216         pRow = sqlite3ExprDup(db, pChanges->a[aXRef[iPk]].pExpr, 0);
1217       }else{
1218         pRow = exprRowColumn(pParse, iPk);
1219       }
1220     }
1221     pList = sqlite3ExprListAppend(pParse, 0, pRow);
1222 
1223     for(i=0; i<pTab->nCol; i++){
1224       if( aXRef[i]>=0 ){
1225         pList = sqlite3ExprListAppend(pParse, pList,
1226           sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0)
1227         );
1228       }else{
1229         pList = sqlite3ExprListAppend(pParse, pList, exprRowColumn(pParse, i));
1230       }
1231     }
1232 
1233     updateFromSelect(pParse, ephemTab, pPk, pList, pSrc, pWhere, 0, 0);
1234     sqlite3ExprListDelete(db, pList);
1235     eOnePass = ONEPASS_OFF;
1236   }else{
1237     regRec = ++pParse->nMem;
1238     regRowid = ++pParse->nMem;
1239 
1240     /* Start scanning the virtual table */
1241     pWInfo = sqlite3WhereBegin(pParse, pSrc,pWhere,0,0,WHERE_ONEPASS_DESIRED,0);
1242     if( pWInfo==0 ) return;
1243 
1244     /* Populate the argument registers. */
1245     for(i=0; i<pTab->nCol; i++){
1246       assert( (pTab->aCol[i].colFlags & COLFLAG_GENERATED)==0 );
1247       if( aXRef[i]>=0 ){
1248         sqlite3ExprCode(pParse, pChanges->a[aXRef[i]].pExpr, regArg+2+i);
1249       }else{
1250         sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, i, regArg+2+i);
1251         sqlite3VdbeChangeP5(v, OPFLAG_NOCHNG);/* For sqlite3_vtab_nochange() */
1252       }
1253     }
1254     if( HasRowid(pTab) ){
1255       sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg);
1256       if( pRowid ){
1257         sqlite3ExprCode(pParse, pRowid, regArg+1);
1258       }else{
1259         sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg+1);
1260       }
1261     }else{
1262       Index *pPk;   /* PRIMARY KEY index */
1263       i16 iPk;      /* PRIMARY KEY column */
1264       pPk = sqlite3PrimaryKeyIndex(pTab);
1265       assert( pPk!=0 );
1266       assert( pPk->nKeyCol==1 );
1267       iPk = pPk->aiColumn[0];
1268       sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, iPk, regArg);
1269       sqlite3VdbeAddOp2(v, OP_SCopy, regArg+2+iPk, regArg+1);
1270     }
1271 
1272     eOnePass = sqlite3WhereOkOnePass(pWInfo, aDummy);
1273 
1274     /* There is no ONEPASS_MULTI on virtual tables */
1275     assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );
1276 
1277     if( eOnePass ){
1278       /* If using the onepass strategy, no-op out the OP_OpenEphemeral coded
1279       ** above. */
1280       sqlite3VdbeChangeToNoop(v, addr);
1281       sqlite3VdbeAddOp1(v, OP_Close, iCsr);
1282     }else{
1283       /* Create a record from the argument register contents and insert it into
1284       ** the ephemeral table. */
1285       sqlite3MultiWrite(pParse);
1286       sqlite3VdbeAddOp3(v, OP_MakeRecord, regArg, nArg, regRec);
1287 #if defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_NULL_TRIM)
1288       /* Signal an assert() within OP_MakeRecord that it is allowed to
1289       ** accept no-change records with serial_type 10 */
1290       sqlite3VdbeChangeP5(v, OPFLAG_NOCHNG_MAGIC);
1291 #endif
1292       sqlite3VdbeAddOp2(v, OP_NewRowid, ephemTab, regRowid);
1293       sqlite3VdbeAddOp3(v, OP_Insert, ephemTab, regRec, regRowid);
1294     }
1295   }
1296 
1297 
1298   if( eOnePass==ONEPASS_OFF ){
1299     /* End the virtual table scan */
1300     if( pSrc->nSrc==1 ){
1301       sqlite3WhereEnd(pWInfo);
1302     }
1303 
1304     /* Begin scannning through the ephemeral table. */
1305     addr = sqlite3VdbeAddOp1(v, OP_Rewind, ephemTab); VdbeCoverage(v);
1306 
1307     /* Extract arguments from the current row of the ephemeral table and
1308     ** invoke the VUpdate method.  */
1309     for(i=0; i<nArg; i++){
1310       sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i, regArg+i);
1311     }
1312   }
1313   sqlite3VtabMakeWritable(pParse, pTab);
1314   sqlite3VdbeAddOp4(v, OP_VUpdate, 0, nArg, regArg, pVTab, P4_VTAB);
1315   sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
1316   sqlite3MayAbort(pParse);
1317 
1318   /* End of the ephemeral table scan. Or, if using the onepass strategy,
1319   ** jump to here if the scan visited zero rows. */
1320   if( eOnePass==ONEPASS_OFF ){
1321     sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
1322     sqlite3VdbeJumpHere(v, addr);
1323     sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
1324   }else{
1325     sqlite3WhereEnd(pWInfo);
1326   }
1327 }
1328 #endif /* SQLITE_OMIT_VIRTUALTABLE */
1329