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