Fix code indentation. No logic changes.
[sqlite.git] / src / update.c
blob15e8f4a6ce7bfee85c3674bfe38640a0a7acb2a7
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.
11 *************************************************************************
12 ** This file contains C code routines that are called by the parser
13 ** to handle UPDATE statements.
15 #include "sqliteInt.h"
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 */
29 #endif /* SQLITE_OMIT_VIRTUALTABLE */
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.
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.
45 ** Column definitions created by an ALTER TABLE command may only have
46 ** literal default values specified: a number, null or a string. (If a more
47 ** complicated default expression value was provided, it is evaluated
48 ** when the ALTER TABLE is executed and one of the literal values written
49 ** into the sqlite_master table.)
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.
56 ** If parameter iReg is not negative, code an OP_RealAffinity instruction
57 ** on register iReg. This is used when an equivalent integer value is
58 ** stored in place of an 8-byte floating point value in order to save
59 ** space.
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);
75 #ifndef SQLITE_OMIT_FLOATING_POINT
76 if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
77 sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
79 #endif
83 ** Process an UPDATE statement.
85 ** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
86 ** \_______/ \________/ \______/ \________________/
87 * onError pTabList pChanges pWhere
89 void sqlite3Update(
90 Parse *pParse, /* The parser context */
91 SrcList *pTabList, /* The table in which we should change things */
92 ExprList *pChanges, /* Things to be changed */
93 Expr *pWhere, /* The WHERE clause. May be null */
94 int onError, /* How to handle constraint errors */
95 ExprList *pOrderBy, /* ORDER BY clause. May be null */
96 Expr *pLimit /* LIMIT clause. May be null */
98 int i, j; /* Loop counters */
99 Table *pTab; /* The table to be updated */
100 int addrTop = 0; /* VDBE instruction address of the start of the loop */
101 WhereInfo *pWInfo; /* Information about the WHERE clause */
102 Vdbe *v; /* The virtual database engine */
103 Index *pIdx; /* For looping over indices */
104 Index *pPk; /* The PRIMARY KEY index for WITHOUT ROWID tables */
105 int nIdx; /* Number of indices that need updating */
106 int iBaseCur; /* Base cursor number */
107 int iDataCur; /* Cursor for the canonical data btree */
108 int iIdxCur; /* Cursor for the first index */
109 sqlite3 *db; /* The database structure */
110 int *aRegIdx = 0; /* First register in array assigned to each index */
111 int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
112 ** an expression for the i-th column of the table.
113 ** aXRef[i]==-1 if the i-th column is not changed. */
114 u8 *aToOpen; /* 1 for tables and indices to be opened */
115 u8 chngPk; /* PRIMARY KEY changed in a WITHOUT ROWID table */
116 u8 chngRowid; /* Rowid changed in a normal table */
117 u8 chngKey; /* Either chngPk or chngRowid */
118 Expr *pRowidExpr = 0; /* Expression defining the new record number */
119 AuthContext sContext; /* The authorization context */
120 NameContext sNC; /* The name-context to resolve expressions in */
121 int iDb; /* Database containing the table being updated */
122 int eOnePass; /* ONEPASS_XXX value from where.c */
123 int hasFK; /* True if foreign key processing is required */
124 int labelBreak; /* Jump here to break out of UPDATE loop */
125 int labelContinue; /* Jump here to continue next step of UPDATE loop */
126 int flags; /* Flags for sqlite3WhereBegin() */
128 #ifndef SQLITE_OMIT_TRIGGER
129 int isView; /* True when updating a view (INSTEAD OF trigger) */
130 Trigger *pTrigger; /* List of triggers on pTab, if required */
131 int tmask; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
132 #endif
133 int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */
134 int iEph = 0; /* Ephemeral table holding all primary key values */
135 int nKey = 0; /* Number of elements in regKey for WITHOUT ROWID */
136 int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
137 int addrOpen = 0; /* Address of OP_OpenEphemeral */
138 int iPk = 0; /* First of nPk cells holding PRIMARY KEY value */
139 i16 nPk = 0; /* Number of components of the PRIMARY KEY */
140 int bReplace = 0; /* True if REPLACE conflict resolution might happen */
142 /* Register Allocations */
143 int regRowCount = 0; /* A count of rows changed */
144 int regOldRowid = 0; /* The old rowid */
145 int regNewRowid = 0; /* The new rowid */
146 int regNew = 0; /* Content of the NEW.* table in triggers */
147 int regOld = 0; /* Content of OLD.* table in triggers */
148 int regRowSet = 0; /* Rowset of rows to be updated */
149 int regKey = 0; /* composite PRIMARY KEY value */
151 memset(&sContext, 0, sizeof(sContext));
152 db = pParse->db;
153 if( pParse->nErr || db->mallocFailed ){
154 goto update_cleanup;
156 assert( pTabList->nSrc==1 );
158 /* Locate the table which we want to update.
160 pTab = sqlite3SrcListLookup(pParse, pTabList);
161 if( pTab==0 ) goto update_cleanup;
162 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
164 /* Figure out if we have any triggers and if the table being
165 ** updated is a view.
167 #ifndef SQLITE_OMIT_TRIGGER
168 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
169 isView = pTab->pSelect!=0;
170 assert( pTrigger || tmask==0 );
171 #else
172 # define pTrigger 0
173 # define isView 0
174 # define tmask 0
175 #endif
176 #ifdef SQLITE_OMIT_VIEW
177 # undef isView
178 # define isView 0
179 #endif
181 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
182 if( !isView ){
183 pWhere = sqlite3LimitWhere(
184 pParse, pTabList, pWhere, pOrderBy, pLimit, "UPDATE"
186 pOrderBy = 0;
187 pLimit = 0;
189 #endif
191 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
192 goto update_cleanup;
194 if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
195 goto update_cleanup;
198 /* Allocate a cursors for the main database table and for all indices.
199 ** The index cursors might not be used, but if they are used they
200 ** need to occur right after the database cursor. So go ahead and
201 ** allocate enough space, just in case.
203 pTabList->a[0].iCursor = iBaseCur = iDataCur = pParse->nTab++;
204 iIdxCur = iDataCur+1;
205 pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
206 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
207 if( IsPrimaryKeyIndex(pIdx) && pPk!=0 ){
208 iDataCur = pParse->nTab;
209 pTabList->a[0].iCursor = iDataCur;
211 pParse->nTab++;
214 /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].
215 ** Initialize aXRef[] and aToOpen[] to their default values.
217 aXRef = sqlite3DbMallocRawNN(db, sizeof(int) * (pTab->nCol+nIdx) + nIdx+2 );
218 if( aXRef==0 ) goto update_cleanup;
219 aRegIdx = aXRef+pTab->nCol;
220 aToOpen = (u8*)(aRegIdx+nIdx);
221 memset(aToOpen, 1, nIdx+1);
222 aToOpen[nIdx+1] = 0;
223 for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
225 /* Initialize the name-context */
226 memset(&sNC, 0, sizeof(sNC));
227 sNC.pParse = pParse;
228 sNC.pSrcList = pTabList;
230 /* Resolve the column names in all the expressions of the
231 ** of the UPDATE statement. Also find the column index
232 ** for each column to be updated in the pChanges array. For each
233 ** column to be updated, make sure we have authorization to change
234 ** that column.
236 chngRowid = chngPk = 0;
237 for(i=0; i<pChanges->nExpr; i++){
238 if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
239 goto update_cleanup;
241 for(j=0; j<pTab->nCol; j++){
242 if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
243 if( j==pTab->iPKey ){
244 chngRowid = 1;
245 pRowidExpr = pChanges->a[i].pExpr;
246 }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
247 chngPk = 1;
249 aXRef[j] = i;
250 break;
253 if( j>=pTab->nCol ){
254 if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){
255 j = -1;
256 chngRowid = 1;
257 pRowidExpr = pChanges->a[i].pExpr;
258 }else{
259 sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
260 pParse->checkSchema = 1;
261 goto update_cleanup;
264 #ifndef SQLITE_OMIT_AUTHORIZATION
266 int rc;
267 rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
268 j<0 ? "ROWID" : pTab->aCol[j].zName,
269 db->aDb[iDb].zDbSName);
270 if( rc==SQLITE_DENY ){
271 goto update_cleanup;
272 }else if( rc==SQLITE_IGNORE ){
273 aXRef[j] = -1;
276 #endif
278 assert( (chngRowid & chngPk)==0 );
279 assert( chngRowid==0 || chngRowid==1 );
280 assert( chngPk==0 || chngPk==1 );
281 chngKey = chngRowid + chngPk;
283 /* The SET expressions are not actually used inside the WHERE loop.
284 ** So reset the colUsed mask. Unless this is a virtual table. In that
285 ** case, set all bits of the colUsed mask (to ensure that the virtual
286 ** table implementation makes all columns available).
288 pTabList->a[0].colUsed = IsVirtual(pTab) ? ALLBITS : 0;
290 hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
292 /* There is one entry in the aRegIdx[] array for each index on the table
293 ** being updated. Fill in aRegIdx[] with a register number that will hold
294 ** the key for accessing each index.
296 ** FIXME: Be smarter about omitting indexes that use expressions.
298 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
299 int reg;
300 if( chngKey || hasFK>1 || pIdx->pPartIdxWhere || pIdx==pPk ){
301 reg = ++pParse->nMem;
302 pParse->nMem += pIdx->nColumn;
303 }else{
304 reg = 0;
305 for(i=0; i<pIdx->nKeyCol; i++){
306 i16 iIdxCol = pIdx->aiColumn[i];
307 if( iIdxCol<0 || aXRef[iIdxCol]>=0 ){
308 reg = ++pParse->nMem;
309 pParse->nMem += pIdx->nColumn;
310 if( (onError==OE_Replace)
311 || (onError==OE_Default && pIdx->onError==OE_Replace)
313 bReplace = 1;
315 break;
319 if( reg==0 ) aToOpen[j+1] = 0;
320 aRegIdx[j] = reg;
322 if( bReplace ){
323 /* If REPLACE conflict resolution might be invoked, open cursors on all
324 ** indexes in case they are needed to delete records. */
325 memset(aToOpen, 1, nIdx+1);
328 /* Begin generating code. */
329 v = sqlite3GetVdbe(pParse);
330 if( v==0 ) goto update_cleanup;
331 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
332 sqlite3BeginWriteOperation(pParse, 1, iDb);
334 /* Allocate required registers. */
335 if( !IsVirtual(pTab) ){
336 regRowSet = ++pParse->nMem;
337 regOldRowid = regNewRowid = ++pParse->nMem;
338 if( chngPk || pTrigger || hasFK ){
339 regOld = pParse->nMem + 1;
340 pParse->nMem += pTab->nCol;
342 if( chngKey || pTrigger || hasFK ){
343 regNewRowid = ++pParse->nMem;
345 regNew = pParse->nMem + 1;
346 pParse->nMem += pTab->nCol;
349 /* Start the view context. */
350 if( isView ){
351 sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
354 /* If we are trying to update a view, realize that view into
355 ** an ephemeral table.
357 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
358 if( isView ){
359 sqlite3MaterializeView(pParse, pTab,
360 pWhere, pOrderBy, pLimit, iDataCur
362 pOrderBy = 0;
363 pLimit = 0;
365 #endif
367 /* Resolve the column names in all the expressions in the
368 ** WHERE clause.
370 if( sqlite3ResolveExprNames(&sNC, pWhere) ){
371 goto update_cleanup;
374 #ifndef SQLITE_OMIT_VIRTUALTABLE
375 /* Virtual tables must be handled separately */
376 if( IsVirtual(pTab) ){
377 updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
378 pWhere, onError);
379 goto update_cleanup;
381 #endif
383 /* Initialize the count of updated rows */
384 if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
385 regRowCount = ++pParse->nMem;
386 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
389 if( HasRowid(pTab) ){
390 sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
391 }else{
392 assert( pPk!=0 );
393 nPk = pPk->nKeyCol;
394 iPk = pParse->nMem+1;
395 pParse->nMem += nPk;
396 regKey = ++pParse->nMem;
397 iEph = pParse->nTab++;
399 sqlite3VdbeAddOp2(v, OP_Null, 0, iPk);
400 addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk);
401 sqlite3VdbeSetP4KeyInfo(pParse, pPk);
404 /* Begin the database scan.
406 ** Do not consider a single-pass strategy for a multi-row update if
407 ** there are any triggers or foreign keys to process, or rows may
408 ** be deleted as a result of REPLACE conflict handling. Any of these
409 ** things might disturb a cursor being used to scan through the table
410 ** or index, causing a single-pass approach to malfunction. */
411 flags = WHERE_ONEPASS_DESIRED|WHERE_SEEK_UNIQ_TABLE;
412 if( !pParse->nested && !pTrigger && !hasFK && !chngKey && !bReplace ){
413 flags |= WHERE_ONEPASS_MULTIROW;
415 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, flags, iIdxCur);
416 if( pWInfo==0 ) goto update_cleanup;
418 /* A one-pass strategy that might update more than one row may not
419 ** be used if any column of the index used for the scan is being
420 ** updated. Otherwise, if there is an index on "b", statements like
421 ** the following could create an infinite loop:
423 ** UPDATE t1 SET b=b+1 WHERE b>?
425 ** Fall back to ONEPASS_OFF if where.c has selected a ONEPASS_MULTI
426 ** strategy that uses an index for which one or more columns are being
427 ** updated. */
428 eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
429 if( eOnePass==ONEPASS_MULTI ){
430 int iCur = aiCurOnePass[1];
431 if( iCur>=0 && iCur!=iDataCur && aToOpen[iCur-iBaseCur] ){
432 eOnePass = ONEPASS_OFF;
434 assert( iCur!=iDataCur || !HasRowid(pTab) );
437 if( HasRowid(pTab) ){
438 /* Read the rowid of the current row of the WHERE scan. In ONEPASS_OFF
439 ** mode, write the rowid into the FIFO. In either of the one-pass modes,
440 ** leave it in register regOldRowid. */
441 sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
442 if( eOnePass==ONEPASS_OFF ){
443 sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
445 }else{
446 /* Read the PK of the current row into an array of registers. In
447 ** ONEPASS_OFF mode, serialize the array into a record and store it in
448 ** the ephemeral table. Or, in ONEPASS_SINGLE or MULTI mode, change
449 ** the OP_OpenEphemeral instruction to a Noop (the ephemeral table
450 ** is not required) and leave the PK fields in the array of registers. */
451 for(i=0; i<nPk; i++){
452 assert( pPk->aiColumn[i]>=0 );
453 sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur,pPk->aiColumn[i],iPk+i);
455 if( eOnePass ){
456 sqlite3VdbeChangeToNoop(v, addrOpen);
457 nKey = nPk;
458 regKey = iPk;
459 }else{
460 sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
461 sqlite3IndexAffinityStr(db, pPk), nPk);
462 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEph, regKey, iPk, nPk);
466 if( eOnePass!=ONEPASS_MULTI ){
467 sqlite3WhereEnd(pWInfo);
470 labelBreak = sqlite3VdbeMakeLabel(v);
471 if( !isView ){
472 int addrOnce = 0;
474 /* Open every index that needs updating. */
475 if( eOnePass!=ONEPASS_OFF ){
476 if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
477 if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
480 if( eOnePass==ONEPASS_MULTI && (nIdx-(aiCurOnePass[1]>=0))>0 ){
481 addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
483 sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, iBaseCur, aToOpen,
484 0, 0);
485 if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
488 /* Top of the update loop */
489 if( eOnePass!=ONEPASS_OFF ){
490 if( !isView && aiCurOnePass[0]!=iDataCur && aiCurOnePass[1]!=iDataCur ){
491 assert( pPk );
492 sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey, nKey);
493 VdbeCoverageNeverTaken(v);
495 if( eOnePass==ONEPASS_SINGLE ){
496 labelContinue = labelBreak;
497 }else{
498 labelContinue = sqlite3VdbeMakeLabel(v);
500 sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
501 VdbeCoverageIf(v, pPk==0);
502 VdbeCoverageIf(v, pPk!=0);
503 }else if( pPk ){
504 labelContinue = sqlite3VdbeMakeLabel(v);
505 sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
506 addrTop = sqlite3VdbeAddOp2(v, OP_RowData, iEph, regKey);
507 sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0);
508 VdbeCoverage(v);
509 }else{
510 labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, labelBreak,
511 regOldRowid);
512 VdbeCoverage(v);
513 sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
514 VdbeCoverage(v);
517 /* If the record number will change, set register regNewRowid to
518 ** contain the new value. If the record number is not being modified,
519 ** then regNewRowid is the same register as regOldRowid, which is
520 ** already populated. */
521 assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
522 if( chngRowid ){
523 sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
524 sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
527 /* Compute the old pre-UPDATE content of the row being changed, if that
528 ** information is needed */
529 if( chngPk || hasFK || pTrigger ){
530 u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
531 oldmask |= sqlite3TriggerColmask(pParse,
532 pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
534 for(i=0; i<pTab->nCol; i++){
535 if( oldmask==0xffffffff
536 || (i<32 && (oldmask & MASKBIT32(i))!=0)
537 || (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
539 testcase( oldmask!=0xffffffff && i==31 );
540 sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i);
541 }else{
542 sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
545 if( chngRowid==0 && pPk==0 ){
546 sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
550 /* Populate the array of registers beginning at regNew with the new
551 ** row data. This array is used to check constants, create the new
552 ** table and index records, and as the values for any new.* references
553 ** made by triggers.
555 ** If there are one or more BEFORE triggers, then do not populate the
556 ** registers associated with columns that are (a) not modified by
557 ** this UPDATE statement and (b) not accessed by new.* references. The
558 ** values for registers not modified by the UPDATE must be reloaded from
559 ** the database after the BEFORE triggers are fired anyway (as the trigger
560 ** may have modified them). So not loading those that are not going to
561 ** be used eliminates some redundant opcodes.
563 newmask = sqlite3TriggerColmask(
564 pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
566 for(i=0; i<pTab->nCol; i++){
567 if( i==pTab->iPKey ){
568 sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
569 }else{
570 j = aXRef[i];
571 if( j>=0 ){
572 sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
573 }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
574 /* This branch loads the value of a column that will not be changed
575 ** into a register. This is done if there are no BEFORE triggers, or
576 ** if there are one or more BEFORE triggers that use this value via
577 ** a new.* reference in a trigger program.
579 testcase( i==31 );
580 testcase( i==32 );
581 sqlite3ExprCodeGetColumnToReg(pParse, pTab, i, iDataCur, regNew+i);
582 }else{
583 sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
588 /* Fire any BEFORE UPDATE triggers. This happens before constraints are
589 ** verified. One could argue that this is wrong.
591 if( tmask&TRIGGER_BEFORE ){
592 sqlite3TableAffinity(v, pTab, regNew);
593 sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
594 TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
596 /* The row-trigger may have deleted the row being updated. In this
597 ** case, jump to the next row. No updates or AFTER triggers are
598 ** required. This behavior - what happens when the row being updated
599 ** is deleted or renamed by a BEFORE trigger - is left undefined in the
600 ** documentation.
602 if( pPk ){
603 sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey);
604 VdbeCoverage(v);
605 }else{
606 sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
607 VdbeCoverage(v);
610 /* If it did not delete it, the row-trigger may still have modified
611 ** some of the columns of the row being updated. Load the values for
612 ** all columns not modified by the update statement into their
613 ** registers in case this has happened.
615 for(i=0; i<pTab->nCol; i++){
616 if( aXRef[i]<0 && i!=pTab->iPKey ){
617 sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
622 if( !isView ){
623 int addr1 = 0; /* Address of jump instruction */
625 /* Do constraint checks. */
626 assert( regOldRowid>0 );
627 sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
628 regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace,
629 aXRef);
631 /* Do FK constraint checks. */
632 if( hasFK ){
633 sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);
636 /* Delete the index entries associated with the current record. */
637 if( bReplace || chngKey ){
638 if( pPk ){
639 addr1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey);
640 }else{
641 addr1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid);
643 VdbeCoverageNeverTaken(v);
645 sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx, -1);
647 /* If changing the rowid value, or if there are foreign key constraints
648 ** to process, delete the old record. Otherwise, add a noop OP_Delete
649 ** to invoke the pre-update hook.
651 ** That (regNew==regnewRowid+1) is true is also important for the
652 ** pre-update hook. If the caller invokes preupdate_new(), the returned
653 ** value is copied from memory cell (regNewRowid+1+iCol), where iCol
654 ** is the column index supplied by the user.
656 assert( regNew==regNewRowid+1 );
657 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
658 sqlite3VdbeAddOp3(v, OP_Delete, iDataCur,
659 OPFLAG_ISUPDATE | ((hasFK>1 || chngKey) ? 0 : OPFLAG_ISNOOP),
660 regNewRowid
662 if( eOnePass==ONEPASS_MULTI ){
663 assert( hasFK==0 && chngKey==0 );
664 sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
666 if( !pParse->nested ){
667 sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
669 #else
670 if( hasFK>1 || chngKey ){
671 sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
673 #endif
674 if( bReplace || chngKey ){
675 sqlite3VdbeJumpHere(v, addr1);
678 if( hasFK ){
679 sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
682 /* Insert the new index entries and the new record. */
683 sqlite3CompleteInsertion(
684 pParse, pTab, iDataCur, iIdxCur, regNewRowid, aRegIdx,
685 OPFLAG_ISUPDATE | (eOnePass==ONEPASS_MULTI ? OPFLAG_SAVEPOSITION : 0),
686 0, 0
689 /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
690 ** handle rows (possibly in other tables) that refer via a foreign key
691 ** to the row just updated. */
692 if( hasFK ){
693 sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
697 /* Increment the row counter
699 if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
700 sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
703 sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
704 TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
706 /* Repeat the above with the next record to be updated, until
707 ** all record selected by the WHERE clause have been updated.
709 if( eOnePass==ONEPASS_SINGLE ){
710 /* Nothing to do at end-of-loop for a single-pass */
711 }else if( eOnePass==ONEPASS_MULTI ){
712 sqlite3VdbeResolveLabel(v, labelContinue);
713 sqlite3WhereEnd(pWInfo);
714 }else if( pPk ){
715 sqlite3VdbeResolveLabel(v, labelContinue);
716 sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
717 }else{
718 sqlite3VdbeGoto(v, labelContinue);
720 sqlite3VdbeResolveLabel(v, labelBreak);
722 /* Update the sqlite_sequence table by storing the content of the
723 ** maximum rowid counter values recorded while inserting into
724 ** autoincrement tables.
726 if( pParse->nested==0 && pParse->pTriggerTab==0 ){
727 sqlite3AutoincrementEnd(pParse);
731 ** Return the number of rows that were changed. If this routine is
732 ** generating code because of a call to sqlite3NestedParse(), do not
733 ** invoke the callback function.
735 if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
736 sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
737 sqlite3VdbeSetNumCols(v, 1);
738 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
741 update_cleanup:
742 sqlite3AuthContextPop(&sContext);
743 sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */
744 sqlite3SrcListDelete(db, pTabList);
745 sqlite3ExprListDelete(db, pChanges);
746 sqlite3ExprDelete(db, pWhere);
747 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
748 sqlite3ExprListDelete(db, pOrderBy);
749 sqlite3ExprDelete(db, pLimit);
750 #endif
751 return;
753 /* Make sure "isView" and other macros defined above are undefined. Otherwise
754 ** they may interfere with compilation of other functions in this file
755 ** (or in another file, if this file becomes part of the amalgamation). */
756 #ifdef isView
757 #undef isView
758 #endif
759 #ifdef pTrigger
760 #undef pTrigger
761 #endif
763 #ifndef SQLITE_OMIT_VIRTUALTABLE
765 ** Generate code for an UPDATE of a virtual table.
767 ** There are two possible strategies - the default and the special
768 ** "onepass" strategy. Onepass is only used if the virtual table
769 ** implementation indicates that pWhere may match at most one row.
771 ** The default strategy is to create an ephemeral table that contains
772 ** for each row to be changed:
774 ** (A) The original rowid of that row.
775 ** (B) The revised rowid for the row.
776 ** (C) The content of every column in the row.
778 ** Then loop through the contents of this ephemeral table executing a
779 ** VUpdate for each row. When finished, drop the ephemeral table.
781 ** The "onepass" strategy does not use an ephemeral table. Instead, it
782 ** stores the same values (A, B and C above) in a register array and
783 ** makes a single invocation of VUpdate.
785 static void updateVirtualTable(
786 Parse *pParse, /* The parsing context */
787 SrcList *pSrc, /* The virtual table to be modified */
788 Table *pTab, /* The virtual table */
789 ExprList *pChanges, /* The columns to change in the UPDATE statement */
790 Expr *pRowid, /* Expression used to recompute the rowid */
791 int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
792 Expr *pWhere, /* WHERE clause of the UPDATE statement */
793 int onError /* ON CONFLICT strategy */
795 Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */
796 int ephemTab; /* Table holding the result of the SELECT */
797 int i; /* Loop counter */
798 sqlite3 *db = pParse->db; /* Database connection */
799 const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
800 WhereInfo *pWInfo;
801 int nArg = 2 + pTab->nCol; /* Number of arguments to VUpdate */
802 int regArg; /* First register in VUpdate arg array */
803 int regRec; /* Register in which to assemble record */
804 int regRowid; /* Register for ephem table rowid */
805 int iCsr = pSrc->a[0].iCursor; /* Cursor used for virtual table scan */
806 int aDummy[2]; /* Unused arg for sqlite3WhereOkOnePass() */
807 int bOnePass; /* True to use onepass strategy */
808 int addr; /* Address of OP_OpenEphemeral */
810 /* Allocate nArg registers to martial the arguments to VUpdate. Then
811 ** create and open the ephemeral table in which the records created from
812 ** these arguments will be temporarily stored. */
813 assert( v );
814 ephemTab = pParse->nTab++;
815 addr= sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, nArg);
816 regArg = pParse->nMem + 1;
817 pParse->nMem += nArg;
818 regRec = ++pParse->nMem;
819 regRowid = ++pParse->nMem;
821 /* Start scanning the virtual table */
822 pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0,0,WHERE_ONEPASS_DESIRED,0);
823 if( pWInfo==0 ) return;
825 /* Populate the argument registers. */
826 for(i=0; i<pTab->nCol; i++){
827 if( aXRef[i]>=0 ){
828 sqlite3ExprCode(pParse, pChanges->a[aXRef[i]].pExpr, regArg+2+i);
829 }else{
830 sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, i, regArg+2+i);
833 if( HasRowid(pTab) ){
834 sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg);
835 if( pRowid ){
836 sqlite3ExprCode(pParse, pRowid, regArg+1);
837 }else{
838 sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg+1);
840 }else{
841 Index *pPk; /* PRIMARY KEY index */
842 i16 iPk; /* PRIMARY KEY column */
843 pPk = sqlite3PrimaryKeyIndex(pTab);
844 assert( pPk!=0 );
845 assert( pPk->nKeyCol==1 );
846 iPk = pPk->aiColumn[0];
847 sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, iPk, regArg);
848 sqlite3VdbeAddOp2(v, OP_SCopy, regArg+2+iPk, regArg+1);
851 bOnePass = sqlite3WhereOkOnePass(pWInfo, aDummy);
853 if( bOnePass ){
854 /* If using the onepass strategy, no-op out the OP_OpenEphemeral coded
855 ** above. Also, if this is a top-level parse (not a trigger), clear the
856 ** multi-write flag so that the VM does not open a statement journal */
857 sqlite3VdbeChangeToNoop(v, addr);
858 if( sqlite3IsToplevel(pParse) ){
859 pParse->isMultiWrite = 0;
861 }else{
862 /* Create a record from the argument register contents and insert it into
863 ** the ephemeral table. */
864 sqlite3VdbeAddOp3(v, OP_MakeRecord, regArg, nArg, regRec);
865 sqlite3VdbeAddOp2(v, OP_NewRowid, ephemTab, regRowid);
866 sqlite3VdbeAddOp3(v, OP_Insert, ephemTab, regRec, regRowid);
870 if( bOnePass==0 ){
871 /* End the virtual table scan */
872 sqlite3WhereEnd(pWInfo);
874 /* Begin scannning through the ephemeral table. */
875 addr = sqlite3VdbeAddOp1(v, OP_Rewind, ephemTab); VdbeCoverage(v);
877 /* Extract arguments from the current row of the ephemeral table and
878 ** invoke the VUpdate method. */
879 for(i=0; i<nArg; i++){
880 sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i, regArg+i);
883 sqlite3VtabMakeWritable(pParse, pTab);
884 sqlite3VdbeAddOp4(v, OP_VUpdate, 0, nArg, regArg, pVTab, P4_VTAB);
885 sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
886 sqlite3MayAbort(pParse);
888 /* End of the ephemeral table scan. Or, if using the onepass strategy,
889 ** jump to here if the scan visited zero rows. */
890 if( bOnePass==0 ){
891 sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
892 sqlite3VdbeJumpHere(v, addr);
893 sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
894 }else{
895 sqlite3WhereEnd(pWInfo);
898 #endif /* SQLITE_OMIT_VIRTUALTABLE */