xref: /sqlite-3.40.0/src/update.c (revision c9ef12f6)
1cce7d176Sdrh /*
2b19a2bc6Sdrh ** 2001 September 15
3cce7d176Sdrh **
4b19a2bc6Sdrh ** The author disclaims copyright to this source code.  In place of
5b19a2bc6Sdrh ** a legal notice, here is a blessing:
6cce7d176Sdrh **
7b19a2bc6Sdrh **    May you do good and not evil.
8b19a2bc6Sdrh **    May you find forgiveness for yourself and forgive others.
9b19a2bc6Sdrh **    May you share freely, never taking more than you give.
10cce7d176Sdrh **
11a3388cc5Sdrh *************************************************************************
12cce7d176Sdrh ** This file contains C code routines that are called by the parser
13cce7d176Sdrh ** to handle UPDATE statements.
14cce7d176Sdrh */
15cce7d176Sdrh #include "sqliteInt.h"
16cce7d176Sdrh 
17edb193b7Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
189c41938fSdrh /* Forward declaration */
199c41938fSdrh static void updateVirtualTable(
209c41938fSdrh   Parse *pParse,       /* The parsing context */
219c41938fSdrh   SrcList *pSrc,       /* The virtual table to be modified */
229c41938fSdrh   Table *pTab,         /* The virtual table */
239c41938fSdrh   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
249c41938fSdrh   Expr *pRowidExpr,    /* Expression used to recompute the rowid */
259c41938fSdrh   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
26b061d058Sdan   Expr *pWhere,        /* WHERE clause of the UPDATE statement */
27b061d058Sdan   int onError          /* ON CONFLICT strategy */
289c41938fSdrh );
29edb193b7Sdrh #endif /* SQLITE_OMIT_VIRTUALTABLE */
309c41938fSdrh 
31cce7d176Sdrh /*
328a51256cSdrh ** The most recently coded instruction was an OP_Column to retrieve the
3366a5167bSdrh ** i-th column of table pTab. This routine sets the P4 parameter of the
34aee18ef8Sdanielk1977 ** OP_Column to the default value, if any.
35aee18ef8Sdanielk1977 **
36aee18ef8Sdanielk1977 ** The default value of a column is specified by a DEFAULT clause in the
37aee18ef8Sdanielk1977 ** column definition. This was either supplied by the user when the table
38aee18ef8Sdanielk1977 ** was created, or added later to the table definition by an ALTER TABLE
39aee18ef8Sdanielk1977 ** command. If the latter, then the row-records in the table btree on disk
40aee18ef8Sdanielk1977 ** may not contain a value for the column and the default value, taken
4166a5167bSdrh ** from the P4 parameter of the OP_Column instruction, is returned instead.
42aee18ef8Sdanielk1977 ** If the former, then all row-records are guaranteed to include a value
4366a5167bSdrh ** for the column and the P4 value is not required.
44aee18ef8Sdanielk1977 **
45aee18ef8Sdanielk1977 ** Column definitions created by an ALTER TABLE command may only have
46aee18ef8Sdanielk1977 ** literal default values specified: a number, null or a string. (If a more
47aee18ef8Sdanielk1977 ** complicated default expression value was provided, it is evaluated
48aee18ef8Sdanielk1977 ** when the ALTER TABLE is executed and one of the literal values written
491e32bed3Sdrh ** into the sqlite_schema table.)
50aee18ef8Sdanielk1977 **
5166a5167bSdrh ** Therefore, the P4 parameter is only required if the default value for
52aee18ef8Sdanielk1977 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
53aee18ef8Sdanielk1977 ** function is capable of transforming these types of expressions into
54aee18ef8Sdanielk1977 ** sqlite3_value objects.
55c7538b5fSdanielk1977 **
568c1febb2Sdrh ** If column as REAL affinity and the table is an ordinary b-tree table
578c1febb2Sdrh ** (not a virtual table) then the value might have been stored as an
588c1febb2Sdrh ** integer.  In that case, add an OP_RealAffinity opcode to make sure
598c1febb2Sdrh ** it has been converted into REAL.
60aee18ef8Sdanielk1977 */
sqlite3ColumnDefault(Vdbe * v,Table * pTab,int i,int iReg)61c7538b5fSdanielk1977 void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
62*c9ef12f6Sdrh   Column *pCol;
63e289d606Sdrh   assert( pTab!=0 );
6449d77ee6Sdrh   assert( pTab->nCol>i );
6549d77ee6Sdrh   pCol = &pTab->aCol[i];
6649d77ee6Sdrh   if( pCol->iDflt ){
677a419235Sdan     sqlite3_value *pValue = 0;
6814db2665Sdanielk1977     u8 enc = ENC(sqlite3VdbeDb(v));
6949d77ee6Sdrh     assert( !IsView(pTab) );
70cf9d36d1Sdrh     VdbeComment((v, "%s.%s", pTab->zName, pCol->zCnName));
71c9cf6e3dSdanielk1977     assert( i<pTab->nCol );
7279cf2b71Sdrh     sqlite3ValueFromExpr(sqlite3VdbeDb(v),
7379cf2b71Sdrh                          sqlite3ColumnExpr(pTab,pCol), enc,
74d4e70ebdSdrh                          pCol->affinity, &pValue);
7529dda4aeSdrh     if( pValue ){
76f14b7fb7Sdrh       sqlite3VdbeAppendP4(v, pValue, P4_MEM);
7729dda4aeSdrh     }
78da060052Sdrh   }
79c7538b5fSdanielk1977 #ifndef SQLITE_OMIT_FLOATING_POINT
8049d77ee6Sdrh   if( pCol->affinity==SQLITE_AFF_REAL && !IsVirtual(pTab) ){
81c7538b5fSdanielk1977     sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
82c7538b5fSdanielk1977   }
83c7538b5fSdanielk1977 #endif
84aee18ef8Sdanielk1977 }
85aee18ef8Sdanielk1977 
86aee18ef8Sdanielk1977 /*
87e9816d82Sdrh ** Check to see if column iCol of index pIdx references any of the
88e9816d82Sdrh ** columns defined by aXRef and chngRowid.  Return true if it does
8940b4e7a6Sdrh ** and false if not.  This is an optimization.  False-positives are a
9040b4e7a6Sdrh ** performance degradation, but false-negatives can result in a corrupt
9140b4e7a6Sdrh ** index and incorrect answers.
92e9816d82Sdrh **
93e9816d82Sdrh ** aXRef[j] will be non-negative if column j of the original table is
94e9816d82Sdrh ** being updated.  chngRowid will be true if the rowid of the table is
95e9816d82Sdrh ** being updated.
96e9816d82Sdrh */
indexColumnIsBeingUpdated(Index * pIdx,int iCol,int * aXRef,int chngRowid)972b7cdf6fSdrh static int indexColumnIsBeingUpdated(
982b7cdf6fSdrh   Index *pIdx,      /* The index to check */
992b7cdf6fSdrh   int iCol,         /* Which column of the index to check */
100e9816d82Sdrh   int *aXRef,       /* aXRef[j]>=0 if column j is being updated */
101e9816d82Sdrh   int chngRowid     /* true if the rowid is being updated */
102e9816d82Sdrh ){
1032b7cdf6fSdrh   i16 iIdxCol = pIdx->aiColumn[iCol];
10486f34926Sdrh   assert( iIdxCol!=XN_ROWID ); /* Cannot index rowid */
1052b7cdf6fSdrh   if( iIdxCol>=0 ){
1062b7cdf6fSdrh     return aXRef[iIdxCol]>=0;
1072b7cdf6fSdrh   }
1082b7cdf6fSdrh   assert( iIdxCol==XN_EXPR );
109e9816d82Sdrh   assert( pIdx->aColExpr!=0 );
110e9816d82Sdrh   assert( pIdx->aColExpr->a[iCol].pExpr!=0 );
111e9816d82Sdrh   return sqlite3ExprReferencesUpdatedColumn(pIdx->aColExpr->a[iCol].pExpr,
112e9816d82Sdrh                                             aXRef,chngRowid);
113e9816d82Sdrh }
114e9816d82Sdrh 
115e9816d82Sdrh /*
11640b4e7a6Sdrh ** Check to see if index pIdx is a partial index whose conditional
11740b4e7a6Sdrh ** expression might change values due to an UPDATE.  Return true if
11840b4e7a6Sdrh ** the index is subject to change and false if the index is guaranteed
11940b4e7a6Sdrh ** to be unchanged.  This is an optimization.  False-positives are a
12040b4e7a6Sdrh ** performance degradation, but false-negatives can result in a corrupt
12140b4e7a6Sdrh ** index and incorrect answers.
12240b4e7a6Sdrh **
12340b4e7a6Sdrh ** aXRef[j] will be non-negative if column j of the original table is
12440b4e7a6Sdrh ** being updated.  chngRowid will be true if the rowid of the table is
12540b4e7a6Sdrh ** being updated.
12640b4e7a6Sdrh */
indexWhereClauseMightChange(Index * pIdx,int * aXRef,int chngRowid)12740b4e7a6Sdrh static int indexWhereClauseMightChange(
12840b4e7a6Sdrh   Index *pIdx,      /* The index to check */
12940b4e7a6Sdrh   int *aXRef,       /* aXRef[j]>=0 if column j is being updated */
13040b4e7a6Sdrh   int chngRowid     /* true if the rowid is being updated */
13140b4e7a6Sdrh ){
13240b4e7a6Sdrh   if( pIdx->pPartIdxWhere==0 ) return 0;
13340b4e7a6Sdrh   return sqlite3ExprReferencesUpdatedColumn(pIdx->pPartIdxWhere,
13440b4e7a6Sdrh                                             aXRef, chngRowid);
13540b4e7a6Sdrh }
13640b4e7a6Sdrh 
13740b4e7a6Sdrh /*
138576d5a86Sdan ** Allocate and return a pointer to an expression of type TK_ROW with
139576d5a86Sdan ** Expr.iColumn set to value (iCol+1). The resolver will modify the
140576d5a86Sdan ** expression to be a TK_COLUMN reading column iCol of the first
141576d5a86Sdan ** table in the source-list (pSrc->a[0]).
142576d5a86Sdan */
exprRowColumn(Parse * pParse,int iCol)143576d5a86Sdan static Expr *exprRowColumn(Parse *pParse, int iCol){
144576d5a86Sdan   Expr *pRet = sqlite3PExpr(pParse, TK_ROW, 0, 0);
145576d5a86Sdan   if( pRet ) pRet->iColumn = iCol+1;
146576d5a86Sdan   return pRet;
147576d5a86Sdan }
148576d5a86Sdan 
149576d5a86Sdan /*
150576d5a86Sdan ** Assuming both the pLimit and pOrderBy parameters are NULL, this function
151576d5a86Sdan ** generates VM code to run the query:
15269887c99Sdan **
15369887c99Sdan **   SELECT <other-columns>, pChanges FROM pTabList WHERE pWhere
15469887c99Sdan **
15569887c99Sdan ** and write the results to the ephemeral table already opened as cursor
15669887c99Sdan ** iEph. None of pChanges, pTabList or pWhere are modified or consumed by
15769887c99Sdan ** this function, they must be deleted by the caller.
15869887c99Sdan **
159576d5a86Sdan ** Or, if pLimit and pOrderBy are not NULL, and pTab is not a view:
160576d5a86Sdan **
161576d5a86Sdan **   SELECT <other-columns>, pChanges FROM pTabList
162576d5a86Sdan **   WHERE pWhere
163576d5a86Sdan **   GROUP BY <other-columns>
164576d5a86Sdan **   ORDER BY pOrderBy LIMIT pLimit
165576d5a86Sdan **
166576d5a86Sdan ** If pTab is a view, the GROUP BY clause is omitted.
167576d5a86Sdan **
16869887c99Sdan ** Exactly how results are written to table iEph, and exactly what
16969887c99Sdan ** the <other-columns> in the query above are is determined by the type
17069887c99Sdan ** of table pTabList->a[0].pTab.
17169887c99Sdan **
17269887c99Sdan ** If the table is a WITHOUT ROWID table, then argument pPk must be its
17369887c99Sdan ** PRIMARY KEY. In this case <other-columns> are the primary key columns
17469887c99Sdan ** of the table, in order. The results of the query are written to ephemeral
17569887c99Sdan ** table iEph as index keys, using OP_IdxInsert.
17669887c99Sdan **
17769887c99Sdan ** If the table is actually a view, then <other-columns> are all columns of
17869887c99Sdan ** the view. The results are written to the ephemeral table iEph as records
17969887c99Sdan ** with automatically assigned integer keys.
18069887c99Sdan **
18169887c99Sdan ** If the table is a virtual or ordinary intkey table, then <other-columns>
18269887c99Sdan ** is its rowid. For a virtual table, the results are written to iEph as
18369887c99Sdan ** records with automatically assigned integer keys For intkey tables, the
18469887c99Sdan ** rowid value in <other-columns> is used as the integer key, and the
18569887c99Sdan ** remaining fields make up the table record.
18669887c99Sdan */
updateFromSelect(Parse * pParse,int iEph,Index * pPk,ExprList * pChanges,SrcList * pTabList,Expr * pWhere,ExprList * pOrderBy,Expr * pLimit)187576d5a86Sdan static void updateFromSelect(
18869887c99Sdan   Parse *pParse,                  /* Parse context */
18969887c99Sdan   int iEph,                       /* Cursor for open eph. table */
19069887c99Sdan   Index *pPk,                     /* PK if table 0 is WITHOUT ROWID */
19169887c99Sdan   ExprList *pChanges,             /* List of expressions to return */
19269887c99Sdan   SrcList *pTabList,              /* List of tables to select from */
193f2972b60Sdan   Expr *pWhere,                   /* WHERE clause for query */
194a7c74006Sdrh   ExprList *pOrderBy,             /* ORDER BY clause */
195a7c74006Sdrh   Expr *pLimit                    /* LIMIT clause */
19669887c99Sdan ){
19769887c99Sdan   int i;
19869887c99Sdan   SelectDest dest;
19969887c99Sdan   Select *pSelect = 0;
20069887c99Sdan   ExprList *pList = 0;
201576d5a86Sdan   ExprList *pGrp = 0;
2027e1d9512Sdan   Expr *pLimit2 = 0;
2037e1d9512Sdan   ExprList *pOrderBy2 = 0;
2041e113844Sdan   sqlite3 *db = pParse->db;
2051e113844Sdan   Table *pTab = pTabList->a[0].pTab;
2061e113844Sdan   SrcList *pSrc;
2071e113844Sdan   Expr *pWhere2;
20869887c99Sdan   int eDest;
20969887c99Sdan 
2107e1d9512Sdan #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
2111e113844Sdan   if( pOrderBy && pLimit==0 ) {
2121e113844Sdan     sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on UPDATE");
2131e113844Sdan     return;
2141e113844Sdan   }
2157e1d9512Sdan   pOrderBy2 = sqlite3ExprListDup(db, pOrderBy, 0);
2167e1d9512Sdan   pLimit2 = sqlite3ExprDup(db, pLimit, 0);
217a7c74006Sdrh #else
218a7c74006Sdrh   UNUSED_PARAMETER(pOrderBy);
219a7c74006Sdrh   UNUSED_PARAMETER(pLimit);
2207e1d9512Sdan #endif
2211e113844Sdan 
2221e113844Sdan   pSrc = sqlite3SrcListDup(db, pTabList, 0);
2231e113844Sdan   pWhere2 = sqlite3ExprDup(db, pWhere, 0);
2241e113844Sdan 
22569887c99Sdan   assert( pTabList->nSrc>1 );
22669887c99Sdan   if( pSrc ){
227cd1499f4Sdrh     pSrc->a[0].fg.notCte = 1;
22869887c99Sdan     pSrc->a[0].iCursor = -1;
22969887c99Sdan     pSrc->a[0].pTab->nTabRef--;
23069887c99Sdan     pSrc->a[0].pTab = 0;
23169887c99Sdan   }
23269887c99Sdan   if( pPk ){
23369887c99Sdan     for(i=0; i<pPk->nKeyCol; i++){
234576d5a86Sdan       Expr *pNew = exprRowColumn(pParse, pPk->aiColumn[i]);
2357e1d9512Sdan #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
236f2972b60Sdan       if( pLimit ){
237576d5a86Sdan         pGrp = sqlite3ExprListAppend(pParse, pGrp, sqlite3ExprDup(db, pNew, 0));
238f2972b60Sdan       }
2397e1d9512Sdan #endif
240f2972b60Sdan       pList = sqlite3ExprListAppend(pParse, pList, pNew);
24169887c99Sdan     }
2424d906f1bSdan     eDest = IsVirtual(pTab) ? SRT_Table : SRT_Upfrom;
243f38524d2Sdrh   }else if( IsView(pTab) ){
244576d5a86Sdan     for(i=0; i<pTab->nCol; i++){
245576d5a86Sdan       pList = sqlite3ExprListAppend(pParse, pList, exprRowColumn(pParse, i));
246576d5a86Sdan     }
24769887c99Sdan     eDest = SRT_Table;
24869887c99Sdan   }else{
2499ed322d6Sdan     eDest = IsVirtual(pTab) ? SRT_Table : SRT_Upfrom;
250576d5a86Sdan     pList = sqlite3ExprListAppend(pParse, 0, sqlite3PExpr(pParse,TK_ROW,0,0));
2517e1d9512Sdan #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
252f2972b60Sdan     if( pLimit ){
253576d5a86Sdan       pGrp = sqlite3ExprListAppend(pParse, 0, sqlite3PExpr(pParse,TK_ROW,0,0));
254f2972b60Sdan     }
2557e1d9512Sdan #endif
25669887c99Sdan   }
2572be1f2afSdrh   assert( pChanges!=0 || pParse->db->mallocFailed );
2582be1f2afSdrh   if( pChanges ){
25969887c99Sdan     for(i=0; i<pChanges->nExpr; i++){
26069887c99Sdan       pList = sqlite3ExprListAppend(pParse, pList,
26169887c99Sdan           sqlite3ExprDup(db, pChanges->a[i].pExpr, 0)
26269887c99Sdan       );
26369887c99Sdan     }
2648b023cf5Sdan   }
265243210b7Sdan   pSelect = sqlite3SelectNew(pParse, pList,
2665daf69e5Sdan       pSrc, pWhere2, pGrp, 0, pOrderBy2, SF_UFSrcCheck|SF_IncludeHidden, pLimit2
267f2972b60Sdan   );
2680fb78f0cSdrh   if( pSelect ) pSelect->selFlags |= SF_OrderByReqd;
26969887c99Sdan   sqlite3SelectDestInit(&dest, eDest, iEph);
2709ed322d6Sdan   dest.iSDParm2 = (pPk ? pPk->nKeyCol : -1);
27169887c99Sdan   sqlite3Select(pParse, pSelect, &dest);
27269887c99Sdan   sqlite3SelectDelete(db, pSelect);
27369887c99Sdan }
27469887c99Sdan 
27569887c99Sdan /*
276cce7d176Sdrh ** Process an UPDATE statement.
277b2fe7d8cSdrh **
278243210b7Sdan **   UPDATE OR IGNORE tbl SET a=b, c=d FROM tbl2... WHERE e<5 AND f NOT NULL;
279243210b7Sdan **          \_______/ \_/     \______/      \_____/       \________________/
280243210b7Sdan **           onError   |      pChanges         |                pWhere
281243210b7Sdan **                     \_______________________/
282243210b7Sdan **                               pTabList
283cce7d176Sdrh */
sqlite3Update(Parse * pParse,SrcList * pTabList,ExprList * pChanges,Expr * pWhere,int onError,ExprList * pOrderBy,Expr * pLimit,Upsert * pUpsert)2843b61ebb8Sdan void sqlite3Update(
285cce7d176Sdrh   Parse *pParse,         /* The parser context */
286113088ecSdrh   SrcList *pTabList,     /* The table in which we should change things */
287cce7d176Sdrh   ExprList *pChanges,    /* Things to be changed */
2889cfcf5d4Sdrh   Expr *pWhere,          /* The WHERE clause.  May be null */
289b3c16b89Sdan   int onError,           /* How to handle constraint errors */
2903b61ebb8Sdan   ExprList *pOrderBy,    /* ORDER BY clause. May be null */
291eac9fabbSdrh   Expr *pLimit,          /* LIMIT clause. May be null */
292eac9fabbSdrh   Upsert *pUpsert        /* ON CONFLICT clause, or null */
293cce7d176Sdrh ){
2948a53ce2fSdrh   int i, j, k;           /* Loop counters */
295cce7d176Sdrh   Table *pTab;           /* The table to be updated */
296c3e356feSdrh   int addrTop = 0;       /* VDBE instruction address of the start of the loop */
297aec7dc65Sdrh   WhereInfo *pWInfo = 0; /* Information about the WHERE clause */
298cce7d176Sdrh   Vdbe *v;               /* The virtual database engine */
299cce7d176Sdrh   Index *pIdx;           /* For looping over indices */
300ea22abe3Sdrh   Index *pPk;            /* The PRIMARY KEY index for WITHOUT ROWID tables */
301cce7d176Sdrh   int nIdx;              /* Number of indices that need updating */
3029e9374b2Sdrh   int nAllIdx;           /* Total number of indexes */
3036a53499aSdrh   int iBaseCur;          /* Base cursor number */
30477f64bb7Sdrh   int iDataCur;          /* Cursor for the canonical data btree */
30577f64bb7Sdrh   int iIdxCur;           /* Cursor for the first index */
3069bb575fdSdrh   sqlite3 *db;           /* The database structure */
307a7c3b93fSdrh   int *aRegIdx = 0;      /* Registers for to each index and the main table */
308cce7d176Sdrh   int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
309967e8b73Sdrh                          ** an expression for the i-th column of the table.
310967e8b73Sdrh                          ** aXRef[i]==-1 if the i-th column is not changed. */
3116a53499aSdrh   u8 *aToOpen;           /* 1 for tables and indices to be opened */
312f8ffb278Sdrh   u8 chngPk;             /* PRIMARY KEY changed in a WITHOUT ROWID table */
313f8ffb278Sdrh   u8 chngRowid;          /* Rowid changed in a normal table */
314f8ffb278Sdrh   u8 chngKey;            /* Either chngPk or chngRowid */
315f0863fe5Sdrh   Expr *pRowidExpr = 0;  /* Expression defining the new record number */
316243210b7Sdan   int iRowidExpr = -1;   /* Index of "rowid=" (or IPK) assignment in pChanges */
31785e2096fSdrh   AuthContext sContext;  /* The authorization context */
318b3bce662Sdanielk1977   NameContext sNC;       /* The name-context to resolve expressions in */
319da184236Sdanielk1977   int iDb;               /* Database containing the table being updated */
320f91c1318Sdan   int eOnePass;          /* ONEPASS_XXX value from where.c */
3211da40a38Sdan   int hasFK;             /* True if foreign key processing is required */
322ea22abe3Sdrh   int labelBreak;        /* Jump here to break out of UPDATE loop */
323ea22abe3Sdrh   int labelContinue;     /* Jump here to continue next step of UPDATE loop */
324f91c1318Sdan   int flags;             /* Flags for sqlite3WhereBegin() */
325cce7d176Sdrh 
326798da52cSdrh #ifndef SQLITE_OMIT_TRIGGER
327bb5f168fSdan   int isView;            /* True when updating a view (INSTEAD OF trigger) */
3282f886d1dSdanielk1977   Trigger *pTrigger;     /* List of triggers on pTab, if required */
329bb5f168fSdan   int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
330798da52cSdrh #endif
331fd7c9912Sdrh   int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
332ea22abe3Sdrh   int iEph = 0;          /* Ephemeral table holding all primary key values */
33300f91cf5Sdrh   int nKey = 0;          /* Number of elements in regKey for WITHOUT ROWID */
334fc8d4f96Sdrh   int aiCurOnePass[2];   /* The write cursors opened by WHERE_ONEPASS */
335ae051a89Sdrh   int addrOpen = 0;      /* Address of OP_OpenEphemeral */
336ae051a89Sdrh   int iPk = 0;           /* First of nPk cells holding PRIMARY KEY value */
337ae051a89Sdrh   i16 nPk = 0;           /* Number of components of the PRIMARY KEY */
3382c6fec21Sdan   int bReplace = 0;      /* True if REPLACE conflict resolution might happen */
339be3da241Sdrh   int bFinishSeek = 1;   /* The OP_FinishSeek opcode is needed */
340243210b7Sdan   int nChangeFrom = 0;   /* If there is a FROM, pChanges->nExpr, else 0 */
341c3f9bad2Sdanielk1977 
34204adf416Sdrh   /* Register Allocations */
34304adf416Sdrh   int regRowCount = 0;   /* A count of rows changed */
34494f26a1eSdrh   int regOldRowid = 0;   /* The old rowid */
34594f26a1eSdrh   int regNewRowid = 0;   /* The new rowid */
34694f26a1eSdrh   int regNew = 0;        /* Content of the NEW.* table in triggers */
347b8475df8Sdrh   int regOld = 0;        /* Content of OLD.* table in triggers */
3484f21c4afSdrh   int regRowSet = 0;     /* Rowset of rows to be updated */
349ea22abe3Sdrh   int regKey = 0;        /* composite PRIMARY KEY value */
35004adf416Sdrh 
351eeb844a7Sdrh   memset(&sContext, 0, sizeof(sContext));
35217435752Sdrh   db = pParse->db;
3530c7d3d39Sdrh   assert( db->pParse==pParse );
3540c7d3d39Sdrh   if( pParse->nErr ){
3556f7adc8aSdrh     goto update_cleanup;
3566f7adc8aSdrh   }
3570c7d3d39Sdrh   assert( db->mallocFailed==0 );
358daffd0e5Sdrh 
359b2fe7d8cSdrh   /* Locate the table which we want to update.
360cce7d176Sdrh   */
3614adee20fSdanielk1977   pTab = sqlite3SrcListLookup(pParse, pTabList);
362a69d9168Sdrh   if( pTab==0 ) goto update_cleanup;
363da184236Sdanielk1977   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
364b7f9164eSdrh 
365b7f9164eSdrh   /* Figure out if we have any triggers and if the table being
36676d462eeSdan   ** updated is a view.
367b7f9164eSdrh   */
368b7f9164eSdrh #ifndef SQLITE_OMIT_TRIGGER
369bb5f168fSdan   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
370f38524d2Sdrh   isView = IsView(pTab);
371bb5f168fSdan   assert( pTrigger || tmask==0 );
372b7f9164eSdrh #else
3732f886d1dSdanielk1977 # define pTrigger 0
374b7f9164eSdrh # define isView 0
375bb5f168fSdan # define tmask 0
376b7f9164eSdrh #endif
377b7f9164eSdrh #ifdef SQLITE_OMIT_VIEW
378b7f9164eSdrh # undef isView
379b7f9164eSdrh # define isView 0
380b7f9164eSdrh #endif
381243210b7Sdan 
3822a7dcbfbSdrh #if TREETRACE_ENABLED
3832a7dcbfbSdrh   if( sqlite3TreeTrace & 0x10000 ){
3842a7dcbfbSdrh     sqlite3TreeViewLine(0, "In sqlite3Update() at %s:%d", __FILE__, __LINE__);
3852a7dcbfbSdrh     sqlite3TreeViewUpdate(pParse->pWith, pTabList, pChanges, pWhere,
3862a7dcbfbSdrh                           onError, pOrderBy, pLimit, pUpsert, pTrigger);
3872a7dcbfbSdrh   }
3882a7dcbfbSdrh #endif
3892a7dcbfbSdrh 
390243210b7Sdan   /* If there was a FROM clause, set nChangeFrom to the number of expressions
391243210b7Sdan   ** in the change-list. Otherwise, set it to 0. There cannot be a FROM
392243210b7Sdan   ** clause if this function is being called to generate code for part of
393243210b7Sdan   ** an UPSERT statement.  */
39469887c99Sdan   nChangeFrom = (pTabList->nSrc>1) ? pChanges->nExpr : 0;
39569887c99Sdan   assert( nChangeFrom==0 || pUpsert==0 );
396b7f9164eSdrh 
397b3c16b89Sdan #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
398f2972b60Sdan   if( !isView && nChangeFrom==0 ){
399b3c16b89Sdan     pWhere = sqlite3LimitWhere(
4008c0833fbSdrh         pParse, pTabList, pWhere, pOrderBy, pLimit, "UPDATE"
401b3c16b89Sdan     );
402b3c16b89Sdan     pOrderBy = 0;
4038c0833fbSdrh     pLimit = 0;
404b3c16b89Sdan   }
405b3c16b89Sdan #endif
406b3c16b89Sdan 
407595a523aSdanielk1977   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
4085cf590c1Sdrh     goto update_cleanup;
409a69d9168Sdrh   }
410bb5f168fSdan   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
4115cf590c1Sdrh     goto update_cleanup;
4125cf590c1Sdrh   }
413cce7d176Sdrh 
41453e3fc70Sdrh   /* Allocate a cursors for the main database table and for all indices.
41553e3fc70Sdrh   ** The index cursors might not be used, but if they are used they
41653e3fc70Sdrh   ** need to occur right after the database cursor.  So go ahead and
41753e3fc70Sdrh   ** allocate enough space, just in case.
41853e3fc70Sdrh   */
4192ac4e5ccSdrh   iBaseCur = iDataCur = pParse->nTab++;
420313619f5Sdrh   iIdxCur = iDataCur+1;
42177f64bb7Sdrh   pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
4222ac4e5ccSdrh   testcase( pPk!=0 && pPk!=pTab->pIndex );
42377f64bb7Sdrh   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
4242ac4e5ccSdrh     if( pPk==pIdx ){
425313619f5Sdrh       iDataCur = pParse->nTab;
426313619f5Sdrh     }
42753e3fc70Sdrh     pParse->nTab++;
42853e3fc70Sdrh   }
4297fc3aba8Sdrh   if( pUpsert ){
430fb2213e1Sdrh     /* On an UPSERT, reuse the same cursors already opened by INSERT */
4317fc3aba8Sdrh     iDataCur = pUpsert->iDataCur;
4327fc3aba8Sdrh     iIdxCur = pUpsert->iIdxCur;
4337fc3aba8Sdrh     pParse->nTab = iBaseCur;
4347fc3aba8Sdrh   }
4352ac4e5ccSdrh   pTabList->a[0].iCursor = iDataCur;
43653e3fc70Sdrh 
4376a53499aSdrh   /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].
4386a53499aSdrh   ** Initialize aXRef[] and aToOpen[] to their default values.
4396a53499aSdrh   */
440a7c3b93fSdrh   aXRef = sqlite3DbMallocRawNN(db, sizeof(int) * (pTab->nCol+nIdx+1) + nIdx+2 );
4416a53499aSdrh   if( aXRef==0 ) goto update_cleanup;
4426a53499aSdrh   aRegIdx = aXRef+pTab->nCol;
443a7c3b93fSdrh   aToOpen = (u8*)(aRegIdx+nIdx+1);
4446a53499aSdrh   memset(aToOpen, 1, nIdx+1);
4456a53499aSdrh   aToOpen[nIdx+1] = 0;
4466a53499aSdrh   for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
4476a53499aSdrh 
448b3bce662Sdanielk1977   /* Initialize the name-context */
449b3bce662Sdanielk1977   memset(&sNC, 0, sizeof(sNC));
450b3bce662Sdanielk1977   sNC.pParse = pParse;
451b3bce662Sdanielk1977   sNC.pSrcList = pTabList;
452eac9fabbSdrh   sNC.uNC.pUpsert = pUpsert;
453eac9fabbSdrh   sNC.ncFlags = NC_UUpsert;
454b3bce662Sdanielk1977 
45516fd04cdSmistachkin   /* Begin generating code. */
45616fd04cdSmistachkin   v = sqlite3GetVdbe(pParse);
45716fd04cdSmistachkin   if( v==0 ) goto update_cleanup;
45816fd04cdSmistachkin 
45985e2096fSdrh   /* Resolve the column names in all the expressions of the
46085e2096fSdrh   ** of the UPDATE statement.  Also find the column index
461ed6c8671Sdrh   ** for each column to be updated in the pChanges array.  For each
462ed6c8671Sdrh   ** column to be updated, make sure we have authorization to change
463ed6c8671Sdrh   ** that column.
464cce7d176Sdrh   */
465f8ffb278Sdrh   chngRowid = chngPk = 0;
466cce7d176Sdrh   for(i=0; i<pChanges->nExpr; i++){
467cf9d36d1Sdrh     u8 hCol = sqlite3StrIHash(pChanges->a[i].zEName);
46869887c99Sdan     /* If this is an UPDATE with a FROM clause, do not resolve expressions
46969887c99Sdan     ** here. The call to sqlite3Select() below will do that. */
47069887c99Sdan     if( nChangeFrom==0 && sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
471cce7d176Sdrh       goto update_cleanup;
472cce7d176Sdrh     }
473cce7d176Sdrh     for(j=0; j<pTab->nCol; j++){
474cf9d36d1Sdrh       if( pTab->aCol[j].hName==hCol
475cf9d36d1Sdrh        && sqlite3StrICmp(pTab->aCol[j].zCnName, pChanges->a[i].zEName)==0
476cf9d36d1Sdrh       ){
4779647ff85Sdrh         if( j==pTab->iPKey ){
478f0863fe5Sdrh           chngRowid = 1;
479f0863fe5Sdrh           pRowidExpr = pChanges->a[i].pExpr;
4807465787bSdan           iRowidExpr = i;
481f8ffb278Sdrh         }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
482f8ffb278Sdrh           chngPk = 1;
4834a32431cSdrh         }
4848a53ce2fSdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS
485427b96aeSdrh         else if( pTab->aCol[j].colFlags & COLFLAG_GENERATED ){
4866ab61d70Sdrh           testcase( pTab->aCol[j].colFlags & COLFLAG_VIRTUAL );
4876ab61d70Sdrh           testcase( pTab->aCol[j].colFlags & COLFLAG_STORED );
4888a53ce2fSdrh           sqlite3ErrorMsg(pParse,
4898a53ce2fSdrh              "cannot UPDATE generated column \"%s\"",
490cf9d36d1Sdrh              pTab->aCol[j].zCnName);
4918a53ce2fSdrh           goto update_cleanup;
4928a53ce2fSdrh         }
4938a53ce2fSdrh #endif
494cce7d176Sdrh         aXRef[j] = i;
495cce7d176Sdrh         break;
496cce7d176Sdrh       }
497cce7d176Sdrh     }
498cce7d176Sdrh     if( j>=pTab->nCol ){
49941cee668Sdrh       if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zEName) ){
5002722898cSdrh         j = -1;
501f0863fe5Sdrh         chngRowid = 1;
502f0863fe5Sdrh         pRowidExpr = pChanges->a[i].pExpr;
5037465787bSdan         iRowidExpr = i;
504a0217ba7Sdrh       }else{
50541cee668Sdrh         sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zEName);
5061db95106Sdan         pParse->checkSchema = 1;
507cce7d176Sdrh         goto update_cleanup;
508cce7d176Sdrh       }
509a0217ba7Sdrh     }
510ed6c8671Sdrh #ifndef SQLITE_OMIT_AUTHORIZATION
511e5f9c644Sdrh     {
512e5f9c644Sdrh       int rc;
5134adee20fSdanielk1977       rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
514cf9d36d1Sdrh                             j<0 ? "ROWID" : pTab->aCol[j].zCnName,
51569c33826Sdrh                             db->aDb[iDb].zDbSName);
516e5f9c644Sdrh       if( rc==SQLITE_DENY ){
517e5f9c644Sdrh         goto update_cleanup;
518e5f9c644Sdrh       }else if( rc==SQLITE_IGNORE ){
519ed6c8671Sdrh         aXRef[j] = -1;
520ed6c8671Sdrh       }
521e5f9c644Sdrh     }
522ed6c8671Sdrh #endif
523cce7d176Sdrh   }
524f8ffb278Sdrh   assert( (chngRowid & chngPk)==0 );
525f8ffb278Sdrh   assert( chngRowid==0 || chngRowid==1 );
526f8ffb278Sdrh   assert( chngPk==0 || chngPk==1 );
527f8ffb278Sdrh   chngKey = chngRowid + chngPk;
528cce7d176Sdrh 
5297e7fd73bSdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS
5307e7fd73bSdrh   /* Mark generated columns as changing if their generator expressions
5317e7fd73bSdrh   ** reference any changing column.  The actual aXRef[] value for
5327e7fd73bSdrh   ** generated expressions is not used, other than to check to see that it
5337e7fd73bSdrh   ** is non-negative, so the value of aXRef[] for generated columns can be
5347e7fd73bSdrh   ** set to any non-negative number.  We use 99999 so that the value is
5357e7fd73bSdrh   ** obvious when looking at aXRef[] in a symbolic debugger.
5367e7fd73bSdrh   */
5377e7fd73bSdrh   if( pTab->tabFlags & TF_HasGenerated ){
5387e7fd73bSdrh     int bProgress;
5397e7fd73bSdrh     testcase( pTab->tabFlags & TF_HasVirtual );
5407e7fd73bSdrh     testcase( pTab->tabFlags & TF_HasStored );
5417e7fd73bSdrh     do{
5427e7fd73bSdrh       bProgress = 0;
5437e7fd73bSdrh       for(i=0; i<pTab->nCol; i++){
5447e7fd73bSdrh         if( aXRef[i]>=0 ) continue;
5457e7fd73bSdrh         if( (pTab->aCol[i].colFlags & COLFLAG_GENERATED)==0 ) continue;
54679cf2b71Sdrh         if( sqlite3ExprReferencesUpdatedColumn(
54779cf2b71Sdrh                 sqlite3ColumnExpr(pTab, &pTab->aCol[i]),
54879cf2b71Sdrh                  aXRef, chngRowid)
54979cf2b71Sdrh         ){
5507e7fd73bSdrh           aXRef[i] = 99999;
5517e7fd73bSdrh           bProgress = 1;
5527e7fd73bSdrh         }
5537e7fd73bSdrh       }
5547e7fd73bSdrh     }while( bProgress );
5557e7fd73bSdrh   }
5567e7fd73bSdrh #endif
5577e7fd73bSdrh 
5585c82f4dfSdrh   /* The SET expressions are not actually used inside the WHERE loop.
5591acb539fSdan   ** So reset the colUsed mask. Unless this is a virtual table. In that
5601acb539fSdan   ** case, set all bits of the colUsed mask (to ensure that the virtual
5611acb539fSdan   ** table implementation makes all columns available).
5625c82f4dfSdrh   */
5638426e36cSdrh   pTabList->a[0].colUsed = IsVirtual(pTab) ? ALLBITS : 0;
5645c82f4dfSdrh 
565f8ffb278Sdrh   hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
566e7a94d81Sdan 
5676a53499aSdrh   /* There is one entry in the aRegIdx[] array for each index on the table
5686a53499aSdrh   ** being updated.  Fill in aRegIdx[] with a register number that will hold
5696a53499aSdrh   ** the key for accessing each index.
570cce7d176Sdrh   */
571247c1b4aSdrh   if( onError==OE_Replace ) bReplace = 1;
5729e9374b2Sdrh   for(nAllIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nAllIdx++){
573aa9b8963Sdrh     int reg;
57440b4e7a6Sdrh     if( chngKey || hasFK>1 || pIdx==pPk
57540b4e7a6Sdrh      || indexWhereClauseMightChange(pIdx,aXRef,chngRowid)
57640b4e7a6Sdrh     ){
577aa9b8963Sdrh       reg = ++pParse->nMem;
5782c4dfc30Sdrh       pParse->nMem += pIdx->nColumn;
5794a32431cSdrh     }else{
580aa9b8963Sdrh       reg = 0;
581f8ffb278Sdrh       for(i=0; i<pIdx->nKeyCol; i++){
5822b7cdf6fSdrh         if( indexColumnIsBeingUpdated(pIdx, i, aXRef, chngRowid) ){
583aa9b8963Sdrh           reg = ++pParse->nMem;
5842c4dfc30Sdrh           pParse->nMem += pIdx->nColumn;
585247c1b4aSdrh           if( onError==OE_Default && pIdx->onError==OE_Replace ){
5862c6fec21Sdan             bReplace = 1;
5872c6fec21Sdan           }
588aa9b8963Sdrh           break;
589cce7d176Sdrh         }
5904a32431cSdrh       }
591cce7d176Sdrh     }
5929e9374b2Sdrh     if( reg==0 ) aToOpen[nAllIdx+1] = 0;
5939e9374b2Sdrh     aRegIdx[nAllIdx] = reg;
594cce7d176Sdrh   }
5959e9374b2Sdrh   aRegIdx[nAllIdx] = ++pParse->nMem;  /* Register storing the table record */
5962c6fec21Sdan   if( bReplace ){
5972c6fec21Sdan     /* If REPLACE conflict resolution might be invoked, open cursors on all
5982c6fec21Sdan     ** indexes in case they are needed to delete records.  */
5992c6fec21Sdan     memset(aToOpen, 1, nIdx+1);
6002c6fec21Sdan   }
601cce7d176Sdrh 
6024794f735Sdrh   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
603ac9151d8Sdrh   sqlite3BeginWriteOperation(pParse, pTrigger || hasFK, iDb);
604cce7d176Sdrh 
605165921a7Sdan   /* Allocate required registers. */
6060f40037eSdan   if( !IsVirtual(pTab) ){
6079e9374b2Sdrh     /* For now, regRowSet and aRegIdx[nAllIdx] share the same register.
6089e9374b2Sdrh     ** If regRowSet turns out to be needed, then aRegIdx[nAllIdx] will be
6099e9374b2Sdrh     ** reallocated.  aRegIdx[nAllIdx] is the register in which the main
6109e9374b2Sdrh     ** table record is written.  regRowSet holds the RowSet for the
6119e9374b2Sdrh     ** two-pass update algorithm. */
6129e9374b2Sdrh     assert( aRegIdx[nAllIdx]==pParse->nMem );
6139e9374b2Sdrh     regRowSet = aRegIdx[nAllIdx];
614165921a7Sdan     regOldRowid = regNewRowid = ++pParse->nMem;
615f8ffb278Sdrh     if( chngPk || pTrigger || hasFK ){
616165921a7Sdan       regOld = pParse->nMem + 1;
617165921a7Sdan       pParse->nMem += pTab->nCol;
618165921a7Sdan     }
619f8ffb278Sdrh     if( chngKey || pTrigger || hasFK ){
620165921a7Sdan       regNewRowid = ++pParse->nMem;
621165921a7Sdan     }
622165921a7Sdan     regNew = pParse->nMem + 1;
623165921a7Sdan     pParse->nMem += pTab->nCol;
6240f40037eSdan   }
625165921a7Sdan 
626165921a7Sdan   /* Start the view context. */
6274273deaeSdanielk1977   if( isView ){
6284273deaeSdanielk1977     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
6294273deaeSdanielk1977   }
6304273deaeSdanielk1977 
6319d2985c7Sdrh   /* If we are trying to update a view, realize that view into
63260ec914cSpeter.d.reid   ** an ephemeral table.
6335cf590c1Sdrh   */
634fa4e62f3Sshane #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
63569887c99Sdan   if( nChangeFrom==0 && isView ){
636b3c16b89Sdan     sqlite3MaterializeView(pParse, pTab,
6378c0833fbSdrh         pWhere, pOrderBy, pLimit, iDataCur
638b3c16b89Sdan     );
639b3c16b89Sdan     pOrderBy = 0;
6408c0833fbSdrh     pLimit = 0;
6410f35a6b5Sdrh   }
642fa4e62f3Sshane #endif
6431013c932Sdrh 
6440f35a6b5Sdrh   /* Resolve the column names in all the expressions in the
6450f35a6b5Sdrh   ** WHERE clause.
6460f35a6b5Sdrh   */
64769887c99Sdan   if( nChangeFrom==0 && sqlite3ResolveExprNames(&sNC, pWhere) ){
6480f35a6b5Sdrh     goto update_cleanup;
6495cf590c1Sdrh   }
6505cf590c1Sdrh 
6510f40037eSdan #ifndef SQLITE_OMIT_VIRTUALTABLE
6520f40037eSdan   /* Virtual tables must be handled separately */
6530f40037eSdan   if( IsVirtual(pTab) ){
6540f40037eSdan     updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
6550f40037eSdan                        pWhere, onError);
6560f40037eSdan     goto update_cleanup;
6570f40037eSdan   }
6580f40037eSdan #endif
6590f40037eSdan 
660fb2213e1Sdrh   /* Jump to labelBreak to abandon further processing of this UPDATE */
661ec4ccdbcSdrh   labelContinue = labelBreak = sqlite3VdbeMakeLabel(pParse);
662fb2213e1Sdrh 
663fb2213e1Sdrh   /* Not an UPSERT.  Normal processing.  Begin by
664fb2213e1Sdrh   ** initialize the count of updated rows */
66579636913Sdrh   if( (db->flags&SQLITE_CountRows)!=0
66679636913Sdrh    && !pParse->pTriggerTab
66779636913Sdrh    && !pParse->nested
668d086aa0aSdrh    && !pParse->bReturning
6695deb1813Sdrh    && pUpsert==0
67079636913Sdrh   ){
671f91c1318Sdan     regRowCount = ++pParse->nMem;
672f91c1318Sdan     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
6733d4501e5Sdrh   }
674cce7d176Sdrh 
67569887c99Sdan   if( nChangeFrom==0 && HasRowid(pTab) ){
676f91c1318Sdan     sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
677ea248720Sdrh     iEph = pParse->nTab++;
67832881bebSdrh     addrOpen = sqlite3VdbeAddOp3(v, OP_OpenEphemeral, iEph, 0, regRowSet);
679ea22abe3Sdrh   }else{
68069887c99Sdan     assert( pPk!=0 || HasRowid(pTab) );
68169887c99Sdan     nPk = pPk ? pPk->nKeyCol : 0;
682ea22abe3Sdrh     iPk = pParse->nMem+1;
683ea22abe3Sdrh     pParse->nMem += nPk;
68469887c99Sdan     pParse->nMem += nChangeFrom;
685ea22abe3Sdrh     regKey = ++pParse->nMem;
6865deb1813Sdrh     if( pUpsert==0 ){
68769887c99Sdan       int nEphCol = nPk + nChangeFrom + (isView ? pTab->nCol : 0);
688ea22abe3Sdrh       iEph = pParse->nTab++;
68969887c99Sdan       if( pPk ) sqlite3VdbeAddOp3(v, OP_Null, 0, iPk, iPk+nPk-1);
69069887c99Sdan       addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nEphCol);
691be952c11Sdan       if( pPk ){
692be952c11Sdan         KeyInfo *pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pPk);
693be952c11Sdan         if( pKeyInfo ){
694be952c11Sdan           pKeyInfo->nAllField = nEphCol;
695be952c11Sdan           sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
696be952c11Sdan         }
697be952c11Sdan       }
69869887c99Sdan       if( nChangeFrom ){
699576d5a86Sdan         updateFromSelect(
700f2972b60Sdan             pParse, iEph, pPk, pChanges, pTabList, pWhere, pOrderBy, pLimit
701f2972b60Sdan         );
70269887c99Sdan #ifndef SQLITE_OMIT_SUBQUERY
70369887c99Sdan         if( isView ) iDataCur = iEph;
70469887c99Sdan #endif
70569887c99Sdan       }
706f91c1318Sdan     }
7075deb1813Sdrh   }
708f91c1318Sdan 
70969887c99Sdan   if( nChangeFrom ){
71069887c99Sdan     sqlite3MultiWrite(pParse);
71169887c99Sdan     eOnePass = ONEPASS_OFF;
7127465787bSdan     nKey = nPk;
7137465787bSdan     regKey = iPk;
71469887c99Sdan   }else{
7155deb1813Sdrh     if( pUpsert ){
7165deb1813Sdrh       /* If this is an UPSERT, then all cursors have already been opened by
7175deb1813Sdrh       ** the outer INSERT and the data cursor should be pointing at the row
7185deb1813Sdrh       ** that is to be updated.  So bypass the code that searches for the
7195deb1813Sdrh       ** row(s) to be updated.
7205deb1813Sdrh       */
7215deb1813Sdrh       pWInfo = 0;
7225deb1813Sdrh       eOnePass = ONEPASS_SINGLE;
7235deb1813Sdrh       sqlite3ExprIfFalse(pParse, pWhere, labelBreak, SQLITE_JUMPIFNULL);
724be3da241Sdrh       bFinishSeek = 0;
7255deb1813Sdrh     }else{
7262c6fec21Sdan       /* Begin the database scan.
7272c6fec21Sdan       **
7282c6fec21Sdan       ** Do not consider a single-pass strategy for a multi-row update if
7292c6fec21Sdan       ** there are any triggers or foreign keys to process, or rows may
7302c6fec21Sdan       ** be deleted as a result of REPLACE conflict handling. Any of these
7312c6fec21Sdan       ** things might disturb a cursor being used to scan through the table
7322c6fec21Sdan       ** or index, causing a single-pass approach to malfunction.  */
73368c0c710Sdrh       flags = WHERE_ONEPASS_DESIRED;
7342c6fec21Sdan       if( !pParse->nested && !pTrigger && !hasFK && !chngKey && !bReplace ){
735f91c1318Sdan         flags |= WHERE_ONEPASS_MULTIROW;
736f91c1318Sdan       }
737895bab33Sdrh       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0,0,0,flags,iIdxCur);
738ea22abe3Sdrh       if( pWInfo==0 ) goto update_cleanup;
739f91c1318Sdan 
740f91c1318Sdan       /* A one-pass strategy that might update more than one row may not
741f91c1318Sdan       ** be used if any column of the index used for the scan is being
742f91c1318Sdan       ** updated. Otherwise, if there is an index on "b", statements like
743f91c1318Sdan       ** the following could create an infinite loop:
744f91c1318Sdan       **
745f91c1318Sdan       **   UPDATE t1 SET b=b+1 WHERE b>?
746f91c1318Sdan       **
747f91c1318Sdan       ** Fall back to ONEPASS_OFF if where.c has selected a ONEPASS_MULTI
748f91c1318Sdan       ** strategy that uses an index for which one or more columns are being
749f91c1318Sdan       ** updated.  */
750f91c1318Sdan       eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
751be3da241Sdrh       bFinishSeek = sqlite3WhereUsesDeferredSeek(pWInfo);
752ac9151d8Sdrh       if( eOnePass!=ONEPASS_SINGLE ){
753ac9151d8Sdrh         sqlite3MultiWrite(pParse);
754f91c1318Sdan         if( eOnePass==ONEPASS_MULTI ){
755f91c1318Sdan           int iCur = aiCurOnePass[1];
756372f942fSdan           if( iCur>=0 && iCur!=iDataCur && aToOpen[iCur-iBaseCur] ){
757372f942fSdan             eOnePass = ONEPASS_OFF;
758372f942fSdan           }
759372f942fSdan           assert( iCur!=iDataCur || !HasRowid(pTab) );
760f91c1318Sdan         }
761fb2213e1Sdrh       }
762ac9151d8Sdrh     }
763f91c1318Sdan 
764f91c1318Sdan     if( HasRowid(pTab) ){
765f91c1318Sdan       /* Read the rowid of the current row of the WHERE scan. In ONEPASS_OFF
766f91c1318Sdan       ** mode, write the rowid into the FIFO. In either of the one-pass modes,
767f91c1318Sdan       ** leave it in register regOldRowid.  */
768f91c1318Sdan       sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
769f91c1318Sdan       if( eOnePass==ONEPASS_OFF ){
7709e9374b2Sdrh         aRegIdx[nAllIdx] = ++pParse->nMem;
771ea248720Sdrh         sqlite3VdbeAddOp3(v, OP_Insert, iEph, regRowSet, regOldRowid);
772ea248720Sdrh       }else{
77332881bebSdrh         if( ALWAYS(addrOpen) ) sqlite3VdbeChangeToNoop(v, addrOpen);
774f91c1318Sdan       }
775f91c1318Sdan     }else{
776f91c1318Sdan       /* Read the PK of the current row into an array of registers. In
777f91c1318Sdan       ** ONEPASS_OFF mode, serialize the array into a record and store it in
778f91c1318Sdan       ** the ephemeral table. Or, in ONEPASS_SINGLE or MULTI mode, change
779f91c1318Sdan       ** the OP_OpenEphemeral instruction to a Noop (the ephemeral table
780f91c1318Sdan       ** is not required) and leave the PK fields in the array of registers.  */
781ea22abe3Sdrh       for(i=0; i<nPk; i++){
7824b92f98cSdrh         assert( pPk->aiColumn[i]>=0 );
7836df9c4b9Sdrh         sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur,
78481f7b372Sdrh                                         pPk->aiColumn[i], iPk+i);
785ea22abe3Sdrh       }
786f91c1318Sdan       if( eOnePass ){
787fb2213e1Sdrh         if( addrOpen ) sqlite3VdbeChangeToNoop(v, addrOpen);
788702ba9f2Sdrh         nKey = nPk;
789702ba9f2Sdrh         regKey = iPk;
790702ba9f2Sdrh       }else{
791ea22abe3Sdrh         sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
792e9107698Sdrh                           sqlite3IndexAffinityStr(db, pPk), nPk);
7939b4eaebcSdrh         sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEph, regKey, iPk, nPk);
794702ba9f2Sdrh       }
795ea22abe3Sdrh     }
79669887c99Sdan   }
797cce7d176Sdrh 
798fb2213e1Sdrh   if( pUpsert==0 ){
79969887c99Sdan     if( nChangeFrom==0 && eOnePass!=ONEPASS_MULTI ){
800f91c1318Sdan       sqlite3WhereEnd(pWInfo);
8011bee3d7bSdrh     }
8021bee3d7bSdrh 
803fb2213e1Sdrh     if( !isView ){
8042c6fec21Sdan       int addrOnce = 0;
8052c6fec21Sdan 
8062c6fec21Sdan       /* Open every index that needs updating. */
807f91c1318Sdan       if( eOnePass!=ONEPASS_OFF ){
8086a53499aSdrh         if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
8096a53499aSdrh         if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
810fc8d4f96Sdrh       }
811f91c1318Sdan 
812f91c1318Sdan       if( eOnePass==ONEPASS_MULTI && (nIdx-(aiCurOnePass[1]>=0))>0 ){
8132c6fec21Sdan         addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
814f91c1318Sdan       }
815fb2213e1Sdrh       sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, iBaseCur,
816fb2213e1Sdrh                                  aToOpen, 0, 0);
817dc4f6fc0Sdrh       if( addrOnce ){
818dc4f6fc0Sdrh         sqlite3VdbeJumpHereOrPopInst(v, addrOnce);
819dc4f6fc0Sdrh       }
820e448dc4aSdanielk1977     }
821e448dc4aSdanielk1977 
822e448dc4aSdanielk1977     /* Top of the update loop */
823f91c1318Sdan     if( eOnePass!=ONEPASS_OFF ){
8246e5020e8Sdrh       if( aiCurOnePass[0]!=iDataCur
8256e5020e8Sdrh        && aiCurOnePass[1]!=iDataCur
8266e5020e8Sdrh #ifdef SQLITE_ALLOW_ROWID_IN_VIEW
8276e5020e8Sdrh        && !isView
8286e5020e8Sdrh #endif
8296e5020e8Sdrh       ){
830dd8c4600Sdan         assert( pPk );
8316a53499aSdrh         sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey,nKey);
8326ccbd278Sdrh         VdbeCoverage(v);
8336a53499aSdrh       }
8344b8bd843Sdrh       if( eOnePass!=ONEPASS_SINGLE ){
835ec4ccdbcSdrh         labelContinue = sqlite3VdbeMakeLabel(pParse);
836f91c1318Sdan       }
837702ba9f2Sdrh       sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
8382c3ea069Sdrh       VdbeCoverageIf(v, pPk==0);
8392c3ea069Sdrh       VdbeCoverageIf(v, pPk!=0);
84069887c99Sdan     }else if( pPk || nChangeFrom ){
841ec4ccdbcSdrh       labelContinue = sqlite3VdbeMakeLabel(pParse);
842688852abSdrh       sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
84369887c99Sdan       addrTop = sqlite3VdbeCurrentAddr(v);
84469887c99Sdan       if( nChangeFrom ){
84569887c99Sdan         if( !isView ){
84669887c99Sdan           if( pPk ){
84769887c99Sdan             for(i=0; i<nPk; i++){
84869887c99Sdan               sqlite3VdbeAddOp3(v, OP_Column, iEph, i, iPk+i);
84969887c99Sdan             }
85069887c99Sdan             sqlite3VdbeAddOp4Int(
85169887c99Sdan                 v, OP_NotFound, iDataCur, labelContinue, iPk, nPk
8526265c47aSdrh             ); VdbeCoverage(v);
85369887c99Sdan           }else{
85469887c99Sdan             sqlite3VdbeAddOp2(v, OP_Rowid, iEph, regOldRowid);
85569887c99Sdan             sqlite3VdbeAddOp3(
85669887c99Sdan                 v, OP_NotExists, iDataCur, labelContinue, regOldRowid
8576265c47aSdrh             ); VdbeCoverage(v);
85869887c99Sdan           }
85969887c99Sdan         }
86069887c99Sdan       }else{
86169887c99Sdan         sqlite3VdbeAddOp2(v, OP_RowData, iEph, regKey);
862313619f5Sdrh         sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey,0);
863688852abSdrh         VdbeCoverage(v);
86469887c99Sdan       }
86508c88eb0Sdrh     }else{
866ea248720Sdrh       sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
867ea248720Sdrh       labelContinue = sqlite3VdbeMakeLabel(pParse);
868ea248720Sdrh       addrTop = sqlite3VdbeAddOp2(v, OP_Rowid, iEph, regOldRowid);
869688852abSdrh       VdbeCoverage(v);
870c3e356feSdrh       sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
871688852abSdrh       VdbeCoverage(v);
87208c88eb0Sdrh     }
873fb2213e1Sdrh   }
874c3f9bad2Sdanielk1977 
8757007640fSdrh   /* If the rowid value will change, set register regNewRowid to
8767007640fSdrh   ** contain the new value. If the rowid is not being modified,
8771da40a38Sdan   ** then regNewRowid is the same register as regOldRowid, which is
8781da40a38Sdan   ** already populated.  */
879f8ffb278Sdrh   assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
8801da40a38Sdan   if( chngRowid ){
8817465787bSdan     assert( iRowidExpr>=0 );
8827465787bSdan     if( nChangeFrom==0 ){
8831da40a38Sdan       sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
8847465787bSdan     }else{
8857465787bSdan       sqlite3VdbeAddOp3(v, OP_Column, iEph, iRowidExpr, regNewRowid);
8867465787bSdan     }
887688852abSdrh     sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
8881da40a38Sdan   }
8891da40a38Sdan 
890f8ffb278Sdrh   /* Compute the old pre-UPDATE content of the row being changed, if that
891f8ffb278Sdrh   ** information is needed */
892f8ffb278Sdrh   if( chngPk || hasFK || pTrigger ){
893e7a94d81Sdan     u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
894bb5f168fSdan     oldmask |= sqlite3TriggerColmask(pParse,
895bb5f168fSdan         pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
896bb5f168fSdan     );
897ff37c407Sdrh     for(i=0; i<pTab->nCol; i++){
8988a53ce2fSdrh       u32 colFlags = pTab->aCol[i].colFlags;
899ff37c407Sdrh       k = sqlite3TableColumnToStorage(pTab, i) + regOld;
900f8ffb278Sdrh       if( oldmask==0xffffffff
901693e6719Sdrh        || (i<32 && (oldmask & MASKBIT32(i))!=0)
9028a53ce2fSdrh        || (colFlags & COLFLAG_PRIMKEY)!=0
903f8ffb278Sdrh       ){
904693e6719Sdrh         testcase(  oldmask!=0xffffffff && i==31 );
9056df9c4b9Sdrh         sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, k);
906c3f9bad2Sdanielk1977       }else{
9078a53ce2fSdrh         sqlite3VdbeAddOp2(v, OP_Null, 0, k);
9088f2c54e6Sdanielk1977       }
909c3f9bad2Sdanielk1977     }
910f8ffb278Sdrh     if( chngRowid==0 && pPk==0 ){
911165921a7Sdan       sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
9124a32431cSdrh     }
9131da40a38Sdan   }
9144a32431cSdrh 
915165921a7Sdan   /* Populate the array of registers beginning at regNew with the new
91660ec914cSpeter.d.reid   ** row data. This array is used to check constants, create the new
917165921a7Sdan   ** table and index records, and as the values for any new.* references
918bb5f168fSdan   ** made by triggers.
919bb5f168fSdan   **
920bb5f168fSdan   ** If there are one or more BEFORE triggers, then do not populate the
921bb5f168fSdan   ** registers associated with columns that are (a) not modified by
922bb5f168fSdan   ** this UPDATE statement and (b) not accessed by new.* references. The
923bb5f168fSdan   ** values for registers not modified by the UPDATE must be reloaded from
924bb5f168fSdan   ** the database after the BEFORE triggers are fired anyway (as the trigger
925bb5f168fSdan   ** may have modified them). So not loading those that are not going to
926bb5f168fSdan   ** be used eliminates some redundant opcodes.
927bb5f168fSdan   */
928bb5f168fSdan   newmask = sqlite3TriggerColmask(
929bb5f168fSdan       pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
930bb5f168fSdan   );
9318a53ce2fSdrh   for(i=0, k=regNew; i<pTab->nCol; i++, k++){
9324a32431cSdrh     if( i==pTab->iPKey ){
9338a53ce2fSdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, k);
934c1431144Sdrh     }else if( (pTab->aCol[i].colFlags & COLFLAG_GENERATED)!=0 ){
935c1431144Sdrh       if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ) k--;
936165921a7Sdan     }else{
937cce7d176Sdrh       j = aXRef[i];
938bb5f168fSdan       if( j>=0 ){
93969887c99Sdan         if( nChangeFrom ){
94069887c99Sdan           int nOff = (isView ? pTab->nCol : nPk);
941a7c74006Sdrh           assert( eOnePass==ONEPASS_OFF );
94269887c99Sdan           sqlite3VdbeAddOp3(v, OP_Column, iEph, nOff+j, k);
94369887c99Sdan         }else{
9448a53ce2fSdrh           sqlite3ExprCode(pParse, pChanges->a[j].pExpr, k);
94569887c99Sdan         }
946693e6719Sdrh       }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
947bb5f168fSdan         /* This branch loads the value of a column that will not be changed
948bb5f168fSdan         ** into a register. This is done if there are no BEFORE triggers, or
949bb5f168fSdan         ** if there are one or more BEFORE triggers that use this value via
950bb5f168fSdan         ** a new.* reference in a trigger program.
951bb5f168fSdan         */
952fd7c9912Sdrh         testcase( i==31 );
953fd7c9912Sdrh         testcase( i==32 );
9546df9c4b9Sdrh         sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, k);
955be3da241Sdrh         bFinishSeek = 0;
956edfac345Sdrh       }else{
9578a53ce2fSdrh         sqlite3VdbeAddOp2(v, OP_Null, 0, k);
958165921a7Sdan       }
959cce7d176Sdrh     }
960cce7d176Sdrh   }
961c1431144Sdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS
962427b96aeSdrh   if( pTab->tabFlags & TF_HasGenerated ){
963427b96aeSdrh     testcase( pTab->tabFlags & TF_HasVirtual );
964427b96aeSdrh     testcase( pTab->tabFlags & TF_HasStored );
965dd6cc9b5Sdrh     sqlite3ComputeGeneratedColumns(pParse, regNew, pTab);
966c1431144Sdrh   }
967c1431144Sdrh #endif
968cce7d176Sdrh 
969165921a7Sdan   /* Fire any BEFORE UPDATE triggers. This happens before constraints are
970bb5f168fSdan   ** verified. One could argue that this is wrong.
971bb5f168fSdan   */
972bb5f168fSdan   if( tmask&TRIGGER_BEFORE ){
97357bf4a8eSdrh     sqlite3TableAffinity(v, pTab, regNew);
974165921a7Sdan     sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
975c3e356feSdrh         TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
976ae0931edSdan 
97769887c99Sdan     if( !isView ){
978ae0931edSdan       /* The row-trigger may have deleted the row being updated. In this
979ae0931edSdan       ** case, jump to the next row. No updates or AFTER triggers are
98048864df9Smistachkin       ** required. This behavior - what happens when the row being updated
981ae0931edSdan       ** is deleted or renamed by a BEFORE trigger - is left undefined in the
982bb5f168fSdan       ** documentation.
983bb5f168fSdan       */
984f8ffb278Sdrh       if( pPk ){
9857465787bSdan         sqlite3VdbeAddOp4Int(v, OP_NotFound,iDataCur,labelContinue,regKey,nKey);
986688852abSdrh         VdbeCoverage(v);
987f8ffb278Sdrh       }else{
988c3e356feSdrh         sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue,regOldRowid);
989688852abSdrh         VdbeCoverage(v);
990f8ffb278Sdrh       }
991bb5f168fSdan 
992909066bbSdrh       /* After-BEFORE-trigger-reload-loop:
993909066bbSdrh       ** If it did not delete it, the BEFORE trigger may still have modified
994bb5f168fSdan       ** some of the columns of the row being updated. Load the values for
995de7ca50dSdrh       ** all columns not modified by the update statement into their registers
996de7ca50dSdrh       ** in case this has happened. Only unmodified columns are reloaded.
997de7ca50dSdrh       ** The values computed for modified columns use the values before the
998de7ca50dSdrh       ** BEFORE trigger runs.  See test case trigger1-18.0 (added 2018-04-26)
999de7ca50dSdrh       ** for an example.
1000bb5f168fSdan       */
10018a53ce2fSdrh       for(i=0, k=regNew; i<pTab->nCol; i++, k++){
1002c1431144Sdrh         if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){
1003c1431144Sdrh           if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ) k--;
10048a53ce2fSdrh         }else if( aXRef[i]<0 && i!=pTab->iPKey ){
10056df9c4b9Sdrh           sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, k);
1006bb5f168fSdan         }
1007bb5f168fSdan       }
1008c1431144Sdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1009427b96aeSdrh       if( pTab->tabFlags & TF_HasGenerated ){
1010427b96aeSdrh         testcase( pTab->tabFlags & TF_HasVirtual );
1011427b96aeSdrh         testcase( pTab->tabFlags & TF_HasStored );
1012dd6cc9b5Sdrh         sqlite3ComputeGeneratedColumns(pParse, regNew, pTab);
1013c1431144Sdrh       }
1014c1431144Sdrh #endif
10152832ad42Sdan     }
101669887c99Sdan   }
1017165921a7Sdan 
1018165921a7Sdan   if( !isView ){
1019165921a7Sdan     /* Do constraint checks. */
1020f8ffb278Sdrh     assert( regOldRowid>0 );
1021f8ffb278Sdrh     sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
1022bdb00225Sdrh         regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace,
1023788d55aaSdrh         aXRef, 0);
10240ca3e24bSdrh 
1025f66bfcb7Sdan     /* If REPLACE conflict handling may have been used, or if the PK of the
1026f66bfcb7Sdan     ** row is changing, then the GenerateConstraintChecks() above may have
1027f66bfcb7Sdan     ** moved cursor iDataCur. Reseek it. */
1028f66bfcb7Sdan     if( bReplace || chngKey ){
1029f66bfcb7Sdan       if( pPk ){
1030f66bfcb7Sdan         sqlite3VdbeAddOp4Int(v, OP_NotFound,iDataCur,labelContinue,regKey,nKey);
1031f66bfcb7Sdan       }else{
1032f66bfcb7Sdan         sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue,regOldRowid);
1033f66bfcb7Sdan       }
103410c5341cSdrh       VdbeCoverage(v);
1035f66bfcb7Sdan     }
1036f66bfcb7Sdan 
10371da40a38Sdan     /* Do FK constraint checks. */
1038e7a94d81Sdan     if( hasFK ){
1039f8ffb278Sdrh       sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);
1040e7a94d81Sdan     }
10411da40a38Sdan 
1042165921a7Sdan     /* Delete the index entries associated with the current record.  */
1043f0ee1d3cSdan     sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx, -1);
10440ca3e24bSdrh 
1045be3da241Sdrh     /* We must run the OP_FinishSeek opcode to resolve a prior
1046be3da241Sdrh     ** OP_DeferredSeek if there is any possibility that there have been
1047be3da241Sdrh     ** no OP_Column opcodes since the OP_DeferredSeek was issued.  But
1048be3da241Sdrh     ** we want to avoid the OP_FinishSeek if possible, as running it
1049be3da241Sdrh     ** costs CPU cycles. */
1050be3da241Sdrh     if( bFinishSeek ){
1051be3da241Sdrh       sqlite3VdbeAddOp1(v, OP_FinishSeek, iDataCur);
1052d3ee3ad1Sdrh     }
1053d3ee3ad1Sdrh 
105446c47d46Sdan     /* If changing the rowid value, or if there are foreign key constraints
105546c47d46Sdan     ** to process, delete the old record. Otherwise, add a noop OP_Delete
105646c47d46Sdan     ** to invoke the pre-update hook.
105737db03bfSdan     **
105837db03bfSdan     ** That (regNew==regnewRowid+1) is true is also important for the
10599b1c62d4Sdrh     ** pre-update hook. If the caller invokes preupdate_new(), the returned
106037db03bfSdan     ** value is copied from memory cell (regNewRowid+1+iCol), where iCol
106137db03bfSdan     ** is the column index supplied by the user.
106246c47d46Sdan     */
106337db03bfSdan     assert( regNew==regNewRowid+1 );
106474c3302fSdrh #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
1065cbf1b8efSdrh     sqlite3VdbeAddOp3(v, OP_Delete, iDataCur,
1066940b5eaaSdan         OPFLAG_ISUPDATE | ((hasFK>1 || chngKey) ? 0 : OPFLAG_ISNOOP),
106746c47d46Sdan         regNewRowid
106846c47d46Sdan     );
1069e206ea7fSdan     if( eOnePass==ONEPASS_MULTI ){
1070e206ea7fSdan       assert( hasFK==0 && chngKey==0 );
1071e206ea7fSdan       sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
1072e206ea7fSdan     }
107346c47d46Sdan     if( !pParse->nested ){
1074f14b7fb7Sdrh       sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
10754a32431cSdrh     }
107674c3302fSdrh #else
1077940b5eaaSdan     if( hasFK>1 || chngKey ){
107874c3302fSdrh       sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
107974c3302fSdrh     }
108074c3302fSdrh #endif
10814a32431cSdrh 
1082e7a94d81Sdan     if( hasFK ){
1083f8ffb278Sdrh       sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
1084e7a94d81Sdan     }
10859277efa3Sdan 
108676d462eeSdan     /* Insert the new index entries and the new record. */
1087f91c1318Sdan     sqlite3CompleteInsertion(
1088f91c1318Sdan         pParse, pTab, iDataCur, iIdxCur, regNewRowid, aRegIdx,
1089f91c1318Sdan         OPFLAG_ISUPDATE | (eOnePass==ONEPASS_MULTI ? OPFLAG_SAVEPOSITION : 0),
1090f91c1318Sdan         0, 0
1091f91c1318Sdan     );
10921da40a38Sdan 
10931da40a38Sdan     /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
10941da40a38Sdan     ** handle rows (possibly in other tables) that refer via a foreign key
10951da40a38Sdan     ** to the row just updated. */
1096e7a94d81Sdan     if( hasFK ){
1097f8ffb278Sdrh       sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
10985cf590c1Sdrh     }
1099e7a94d81Sdan   }
1100cce7d176Sdrh 
11010ca3e24bSdrh   /* Increment the row counter
11021bee3d7bSdrh   */
110379636913Sdrh   if( regRowCount ){
110404adf416Sdrh     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
11051bee3d7bSdrh   }
11061bee3d7bSdrh 
1107165921a7Sdan   sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
1108c3e356feSdrh       TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
1109c3f9bad2Sdanielk1977 
1110cce7d176Sdrh   /* Repeat the above with the next record to be updated, until
1111cce7d176Sdrh   ** all record selected by the WHERE clause have been updated.
1112cce7d176Sdrh   */
1113f91c1318Sdan   if( eOnePass==ONEPASS_SINGLE ){
1114702ba9f2Sdrh     /* Nothing to do at end-of-loop for a single-pass */
1115f91c1318Sdan   }else if( eOnePass==ONEPASS_MULTI ){
1116f91c1318Sdan     sqlite3VdbeResolveLabel(v, labelContinue);
1117f91c1318Sdan     sqlite3WhereEnd(pWInfo);
111832881bebSdrh   }else{
1119ea22abe3Sdrh     sqlite3VdbeResolveLabel(v, labelContinue);
1120688852abSdrh     sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
1121ea22abe3Sdrh   }
1122ea22abe3Sdrh   sqlite3VdbeResolveLabel(v, labelBreak);
1123c3f9bad2Sdanielk1977 
11240b9f50d8Sdrh   /* Update the sqlite_sequence table by storing the content of the
11250b9f50d8Sdrh   ** maximum rowid counter values recorded while inserting into
11260b9f50d8Sdrh   ** autoincrement tables.
11270b9f50d8Sdrh   */
1128f3d7bbb7Sdrh   if( pParse->nested==0 && pParse->pTriggerTab==0 && pUpsert==0 ){
11290b9f50d8Sdrh     sqlite3AutoincrementEnd(pParse);
11300b9f50d8Sdrh   }
11310b9f50d8Sdrh 
11321bee3d7bSdrh   /*
113379636913Sdrh   ** Return the number of rows that were changed, if we are tracking
113479636913Sdrh   ** that information.
11351bee3d7bSdrh   */
113679636913Sdrh   if( regRowCount ){
11373b26b2b5Sdrh     sqlite3CodeChangeCount(v, regRowCount, "rows updated");
11381bee3d7bSdrh   }
11391bee3d7bSdrh 
1140cce7d176Sdrh update_cleanup:
11414adee20fSdanielk1977   sqlite3AuthContextPop(&sContext);
11426a53499aSdrh   sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */
1143633e6d57Sdrh   sqlite3SrcListDelete(db, pTabList);
1144633e6d57Sdrh   sqlite3ExprListDelete(db, pChanges);
1145633e6d57Sdrh   sqlite3ExprDelete(db, pWhere);
11463b61ebb8Sdan #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
1147b3c16b89Sdan   sqlite3ExprListDelete(db, pOrderBy);
1148b3c16b89Sdan   sqlite3ExprDelete(db, pLimit);
11493b61ebb8Sdan #endif
1150cce7d176Sdrh   return;
1151cce7d176Sdrh }
115275cbd984Sdan /* Make sure "isView" and other macros defined above are undefined. Otherwise
115360ec914cSpeter.d.reid ** they may interfere with compilation of other functions in this file
115475cbd984Sdan ** (or in another file, if this file becomes part of the amalgamation).  */
115575cbd984Sdan #ifdef isView
115675cbd984Sdan  #undef isView
115775cbd984Sdan #endif
115875cbd984Sdan #ifdef pTrigger
115975cbd984Sdan  #undef pTrigger
116075cbd984Sdan #endif
11619c41938fSdrh 
11629c41938fSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
11639c41938fSdrh /*
11649c41938fSdrh ** Generate code for an UPDATE of a virtual table.
11659c41938fSdrh **
11660f40037eSdan ** There are two possible strategies - the default and the special
11670f40037eSdan ** "onepass" strategy. Onepass is only used if the virtual table
11680f40037eSdan ** implementation indicates that pWhere may match at most one row.
11690f40037eSdan **
11700f40037eSdan ** The default strategy is to create an ephemeral table that contains
11719c41938fSdrh ** for each row to be changed:
11729c41938fSdrh **
11739c41938fSdrh **   (A)  The original rowid of that row.
11740f40037eSdan **   (B)  The revised rowid for the row.
11759c41938fSdrh **   (C)  The content of every column in the row.
11769c41938fSdrh **
11770f40037eSdan ** Then loop through the contents of this ephemeral table executing a
11780f40037eSdan ** VUpdate for each row. When finished, drop the ephemeral table.
11799c41938fSdrh **
11800f40037eSdan ** The "onepass" strategy does not use an ephemeral table. Instead, it
11810f40037eSdan ** stores the same values (A, B and C above) in a register array and
11820f40037eSdan ** makes a single invocation of VUpdate.
11839c41938fSdrh */
updateVirtualTable(Parse * pParse,SrcList * pSrc,Table * pTab,ExprList * pChanges,Expr * pRowid,int * aXRef,Expr * pWhere,int onError)11849c41938fSdrh static void updateVirtualTable(
11859c41938fSdrh   Parse *pParse,       /* The parsing context */
11869c41938fSdrh   SrcList *pSrc,       /* The virtual table to be modified */
11879c41938fSdrh   Table *pTab,         /* The virtual table */
11889c41938fSdrh   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
11899c41938fSdrh   Expr *pRowid,        /* Expression used to recompute the rowid */
11909c41938fSdrh   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
1191b061d058Sdan   Expr *pWhere,        /* WHERE clause of the UPDATE statement */
1192b061d058Sdan   int onError          /* ON CONFLICT strategy */
11939c41938fSdrh ){
11949c41938fSdrh   Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
11959c41938fSdrh   int ephemTab;             /* Table holding the result of the SELECT */
11969c41938fSdrh   int i;                    /* Loop counter */
119717435752Sdrh   sqlite3 *db = pParse->db; /* Database connection */
1198595a523aSdanielk1977   const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
1199a7c74006Sdrh   WhereInfo *pWInfo = 0;
12000f40037eSdan   int nArg = 2 + pTab->nCol;      /* Number of arguments to VUpdate */
12010f40037eSdan   int regArg;                     /* First register in VUpdate arg array */
12020f40037eSdan   int regRec;                     /* Register in which to assemble record */
12030f40037eSdan   int regRowid;                   /* Register for ephem table rowid */
12040f40037eSdan   int iCsr = pSrc->a[0].iCursor;  /* Cursor used for virtual table scan */
12050f40037eSdan   int aDummy[2];                  /* Unused arg for sqlite3WhereOkOnePass() */
1206338e311aSdrh   int eOnePass;                   /* True to use onepass strategy */
12070f40037eSdan   int addr;                       /* Address of OP_OpenEphemeral */
12089c41938fSdrh 
120924cd20ffSdrh   /* Allocate nArg registers in which to gather the arguments for VUpdate. Then
12100f40037eSdan   ** create and open the ephemeral table in which the records created from
12110f40037eSdan   ** these arguments will be temporarily stored. */
12129c41938fSdrh   assert( v );
12139c41938fSdrh   ephemTab = pParse->nTab++;
12140f40037eSdan   addr= sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, nArg);
12150f40037eSdan   regArg = pParse->nMem + 1;
12160f40037eSdan   pParse->nMem += nArg;
121769887c99Sdan   if( pSrc->nSrc>1 ){
12184d906f1bSdan     Index *pPk = 0;
1219576d5a86Sdan     Expr *pRow;
1220576d5a86Sdan     ExprList *pList;
12214d906f1bSdan     if( HasRowid(pTab) ){
122269887c99Sdan       if( pRowid ){
1223576d5a86Sdan         pRow = sqlite3ExprDup(db, pRowid, 0);
122469887c99Sdan       }else{
1225576d5a86Sdan         pRow = sqlite3PExpr(pParse, TK_ROW, 0, 0);
122669887c99Sdan       }
12274d906f1bSdan     }else{
12284d906f1bSdan       i16 iPk;      /* PRIMARY KEY column */
12294d906f1bSdan       pPk = sqlite3PrimaryKeyIndex(pTab);
12304d906f1bSdan       assert( pPk!=0 );
12314d906f1bSdan       assert( pPk->nKeyCol==1 );
12324d906f1bSdan       iPk = pPk->aiColumn[0];
12334d906f1bSdan       if( aXRef[iPk]>=0 ){
12344d906f1bSdan         pRow = sqlite3ExprDup(db, pChanges->a[aXRef[iPk]].pExpr, 0);
12354d906f1bSdan       }else{
12364d906f1bSdan         pRow = exprRowColumn(pParse, iPk);
12374d906f1bSdan       }
12384d906f1bSdan     }
1239576d5a86Sdan     pList = sqlite3ExprListAppend(pParse, 0, pRow);
1240576d5a86Sdan 
124169887c99Sdan     for(i=0; i<pTab->nCol; i++){
124269887c99Sdan       if( aXRef[i]>=0 ){
124369887c99Sdan         pList = sqlite3ExprListAppend(pParse, pList,
124469887c99Sdan           sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0)
124569887c99Sdan         );
124669887c99Sdan       }else{
1247576d5a86Sdan         pList = sqlite3ExprListAppend(pParse, pList, exprRowColumn(pParse, i));
124869887c99Sdan       }
124969887c99Sdan     }
125069887c99Sdan 
12514d906f1bSdan     updateFromSelect(pParse, ephemTab, pPk, pList, pSrc, pWhere, 0, 0);
125269887c99Sdan     sqlite3ExprListDelete(db, pList);
125369887c99Sdan     eOnePass = ONEPASS_OFF;
125469887c99Sdan   }else{
12550f40037eSdan     regRec = ++pParse->nMem;
12560f40037eSdan     regRowid = ++pParse->nMem;
12579c41938fSdrh 
12580f40037eSdan     /* Start scanning the virtual table */
1259895bab33Sdrh     pWInfo = sqlite3WhereBegin(
1260895bab33Sdrh         pParse, pSrc, pWhere, 0, 0, 0, WHERE_ONEPASS_DESIRED, 0
1261895bab33Sdrh     );
12620f40037eSdan     if( pWInfo==0 ) return;
12639c41938fSdrh 
12640f40037eSdan     /* Populate the argument registers. */
12659c41938fSdrh     for(i=0; i<pTab->nCol; i++){
12667e7fd73bSdrh       assert( (pTab->aCol[i].colFlags & COLFLAG_GENERATED)==0 );
12670f40037eSdan       if( aXRef[i]>=0 ){
12680f40037eSdan         sqlite3ExprCode(pParse, pChanges->a[aXRef[i]].pExpr, regArg+2+i);
12690f40037eSdan       }else{
1270ce2fbd1bSdrh         sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, i, regArg+2+i);
127169887c99Sdan         sqlite3VdbeChangeP5(v, OPFLAG_NOCHNG);/* For sqlite3_vtab_nochange() */
12720f40037eSdan       }
12730f40037eSdan     }
1274e3740f27Sdrh     if( HasRowid(pTab) ){
1275e3740f27Sdrh       sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg);
1276e3740f27Sdrh       if( pRowid ){
1277e3740f27Sdrh         sqlite3ExprCode(pParse, pRowid, regArg+1);
1278e3740f27Sdrh       }else{
1279e3740f27Sdrh         sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg+1);
1280e3740f27Sdrh       }
1281e3740f27Sdrh     }else{
1282e3740f27Sdrh       Index *pPk;   /* PRIMARY KEY index */
1283e3740f27Sdrh       i16 iPk;      /* PRIMARY KEY column */
1284e3740f27Sdrh       pPk = sqlite3PrimaryKeyIndex(pTab);
1285e3740f27Sdrh       assert( pPk!=0 );
1286e3740f27Sdrh       assert( pPk->nKeyCol==1 );
1287e3740f27Sdrh       iPk = pPk->aiColumn[0];
1288e3740f27Sdrh       sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, iPk, regArg);
1289e3740f27Sdrh       sqlite3VdbeAddOp2(v, OP_SCopy, regArg+2+iPk, regArg+1);
1290e3740f27Sdrh     }
12910f40037eSdan 
1292338e311aSdrh     eOnePass = sqlite3WhereOkOnePass(pWInfo, aDummy);
12930f40037eSdan 
1294338e311aSdrh     /* There is no ONEPASS_MULTI on virtual tables */
1295338e311aSdrh     assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );
1296338e311aSdrh 
1297338e311aSdrh     if( eOnePass ){
12980f40037eSdan       /* If using the onepass strategy, no-op out the OP_OpenEphemeral coded
1299ac9151d8Sdrh       ** above. */
13000f40037eSdan       sqlite3VdbeChangeToNoop(v, addr);
1301338e311aSdrh       sqlite3VdbeAddOp1(v, OP_Close, iCsr);
13020f40037eSdan     }else{
13030f40037eSdan       /* Create a record from the argument register contents and insert it into
13040f40037eSdan       ** the ephemeral table. */
1305ac9151d8Sdrh       sqlite3MultiWrite(pParse);
13060f40037eSdan       sqlite3VdbeAddOp3(v, OP_MakeRecord, regArg, nArg, regRec);
1307da36933eSdrh #if defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_NULL_TRIM)
130841fb367aSdrh       /* Signal an assert() within OP_MakeRecord that it is allowed to
130941fb367aSdrh       ** accept no-change records with serial_type 10 */
131041fb367aSdrh       sqlite3VdbeChangeP5(v, OPFLAG_NOCHNG_MAGIC);
131141fb367aSdrh #endif
13120f40037eSdan       sqlite3VdbeAddOp2(v, OP_NewRowid, ephemTab, regRowid);
13130f40037eSdan       sqlite3VdbeAddOp3(v, OP_Insert, ephemTab, regRec, regRowid);
13140f40037eSdan     }
131569887c99Sdan   }
13160f40037eSdan 
1317354474adSdan 
1318338e311aSdrh   if( eOnePass==ONEPASS_OFF ){
13190f40037eSdan     /* End the virtual table scan */
132069887c99Sdan     if( pSrc->nSrc==1 ){
13210f40037eSdan       sqlite3WhereEnd(pWInfo);
132269887c99Sdan     }
13230f40037eSdan 
13240f40037eSdan     /* Begin scannning through the ephemeral table. */
1325354474adSdan     addr = sqlite3VdbeAddOp1(v, OP_Rewind, ephemTab); VdbeCoverage(v);
13260f40037eSdan 
13270f40037eSdan     /* Extract arguments from the current row of the ephemeral table and
13280f40037eSdan     ** invoke the VUpdate method.  */
13290f40037eSdan     for(i=0; i<nArg; i++){
13300f40037eSdan       sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i, regArg+i);
13310f40037eSdan     }
13329c41938fSdrh   }
13334f3dd150Sdrh   sqlite3VtabMakeWritable(pParse, pTab);
13340f40037eSdan   sqlite3VdbeAddOp4(v, OP_VUpdate, 0, nArg, regArg, pVTab, P4_VTAB);
1335b061d058Sdan   sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
1336e0af83acSdan   sqlite3MayAbort(pParse);
13370f40037eSdan 
1338354474adSdan   /* End of the ephemeral table scan. Or, if using the onepass strategy,
1339354474adSdan   ** jump to here if the scan visited zero rows. */
1340338e311aSdrh   if( eOnePass==ONEPASS_OFF ){
1341688852abSdrh     sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
1342bdfb6b5aSdrh     sqlite3VdbeJumpHere(v, addr);
134366a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
1344354474adSdan   }else{
1345354474adSdan     sqlite3WhereEnd(pWInfo);
13460f40037eSdan   }
13479c41938fSdrh }
13489c41938fSdrh #endif /* SQLITE_OMIT_VIRTUALTABLE */
1349