4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
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.
17 #include "sqliteInt.h"
20 ** The most recently coded instruction was an OP_Column to retrieve column
21 ** 'i' of table pTab. This routine sets the P3 parameter of the
22 ** OP_Column to the default value, if any.
24 ** The default value of a column is specified by a DEFAULT clause in the
25 ** column definition. This was either supplied by the user when the table
26 ** was created, or added later to the table definition by an ALTER TABLE
27 ** command. If the latter, then the row-records in the table btree on disk
28 ** may not contain a value for the column and the default value, taken
29 ** from the P3 parameter of the OP_Column instruction, is returned instead.
30 ** If the former, then all row-records are guaranteed to include a value
31 ** for the column and the P3 value is not required.
33 ** Column definitions created by an ALTER TABLE command may only have
34 ** literal default values specified: a number, null or a string. (If a more
35 ** complicated default expression value was provided, it is evaluated
36 ** when the ALTER TABLE is executed and one of the literal values written
37 ** into the sqlite_master table.)
39 ** Therefore, the P3 parameter is only required if the default value for
40 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
41 ** function is capable of transforming these types of expressions into
42 ** sqlite3_value objects.
44 void sqlite3ColumnDefault(Vdbe
*v
, Table
*pTab
, int i
){
45 if( pTab
&& !pTab
->pSelect
){
46 sqlite3_value
*pValue
;
47 u8 enc
= sqlite3VdbeDb(v
)->enc
;
48 Column
*pCol
= &pTab
->aCol
[i
];
49 sqlite3ValueFromExpr(pCol
->pDflt
, enc
, pCol
->affinity
, &pValue
);
50 sqlite3VdbeChangeP3(v
, -1, (const char *)pValue
, P3_MEM
);
55 ** Process an UPDATE statement.
57 ** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
58 ** \_______/ \________/ \______/ \________________/
59 * onError pTabList pChanges pWhere
62 Parse
*pParse
, /* The parser context */
63 SrcList
*pTabList
, /* The table in which we should change things */
64 ExprList
*pChanges
, /* Things to be changed */
65 Expr
*pWhere
, /* The WHERE clause. May be null */
66 int onError
/* How to handle constraint errors */
68 int i
, j
; /* Loop counters */
69 Table
*pTab
; /* The table to be updated */
70 int addr
= 0; /* VDBE instruction address of the start of the loop */
71 WhereInfo
*pWInfo
; /* Information about the WHERE clause */
72 Vdbe
*v
; /* The virtual database engine */
73 Index
*pIdx
; /* For looping over indices */
74 int nIdx
; /* Number of indices that need updating */
75 int nIdxTotal
; /* Total number of indices */
76 int iCur
; /* VDBE Cursor number of pTab */
77 sqlite3
*db
; /* The database structure */
78 Index
**apIdx
= 0; /* An array of indices that need updating too */
79 char *aIdxUsed
= 0; /* aIdxUsed[i]==1 if the i-th index is used */
80 int *aXRef
= 0; /* aXRef[i] is the index in pChanges->a[] of the
81 ** an expression for the i-th column of the table.
82 ** aXRef[i]==-1 if the i-th column is not changed. */
83 int chngRowid
; /* True if the record number is being changed */
84 Expr
*pRowidExpr
= 0; /* Expression defining the new record number */
85 int openAll
= 0; /* True if all indices need to be opened */
86 AuthContext sContext
; /* The authorization context */
87 NameContext sNC
; /* The name-context to resolve expressions in */
89 #ifndef SQLITE_OMIT_TRIGGER
90 int isView
; /* Trying to update a view */
91 int triggers_exist
= 0; /* True if any row triggers exist */
94 int newIdx
= -1; /* index of trigger "new" temp table */
95 int oldIdx
= -1; /* index of trigger "old" temp table */
98 if( pParse
->nErr
|| sqlite3_malloc_failed
) goto update_cleanup
;
100 assert( pTabList
->nSrc
==1 );
102 /* Locate the table which we want to update.
104 pTab
= sqlite3SrcListLookup(pParse
, pTabList
);
105 if( pTab
==0 ) goto update_cleanup
;
107 /* Figure out if we have any triggers and if the table being
110 #ifndef SQLITE_OMIT_TRIGGER
111 triggers_exist
= sqlite3TriggersExist(pParse
, pTab
, TK_UPDATE
, pChanges
);
112 isView
= pTab
->pSelect
!=0;
114 # define triggers_exist 0
117 #ifdef SQLITE_OMIT_VIEW
122 if( sqlite3IsReadOnly(pParse
, pTab
, triggers_exist
) ){
126 if( sqlite3ViewGetColumnNames(pParse
, pTab
) ){
130 aXRef
= sqliteMallocRaw( sizeof(int) * pTab
->nCol
);
131 if( aXRef
==0 ) goto update_cleanup
;
132 for(i
=0; i
<pTab
->nCol
; i
++) aXRef
[i
] = -1;
134 /* If there are FOR EACH ROW triggers, allocate cursors for the
135 ** special OLD and NEW tables
137 if( triggers_exist
){
138 newIdx
= pParse
->nTab
++;
139 oldIdx
= pParse
->nTab
++;
142 /* Allocate a cursors for the main database table and for all indices.
143 ** The index cursors might not be used, but if they are used they
144 ** need to occur right after the database cursor. So go ahead and
145 ** allocate enough space, just in case.
147 pTabList
->a
[0].iCursor
= iCur
= pParse
->nTab
++;
148 for(pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
){
152 /* Initialize the name-context */
153 memset(&sNC
, 0, sizeof(sNC
));
155 sNC
.pSrcList
= pTabList
;
157 /* Resolve the column names in all the expressions of the
158 ** of the UPDATE statement. Also find the column index
159 ** for each column to be updated in the pChanges array. For each
160 ** column to be updated, make sure we have authorization to change
164 for(i
=0; i
<pChanges
->nExpr
; i
++){
165 if( sqlite3ExprResolveNames(&sNC
, pChanges
->a
[i
].pExpr
) ){
168 for(j
=0; j
<pTab
->nCol
; j
++){
169 if( sqlite3StrICmp(pTab
->aCol
[j
].zName
, pChanges
->a
[i
].zName
)==0 ){
170 if( j
==pTab
->iPKey
){
172 pRowidExpr
= pChanges
->a
[i
].pExpr
;
179 if( sqlite3IsRowid(pChanges
->a
[i
].zName
) ){
181 pRowidExpr
= pChanges
->a
[i
].pExpr
;
183 sqlite3ErrorMsg(pParse
, "no such column: %s", pChanges
->a
[i
].zName
);
187 #ifndef SQLITE_OMIT_AUTHORIZATION
190 rc
= sqlite3AuthCheck(pParse
, SQLITE_UPDATE
, pTab
->zName
,
191 pTab
->aCol
[j
].zName
, db
->aDb
[pTab
->iDb
].zName
);
192 if( rc
==SQLITE_DENY
){
194 }else if( rc
==SQLITE_IGNORE
){
201 /* Allocate memory for the array apIdx[] and fill it with pointers to every
202 ** index that needs to be updated. Indices only need updating if their
203 ** key includes one of the columns named in pChanges or if the record
204 ** number of the original table entry is changing.
206 for(nIdx
=nIdxTotal
=0, pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
, nIdxTotal
++){
210 for(i
=0; i
<pIdx
->nColumn
; i
++){
211 if( aXRef
[pIdx
->aiColumn
[i
]]>=0 ) break;
214 if( i
<pIdx
->nColumn
) nIdx
++;
217 apIdx
= sqliteMallocRaw( sizeof(Index
*) * nIdx
+ nIdxTotal
);
218 if( apIdx
==0 ) goto update_cleanup
;
219 aIdxUsed
= (char*)&apIdx
[nIdx
];
221 for(nIdx
=j
=0, pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
, j
++){
225 for(i
=0; i
<pIdx
->nColumn
; i
++){
226 if( aXRef
[pIdx
->aiColumn
[i
]]>=0 ) break;
229 if( i
<pIdx
->nColumn
){
230 if( sqlite3CheckIndexCollSeq(pParse
, pIdx
) ) goto update_cleanup
;
231 apIdx
[nIdx
++] = pIdx
;
238 /* Resolve the column names in all the expressions in the
241 if( sqlite3ExprResolveNames(&sNC
, pWhere
) ){
245 /* Start the view context
248 sqlite3AuthContextPush(pParse
, &sContext
, pTab
->zName
);
251 /* Begin generating code.
253 v
= sqlite3GetVdbe(pParse
);
254 if( v
==0 ) goto update_cleanup
;
255 if( pParse
->nested
==0 ) sqlite3VdbeCountChanges(v
);
256 sqlite3BeginWriteOperation(pParse
, 1, pTab
->iDb
);
258 /* If we are trying to update a view, construct that view into
259 ** a temporary table.
263 pView
= sqlite3SelectDup(pTab
->pSelect
);
264 sqlite3Select(pParse
, pView
, SRT_TempTable
, iCur
, 0, 0, 0, 0);
265 sqlite3SelectDelete(pView
);
268 /* Begin the database scan
270 pWInfo
= sqlite3WhereBegin(pParse
, pTabList
, pWhere
, 0);
271 if( pWInfo
==0 ) goto update_cleanup
;
273 /* Remember the index of every item to be updated.
275 sqlite3VdbeAddOp(v
, OP_Rowid
, iCur
, 0);
276 sqlite3VdbeAddOp(v
, OP_ListWrite
, 0, 0);
278 /* End the database scan loop.
280 sqlite3WhereEnd(pWInfo
);
282 /* Initialize the count of updated rows
284 if( db
->flags
& SQLITE_CountRows
&& !pParse
->trigStack
){
285 sqlite3VdbeAddOp(v
, OP_Integer
, 0, 0);
288 if( triggers_exist
){
289 /* Create pseudo-tables for NEW and OLD
291 sqlite3VdbeAddOp(v
, OP_OpenPseudo
, oldIdx
, 0);
292 sqlite3VdbeAddOp(v
, OP_SetNumColumns
, oldIdx
, pTab
->nCol
);
293 sqlite3VdbeAddOp(v
, OP_OpenPseudo
, newIdx
, 0);
294 sqlite3VdbeAddOp(v
, OP_SetNumColumns
, newIdx
, pTab
->nCol
);
296 /* The top of the update loop for when there are triggers.
298 sqlite3VdbeAddOp(v
, OP_ListRewind
, 0, 0);
299 addr
= sqlite3VdbeAddOp(v
, OP_ListRead
, 0, 0);
302 sqlite3VdbeAddOp(v
, OP_Dup
, 0, 0);
303 sqlite3VdbeAddOp(v
, OP_Dup
, 0, 0);
304 /* Open a cursor and make it point to the record that is
307 sqlite3OpenTableForReading(v
, iCur
, pTab
);
309 sqlite3VdbeAddOp(v
, OP_MoveGe
, iCur
, 0);
311 /* Generate the OLD table
313 sqlite3VdbeAddOp(v
, OP_Rowid
, iCur
, 0);
314 sqlite3VdbeAddOp(v
, OP_RowData
, iCur
, 0);
315 sqlite3VdbeAddOp(v
, OP_Insert
, oldIdx
, 0);
317 /* Generate the NEW table
320 sqlite3ExprCodeAndCache(pParse
, pRowidExpr
);
322 sqlite3VdbeAddOp(v
, OP_Rowid
, iCur
, 0);
324 for(i
=0; i
<pTab
->nCol
; i
++){
325 if( i
==pTab
->iPKey
){
326 sqlite3VdbeAddOp(v
, OP_Null
, 0, 0);
331 sqlite3VdbeAddOp(v
, OP_Column
, iCur
, i
);
332 sqlite3ColumnDefault(v
, pTab
, i
);
334 sqlite3ExprCodeAndCache(pParse
, pChanges
->a
[j
].pExpr
);
337 sqlite3VdbeAddOp(v
, OP_MakeRecord
, pTab
->nCol
, 0);
339 sqlite3TableAffinityStr(v
, pTab
);
341 if( pParse
->nErr
) goto update_cleanup
;
342 sqlite3VdbeAddOp(v
, OP_Insert
, newIdx
, 0);
344 sqlite3VdbeAddOp(v
, OP_Close
, iCur
, 0);
347 /* Fire the BEFORE and INSTEAD OF triggers
349 if( sqlite3CodeRowTrigger(pParse
, TK_UPDATE
, pChanges
, TRIGGER_BEFORE
, pTab
,
350 newIdx
, oldIdx
, onError
, addr
) ){
357 ** Open every index that needs updating. Note that if any
358 ** index could potentially invoke a REPLACE conflict resolution
359 ** action, then we need to open all indices because we might need
360 ** to be deleting some records.
362 sqlite3VdbeAddOp(v
, OP_Integer
, pTab
->iDb
, 0);
363 sqlite3VdbeAddOp(v
, OP_OpenWrite
, iCur
, pTab
->tnum
);
364 sqlite3VdbeAddOp(v
, OP_SetNumColumns
, iCur
, pTab
->nCol
);
365 if( onError
==OE_Replace
){
369 for(pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
){
370 if( pIdx
->onError
==OE_Replace
){
376 for(i
=0, pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
, i
++){
377 if( openAll
|| aIdxUsed
[i
] ){
378 sqlite3VdbeAddOp(v
, OP_Integer
, pIdx
->iDb
, 0);
379 sqlite3VdbeOp3(v
, OP_OpenWrite
, iCur
+i
+1, pIdx
->tnum
,
380 (char*)&pIdx
->keyInfo
, P3_KEYINFO
);
381 assert( pParse
->nTab
>iCur
+i
+1 );
385 /* Loop over every record that needs updating. We have to load
386 ** the old data for each record to be updated because some columns
387 ** might not change and we will need to copy the old value.
388 ** Also, the old data is needed to delete the old index entires.
389 ** So make the cursor point at the old record.
391 if( !triggers_exist
){
392 sqlite3VdbeAddOp(v
, OP_ListRewind
, 0, 0);
393 addr
= sqlite3VdbeAddOp(v
, OP_ListRead
, 0, 0);
394 sqlite3VdbeAddOp(v
, OP_Dup
, 0, 0);
396 sqlite3VdbeAddOp(v
, OP_NotExists
, iCur
, addr
);
398 /* If the record number will change, push the record number as it
399 ** will be after the update. (The old record number is currently
400 ** on top of the stack.)
403 sqlite3ExprCode(pParse
, pRowidExpr
);
404 sqlite3VdbeAddOp(v
, OP_MustBeInt
, 0, 0);
407 /* Compute new data for this record.
409 for(i
=0; i
<pTab
->nCol
; i
++){
410 if( i
==pTab
->iPKey
){
411 sqlite3VdbeAddOp(v
, OP_Null
, 0, 0);
416 sqlite3VdbeAddOp(v
, OP_Column
, iCur
, i
);
417 sqlite3ColumnDefault(v
, pTab
, i
);
419 sqlite3ExprCode(pParse
, pChanges
->a
[j
].pExpr
);
423 /* Do constraint checks
425 sqlite3GenerateConstraintChecks(pParse
, pTab
, iCur
, aIdxUsed
, chngRowid
, 1,
428 /* Delete the old indices for the current record.
430 sqlite3GenerateRowIndexDelete(db
, v
, pTab
, iCur
, aIdxUsed
);
432 /* If changing the record number, delete the old record.
435 sqlite3VdbeAddOp(v
, OP_Delete
, iCur
, 0);
438 /* Create the new index entries and the new record.
440 sqlite3CompleteInsertion(pParse
, pTab
, iCur
, aIdxUsed
, chngRowid
, 1, -1);
443 /* Increment the row counter
445 if( db
->flags
& SQLITE_CountRows
&& !pParse
->trigStack
){
446 sqlite3VdbeAddOp(v
, OP_AddImm
, 1, 0);
449 /* If there are triggers, close all the cursors after each iteration
450 ** through the loop. The fire the after triggers.
452 if( triggers_exist
){
454 for(i
=0, pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
, i
++){
455 if( openAll
|| aIdxUsed
[i
] )
456 sqlite3VdbeAddOp(v
, OP_Close
, iCur
+i
+1, 0);
458 sqlite3VdbeAddOp(v
, OP_Close
, iCur
, 0);
460 if( sqlite3CodeRowTrigger(pParse
, TK_UPDATE
, pChanges
, TRIGGER_AFTER
, pTab
,
461 newIdx
, oldIdx
, onError
, addr
) ){
466 /* Repeat the above with the next record to be updated, until
467 ** all record selected by the WHERE clause have been updated.
469 sqlite3VdbeAddOp(v
, OP_Goto
, 0, addr
);
470 sqlite3VdbeChangeP2(v
, addr
, sqlite3VdbeCurrentAddr(v
));
471 sqlite3VdbeAddOp(v
, OP_ListReset
, 0, 0);
473 /* Close all tables if there were no FOR EACH ROW triggers */
474 if( !triggers_exist
){
475 for(i
=0, pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
, i
++){
476 if( openAll
|| aIdxUsed
[i
] ){
477 sqlite3VdbeAddOp(v
, OP_Close
, iCur
+i
+1, 0);
480 sqlite3VdbeAddOp(v
, OP_Close
, iCur
, 0);
482 sqlite3VdbeAddOp(v
, OP_Close
, newIdx
, 0);
483 sqlite3VdbeAddOp(v
, OP_Close
, oldIdx
, 0);
487 ** Return the number of rows that were changed. If this routine is
488 ** generating code because of a call to sqlite3NestedParse(), do not
489 ** invoke the callback function.
491 if( db
->flags
& SQLITE_CountRows
&& !pParse
->trigStack
&& pParse
->nested
==0 ){
492 sqlite3VdbeAddOp(v
, OP_Callback
, 1, 0);
493 sqlite3VdbeSetNumCols(v
, 1);
494 sqlite3VdbeSetColName(v
, 0, "rows updated", P3_STATIC
);
498 sqlite3AuthContextPop(&sContext
);
501 sqlite3SrcListDelete(pTabList
);
502 sqlite3ExprListDelete(pChanges
);
503 sqlite3ExprDelete(pWhere
);