xref: /sqlite-3.40.0/src/update.c (revision 74217cc0)
1 /*
2 ** 2001 September 15
3 **
4 ** The author disclaims copyright to this source code.  In place of
5 ** a legal notice, here is a blessing:
6 **
7 **    May you do good and not evil.
8 **    May you find forgiveness for yourself and forgive others.
9 **    May you share freely, never taking more than you give.
10 **
11 *************************************************************************
12 ** This file contains C code routines that are called by the parser
13 ** to handle UPDATE statements.
14 **
15 ** $Id: update.c,v 1.112 2005/09/20 17:42:23 drh Exp $
16 */
17 #include "sqliteInt.h"
18 
19 /*
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.
23 **
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.
32 **
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.)
38 **
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.
43 */
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     if( pValue ){
51       sqlite3VdbeChangeP3(v, -1, (const char *)pValue, P3_MEM);
52     }else{
53       VdbeComment((v, "# %s.%s", pTab->zName, pCol->zName));
54     }
55   }
56 }
57 
58 /*
59 ** Process an UPDATE statement.
60 **
61 **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
62 **          \_______/ \________/     \______/       \________________/
63 *            onError   pTabList      pChanges             pWhere
64 */
65 void sqlite3Update(
66   Parse *pParse,         /* The parser context */
67   SrcList *pTabList,     /* The table in which we should change things */
68   ExprList *pChanges,    /* Things to be changed */
69   Expr *pWhere,          /* The WHERE clause.  May be null */
70   int onError            /* How to handle constraint errors */
71 ){
72   int i, j;              /* Loop counters */
73   Table *pTab;           /* The table to be updated */
74   int addr = 0;          /* VDBE instruction address of the start of the loop */
75   WhereInfo *pWInfo;     /* Information about the WHERE clause */
76   Vdbe *v;               /* The virtual database engine */
77   Index *pIdx;           /* For looping over indices */
78   int nIdx;              /* Number of indices that need updating */
79   int nIdxTotal;         /* Total number of indices */
80   int iCur;              /* VDBE Cursor number of pTab */
81   sqlite3 *db;           /* The database structure */
82   Index **apIdx = 0;     /* An array of indices that need updating too */
83   char *aIdxUsed = 0;    /* aIdxUsed[i]==1 if the i-th index is used */
84   int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
85                          ** an expression for the i-th column of the table.
86                          ** aXRef[i]==-1 if the i-th column is not changed. */
87   int chngRowid;         /* True if the record number is being changed */
88   Expr *pRowidExpr = 0;  /* Expression defining the new record number */
89   int openAll = 0;       /* True if all indices need to be opened */
90   AuthContext sContext;  /* The authorization context */
91   NameContext sNC;       /* The name-context to resolve expressions in */
92 
93 #ifndef SQLITE_OMIT_TRIGGER
94   int isView;                  /* Trying to update a view */
95   int triggers_exist = 0;      /* True if any row triggers exist */
96 #endif
97 
98   int newIdx      = -1;  /* index of trigger "new" temp table       */
99   int oldIdx      = -1;  /* index of trigger "old" temp table       */
100 
101   sContext.pParse = 0;
102   if( pParse->nErr || sqlite3_malloc_failed ) goto update_cleanup;
103   db = pParse->db;
104   assert( pTabList->nSrc==1 );
105 
106   /* Locate the table which we want to update.
107   */
108   pTab = sqlite3SrcListLookup(pParse, pTabList);
109   if( pTab==0 ) goto update_cleanup;
110 
111   /* Figure out if we have any triggers and if the table being
112   ** updated is a view
113   */
114 #ifndef SQLITE_OMIT_TRIGGER
115   triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges);
116   isView = pTab->pSelect!=0;
117 #else
118 # define triggers_exist 0
119 # define isView 0
120 #endif
121 #ifdef SQLITE_OMIT_VIEW
122 # undef isView
123 # define isView 0
124 #endif
125 
126   if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
127     goto update_cleanup;
128   }
129   if( isView ){
130     if( sqlite3ViewGetColumnNames(pParse, pTab) ){
131       goto update_cleanup;
132     }
133   }
134   aXRef = sqliteMallocRaw( sizeof(int) * pTab->nCol );
135   if( aXRef==0 ) goto update_cleanup;
136   for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
137 
138   /* If there are FOR EACH ROW triggers, allocate cursors for the
139   ** special OLD and NEW tables
140   */
141   if( triggers_exist ){
142     newIdx = pParse->nTab++;
143     oldIdx = pParse->nTab++;
144   }
145 
146   /* Allocate a cursors for the main database table and for all indices.
147   ** The index cursors might not be used, but if they are used they
148   ** need to occur right after the database cursor.  So go ahead and
149   ** allocate enough space, just in case.
150   */
151   pTabList->a[0].iCursor = iCur = pParse->nTab++;
152   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
153     pParse->nTab++;
154   }
155 
156   /* Initialize the name-context */
157   memset(&sNC, 0, sizeof(sNC));
158   sNC.pParse = pParse;
159   sNC.pSrcList = pTabList;
160 
161   /* Resolve the column names in all the expressions of the
162   ** of the UPDATE statement.  Also find the column index
163   ** for each column to be updated in the pChanges array.  For each
164   ** column to be updated, make sure we have authorization to change
165   ** that column.
166   */
167   chngRowid = 0;
168   for(i=0; i<pChanges->nExpr; i++){
169     if( sqlite3ExprResolveNames(&sNC, pChanges->a[i].pExpr) ){
170       goto update_cleanup;
171     }
172     for(j=0; j<pTab->nCol; j++){
173       if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
174         if( j==pTab->iPKey ){
175           chngRowid = 1;
176           pRowidExpr = pChanges->a[i].pExpr;
177         }
178         aXRef[j] = i;
179         break;
180       }
181     }
182     if( j>=pTab->nCol ){
183       if( sqlite3IsRowid(pChanges->a[i].zName) ){
184         chngRowid = 1;
185         pRowidExpr = pChanges->a[i].pExpr;
186       }else{
187         sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
188         goto update_cleanup;
189       }
190     }
191 #ifndef SQLITE_OMIT_AUTHORIZATION
192     {
193       int rc;
194       rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
195                            pTab->aCol[j].zName, db->aDb[pTab->iDb].zName);
196       if( rc==SQLITE_DENY ){
197         goto update_cleanup;
198       }else if( rc==SQLITE_IGNORE ){
199         aXRef[j] = -1;
200       }
201     }
202 #endif
203   }
204 
205   /* Allocate memory for the array apIdx[] and fill it with pointers to every
206   ** index that needs to be updated.  Indices only need updating if their
207   ** key includes one of the columns named in pChanges or if the record
208   ** number of the original table entry is changing.
209   */
210   for(nIdx=nIdxTotal=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdxTotal++){
211     if( chngRowid ){
212       i = 0;
213     }else {
214       for(i=0; i<pIdx->nColumn; i++){
215         if( aXRef[pIdx->aiColumn[i]]>=0 ) break;
216       }
217     }
218     if( i<pIdx->nColumn ) nIdx++;
219   }
220   if( nIdxTotal>0 ){
221     apIdx = sqliteMallocRaw( sizeof(Index*) * nIdx + nIdxTotal );
222     if( apIdx==0 ) goto update_cleanup;
223     aIdxUsed = (char*)&apIdx[nIdx];
224   }
225   for(nIdx=j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
226     if( chngRowid ){
227       i = 0;
228     }else{
229       for(i=0; i<pIdx->nColumn; i++){
230         if( aXRef[pIdx->aiColumn[i]]>=0 ) break;
231       }
232     }
233     if( i<pIdx->nColumn ){
234       if( sqlite3CheckIndexCollSeq(pParse, pIdx) ) goto update_cleanup;
235       apIdx[nIdx++] = pIdx;
236       aIdxUsed[j] = 1;
237     }else{
238       aIdxUsed[j] = 0;
239     }
240   }
241 
242   /* Resolve the column names in all the expressions in the
243   ** WHERE clause.
244   */
245   if( sqlite3ExprResolveNames(&sNC, pWhere) ){
246     goto update_cleanup;
247   }
248 
249   /* Start the view context
250   */
251   if( isView ){
252     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
253   }
254 
255   /* Begin generating code.
256   */
257   v = sqlite3GetVdbe(pParse);
258   if( v==0 ) goto update_cleanup;
259   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
260   sqlite3BeginWriteOperation(pParse, 1, pTab->iDb);
261 
262   /* If we are trying to update a view, realize that view into
263   ** a ephemeral table.
264   */
265   if( isView ){
266     Select *pView;
267     pView = sqlite3SelectDup(pTab->pSelect);
268     sqlite3Select(pParse, pView, SRT_VirtualTab, iCur, 0, 0, 0, 0);
269     sqlite3SelectDelete(pView);
270   }
271 
272   /* Begin the database scan
273   */
274   pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0);
275   if( pWInfo==0 ) goto update_cleanup;
276 
277   /* Remember the index of every item to be updated.
278   */
279   sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
280   sqlite3VdbeAddOp(v, OP_FifoWrite, 0, 0);
281 
282   /* End the database scan loop.
283   */
284   sqlite3WhereEnd(pWInfo);
285 
286   /* Initialize the count of updated rows
287   */
288   if( db->flags & SQLITE_CountRows && !pParse->trigStack ){
289     sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
290   }
291 
292   if( triggers_exist ){
293     /* Create pseudo-tables for NEW and OLD
294     */
295     sqlite3VdbeAddOp(v, OP_OpenPseudo, oldIdx, 0);
296     sqlite3VdbeAddOp(v, OP_SetNumColumns, oldIdx, pTab->nCol);
297     sqlite3VdbeAddOp(v, OP_OpenPseudo, newIdx, 0);
298     sqlite3VdbeAddOp(v, OP_SetNumColumns, newIdx, pTab->nCol);
299 
300     /* The top of the update loop for when there are triggers.
301     */
302     addr = sqlite3VdbeAddOp(v, OP_FifoRead, 0, 0);
303 
304     if( !isView ){
305       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
306       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
307       /* Open a cursor and make it point to the record that is
308       ** being updated.
309       */
310       sqlite3OpenTableForReading(v, iCur, pTab);
311     }
312     sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
313 
314     /* Generate the OLD table
315     */
316     sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
317     sqlite3VdbeAddOp(v, OP_RowData, iCur, 0);
318     sqlite3VdbeAddOp(v, OP_Insert, oldIdx, 0);
319 
320     /* Generate the NEW table
321     */
322     if( chngRowid ){
323       sqlite3ExprCodeAndCache(pParse, pRowidExpr);
324     }else{
325       sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
326     }
327     for(i=0; i<pTab->nCol; i++){
328       if( i==pTab->iPKey ){
329         sqlite3VdbeAddOp(v, OP_Null, 0, 0);
330         continue;
331       }
332       j = aXRef[i];
333       if( j<0 ){
334         sqlite3VdbeAddOp(v, OP_Column, iCur, i);
335         sqlite3ColumnDefault(v, pTab, i);
336       }else{
337         sqlite3ExprCodeAndCache(pParse, pChanges->a[j].pExpr);
338       }
339     }
340     sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
341     if( !isView ){
342       sqlite3TableAffinityStr(v, pTab);
343     }
344     if( pParse->nErr ) goto update_cleanup;
345     sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0);
346     if( !isView ){
347       sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
348     }
349 
350     /* Fire the BEFORE and INSTEAD OF triggers
351     */
352     if( sqlite3CodeRowTrigger(pParse, TK_UPDATE, pChanges, TRIGGER_BEFORE, pTab,
353           newIdx, oldIdx, onError, addr) ){
354       goto update_cleanup;
355     }
356   }
357 
358   if( !isView ){
359     /*
360     ** Open every index that needs updating.  Note that if any
361     ** index could potentially invoke a REPLACE conflict resolution
362     ** action, then we need to open all indices because we might need
363     ** to be deleting some records.
364     */
365     sqlite3VdbeAddOp(v, OP_Integer, pTab->iDb, 0);
366     sqlite3VdbeAddOp(v, OP_OpenWrite, iCur, pTab->tnum);
367     sqlite3VdbeAddOp(v, OP_SetNumColumns, iCur, pTab->nCol);
368     if( onError==OE_Replace ){
369       openAll = 1;
370     }else{
371       openAll = 0;
372       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
373         if( pIdx->onError==OE_Replace ){
374           openAll = 1;
375           break;
376         }
377       }
378     }
379     for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
380       if( openAll || aIdxUsed[i] ){
381         sqlite3VdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
382         sqlite3VdbeOp3(v, OP_OpenWrite, iCur+i+1, pIdx->tnum,
383                        (char*)&pIdx->keyInfo, P3_KEYINFO);
384         assert( pParse->nTab>iCur+i+1 );
385       }
386     }
387 
388     /* Loop over every record that needs updating.  We have to load
389     ** the old data for each record to be updated because some columns
390     ** might not change and we will need to copy the old value.
391     ** Also, the old data is needed to delete the old index entires.
392     ** So make the cursor point at the old record.
393     */
394     if( !triggers_exist ){
395       addr = sqlite3VdbeAddOp(v, OP_FifoRead, 0, 0);
396       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
397     }
398     sqlite3VdbeAddOp(v, OP_NotExists, iCur, addr);
399 
400     /* If the record number will change, push the record number as it
401     ** will be after the update. (The old record number is currently
402     ** on top of the stack.)
403     */
404     if( chngRowid ){
405       sqlite3ExprCode(pParse, pRowidExpr);
406       sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
407     }
408 
409     /* Compute new data for this record.
410     */
411     for(i=0; i<pTab->nCol; i++){
412       if( i==pTab->iPKey ){
413         sqlite3VdbeAddOp(v, OP_Null, 0, 0);
414         continue;
415       }
416       j = aXRef[i];
417       if( j<0 ){
418         sqlite3VdbeAddOp(v, OP_Column, iCur, i);
419         sqlite3ColumnDefault(v, pTab, i);
420       }else{
421         sqlite3ExprCode(pParse, pChanges->a[j].pExpr);
422       }
423     }
424 
425     /* Do constraint checks
426     */
427     sqlite3GenerateConstraintChecks(pParse, pTab, iCur, aIdxUsed, chngRowid, 1,
428                                    onError, addr);
429 
430     /* Delete the old indices for the current record.
431     */
432     sqlite3GenerateRowIndexDelete(db, v, pTab, iCur, aIdxUsed);
433 
434     /* If changing the record number, delete the old record.
435     */
436     if( chngRowid ){
437       sqlite3VdbeAddOp(v, OP_Delete, iCur, 0);
438     }
439 
440     /* Create the new index entries and the new record.
441     */
442     sqlite3CompleteInsertion(pParse, pTab, iCur, aIdxUsed, chngRowid, 1, -1);
443   }
444 
445   /* Increment the row counter
446   */
447   if( db->flags & SQLITE_CountRows && !pParse->trigStack){
448     sqlite3VdbeAddOp(v, OP_AddImm, 1, 0);
449   }
450 
451   /* If there are triggers, close all the cursors after each iteration
452   ** through the loop.  The fire the after triggers.
453   */
454   if( triggers_exist ){
455     if( !isView ){
456       for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
457         if( openAll || aIdxUsed[i] )
458           sqlite3VdbeAddOp(v, OP_Close, iCur+i+1, 0);
459       }
460       sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
461     }
462     if( sqlite3CodeRowTrigger(pParse, TK_UPDATE, pChanges, TRIGGER_AFTER, pTab,
463           newIdx, oldIdx, onError, addr) ){
464       goto update_cleanup;
465     }
466   }
467 
468   /* Repeat the above with the next record to be updated, until
469   ** all record selected by the WHERE clause have been updated.
470   */
471   sqlite3VdbeAddOp(v, OP_Goto, 0, addr);
472   sqlite3VdbeJumpHere(v, addr);
473 
474   /* Close all tables if there were no FOR EACH ROW triggers */
475   if( !triggers_exist ){
476     for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
477       if( openAll || aIdxUsed[i] ){
478         sqlite3VdbeAddOp(v, OP_Close, iCur+i+1, 0);
479       }
480     }
481     sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
482   }else{
483     sqlite3VdbeAddOp(v, OP_Close, newIdx, 0);
484     sqlite3VdbeAddOp(v, OP_Close, oldIdx, 0);
485   }
486 
487   /*
488   ** Return the number of rows that were changed. If this routine is
489   ** generating code because of a call to sqlite3NestedParse(), do not
490   ** invoke the callback function.
491   */
492   if( db->flags & SQLITE_CountRows && !pParse->trigStack && pParse->nested==0 ){
493     sqlite3VdbeAddOp(v, OP_Callback, 1, 0);
494     sqlite3VdbeSetNumCols(v, 1);
495     sqlite3VdbeSetColName(v, 0, "rows updated", P3_STATIC);
496   }
497 
498 update_cleanup:
499   sqlite3AuthContextPop(&sContext);
500   sqliteFree(apIdx);
501   sqliteFree(aXRef);
502   sqlite3SrcListDelete(pTabList);
503   sqlite3ExprListDelete(pChanges);
504   sqlite3ExprDelete(pWhere);
505   return;
506 }
507