xref: /sqlite-3.40.0/src/delete.c (revision 4dcbdbff)
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 ** in order to generate code for DELETE FROM statements.
14 **
15 ** $Id: delete.c,v 1.109 2005/07/21 18:23:20 drh Exp $
16 */
17 #include "sqliteInt.h"
18 
19 /*
20 ** Look up every table that is named in pSrc.  If any table is not found,
21 ** add an error message to pParse->zErrMsg and return NULL.  If all tables
22 ** are found, return a pointer to the last table.
23 */
24 Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
25   Table *pTab = 0;
26   int i;
27   struct SrcList_item *pItem;
28   for(i=0, pItem=pSrc->a; i<pSrc->nSrc; i++, pItem++){
29     pTab = sqlite3LocateTable(pParse, pItem->zName, pItem->zDatabase);
30     sqlite3DeleteTable(pParse->db, pItem->pTab);
31     pItem->pTab = pTab;
32     if( pTab ){
33       pTab->nRef++;
34     }
35   }
36   return pTab;
37 }
38 
39 /*
40 ** Check to make sure the given table is writable.  If it is not
41 ** writable, generate an error message and return 1.  If it is
42 ** writable return 0;
43 */
44 int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
45   if( pTab->readOnly && (pParse->db->flags & SQLITE_WriteSchema)==0
46         && pParse->nested==0 ){
47     sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
48     return 1;
49   }
50 #ifndef SQLITE_OMIT_VIEW
51   if( !viewOk && pTab->pSelect ){
52     sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
53     return 1;
54   }
55 #endif
56   return 0;
57 }
58 
59 /*
60 ** Generate code that will open a table for reading.
61 */
62 void sqlite3OpenTableForReading(
63   Vdbe *v,        /* Generate code into this VDBE */
64   int iCur,       /* The cursor number of the table */
65   Table *pTab     /* The table to be opened */
66 ){
67   sqlite3VdbeAddOp(v, OP_Integer, pTab->iDb, 0);
68   VdbeComment((v, "# %s", pTab->zName));
69   sqlite3VdbeAddOp(v, OP_OpenRead, iCur, pTab->tnum);
70   sqlite3VdbeAddOp(v, OP_SetNumColumns, iCur, pTab->nCol);
71 }
72 
73 
74 /*
75 ** Generate code for a DELETE FROM statement.
76 **
77 **     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
78 **                 \________/       \________________/
79 **                  pTabList              pWhere
80 */
81 void sqlite3DeleteFrom(
82   Parse *pParse,         /* The parser context */
83   SrcList *pTabList,     /* The table from which we should delete things */
84   Expr *pWhere           /* The WHERE clause.  May be null */
85 ){
86   Vdbe *v;               /* The virtual database engine */
87   Table *pTab;           /* The table from which records will be deleted */
88   const char *zDb;       /* Name of database holding pTab */
89   int end, addr = 0;     /* A couple addresses of generated code */
90   int i;                 /* Loop counter */
91   WhereInfo *pWInfo;     /* Information about the WHERE clause */
92   Index *pIdx;           /* For looping over indices of the table */
93   int iCur;              /* VDBE Cursor number for pTab */
94   sqlite3 *db;           /* Main database structure */
95   AuthContext sContext;  /* Authorization context */
96   int oldIdx = -1;       /* Cursor for the OLD table of AFTER triggers */
97   NameContext sNC;       /* Name context to resolve expressions in */
98 
99 #ifndef SQLITE_OMIT_TRIGGER
100   int isView;                  /* True if attempting to delete from a view */
101   int triggers_exist = 0;      /* True if any triggers exist */
102 #endif
103 
104   sContext.pParse = 0;
105   if( pParse->nErr || sqlite3_malloc_failed ){
106     goto delete_from_cleanup;
107   }
108   db = pParse->db;
109   assert( pTabList->nSrc==1 );
110 
111   /* Locate the table which we want to delete.  This table has to be
112   ** put in an SrcList structure because some of the subroutines we
113   ** will be calling are designed to work with multiple tables and expect
114   ** an SrcList* parameter instead of just a Table* parameter.
115   */
116   pTab = sqlite3SrcListLookup(pParse, pTabList);
117   if( pTab==0 )  goto delete_from_cleanup;
118 
119   /* Figure out if we have any triggers and if the table being
120   ** deleted from is a view
121   */
122 #ifndef SQLITE_OMIT_TRIGGER
123   triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0);
124   isView = pTab->pSelect!=0;
125 #else
126 # define triggers_exist 0
127 # define isView 0
128 #endif
129 #ifdef SQLITE_OMIT_VIEW
130 # undef isView
131 # define isView 0
132 #endif
133 
134   if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
135     goto delete_from_cleanup;
136   }
137   assert( pTab->iDb<db->nDb );
138   zDb = db->aDb[pTab->iDb].zName;
139   if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
140     goto delete_from_cleanup;
141   }
142 
143   /* If pTab is really a view, make sure it has been initialized.
144   */
145   if( isView && sqlite3ViewGetColumnNames(pParse, pTab) ){
146     goto delete_from_cleanup;
147   }
148 
149   /* Allocate a cursor used to store the old.* data for a trigger.
150   */
151   if( triggers_exist ){
152     oldIdx = pParse->nTab++;
153   }
154 
155   /* Resolve the column names in the WHERE clause.
156   */
157   assert( pTabList->nSrc==1 );
158   iCur = pTabList->a[0].iCursor = pParse->nTab++;
159   memset(&sNC, 0, sizeof(sNC));
160   sNC.pParse = pParse;
161   sNC.pSrcList = pTabList;
162   if( sqlite3ExprResolveNames(&sNC, pWhere) ){
163     goto delete_from_cleanup;
164   }
165 
166   /* Start the view context
167   */
168   if( isView ){
169     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
170   }
171 
172   /* Begin generating code.
173   */
174   v = sqlite3GetVdbe(pParse);
175   if( v==0 ){
176     goto delete_from_cleanup;
177   }
178   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
179   sqlite3BeginWriteOperation(pParse, triggers_exist, pTab->iDb);
180 
181   /* If we are trying to delete from a view, construct that view into
182   ** a temporary table.
183   */
184   if( isView ){
185     Select *pView = sqlite3SelectDup(pTab->pSelect);
186     sqlite3Select(pParse, pView, SRT_TempTable, iCur, 0, 0, 0, 0);
187     sqlite3SelectDelete(pView);
188   }
189 
190   /* Initialize the counter of the number of rows deleted, if
191   ** we are counting rows.
192   */
193   if( db->flags & SQLITE_CountRows ){
194     sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
195   }
196 
197   /* Special case: A DELETE without a WHERE clause deletes everything.
198   ** It is easier just to erase the whole table.  Note, however, that
199   ** this means that the row change count will be incorrect.
200   */
201   if( pWhere==0 && !triggers_exist ){
202     if( db->flags & SQLITE_CountRows ){
203       /* If counting rows deleted, just count the total number of
204       ** entries in the table. */
205       int endOfLoop = sqlite3VdbeMakeLabel(v);
206       int addr;
207       if( !isView ){
208         sqlite3OpenTableForReading(v, iCur, pTab);
209       }
210       sqlite3VdbeAddOp(v, OP_Rewind, iCur, sqlite3VdbeCurrentAddr(v)+2);
211       addr = sqlite3VdbeAddOp(v, OP_AddImm, 1, 0);
212       sqlite3VdbeAddOp(v, OP_Next, iCur, addr);
213       sqlite3VdbeResolveLabel(v, endOfLoop);
214       sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
215     }
216     if( !isView ){
217       sqlite3VdbeAddOp(v, OP_Clear, pTab->tnum, pTab->iDb);
218       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
219         sqlite3VdbeAddOp(v, OP_Clear, pIdx->tnum, pIdx->iDb);
220       }
221     }
222   }
223 
224   /* The usual case: There is a WHERE clause so we have to scan through
225   ** the table and pick which records to delete.
226   */
227   else{
228     /* Ensure all required collation sequences are available. */
229     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
230       if( sqlite3CheckIndexCollSeq(pParse, pIdx) ){
231         goto delete_from_cleanup;
232       }
233     }
234 
235     /* Begin the database scan
236     */
237     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0);
238     if( pWInfo==0 ) goto delete_from_cleanup;
239 
240     /* Remember the rowid of every item to be deleted.
241     */
242     sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
243     sqlite3VdbeAddOp(v, OP_FifoWrite, 0, 0);
244     if( db->flags & SQLITE_CountRows ){
245       sqlite3VdbeAddOp(v, OP_AddImm, 1, 0);
246     }
247 
248     /* End the database scan loop.
249     */
250     sqlite3WhereEnd(pWInfo);
251 
252     /* Open the pseudo-table used to store OLD if there are triggers.
253     */
254     if( triggers_exist ){
255       sqlite3VdbeAddOp(v, OP_OpenPseudo, oldIdx, 0);
256       sqlite3VdbeAddOp(v, OP_SetNumColumns, oldIdx, pTab->nCol);
257     }
258 
259     /* Delete every item whose key was written to the list during the
260     ** database scan.  We have to delete items after the scan is complete
261     ** because deleting an item can change the scan order.
262     */
263     end = sqlite3VdbeMakeLabel(v);
264 
265     /* This is the beginning of the delete loop when there are
266     ** row triggers.
267     */
268     if( triggers_exist ){
269       addr = sqlite3VdbeAddOp(v, OP_FifoRead, 0, end);
270       if( !isView ){
271         sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
272         sqlite3OpenTableForReading(v, iCur, pTab);
273       }
274       sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
275       sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
276       sqlite3VdbeAddOp(v, OP_RowData, iCur, 0);
277       sqlite3VdbeAddOp(v, OP_Insert, oldIdx, 0);
278       if( !isView ){
279         sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
280       }
281 
282       (void)sqlite3CodeRowTrigger(pParse, TK_DELETE, 0, TRIGGER_BEFORE, pTab,
283           -1, oldIdx, (pParse->trigStack)?pParse->trigStack->orconf:OE_Default,
284           addr);
285     }
286 
287     if( !isView ){
288       /* Open cursors for the table we are deleting from and all its
289       ** indices.  If there are row triggers, this happens inside the
290       ** OP_FifoRead loop because the cursor have to all be closed
291       ** before the trigger fires.  If there are no row triggers, the
292       ** cursors are opened only once on the outside the loop.
293       */
294       sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
295 
296       /* This is the beginning of the delete loop when there are no
297       ** row triggers */
298       if( !triggers_exist ){
299         addr = sqlite3VdbeAddOp(v, OP_FifoRead, 0, end);
300       }
301 
302       /* Delete the row */
303       sqlite3GenerateRowDelete(db, v, pTab, iCur, pParse->nested==0);
304     }
305 
306     /* If there are row triggers, close all cursors then invoke
307     ** the AFTER triggers
308     */
309     if( triggers_exist ){
310       if( !isView ){
311         for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
312           sqlite3VdbeAddOp(v, OP_Close, iCur + i, pIdx->tnum);
313         }
314         sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
315       }
316       (void)sqlite3CodeRowTrigger(pParse, TK_DELETE, 0, TRIGGER_AFTER, pTab, -1,
317           oldIdx, (pParse->trigStack)?pParse->trigStack->orconf:OE_Default,
318           addr);
319     }
320 
321     /* End of the delete loop */
322     sqlite3VdbeAddOp(v, OP_Goto, 0, addr);
323     sqlite3VdbeResolveLabel(v, end);
324 
325     /* Close the cursors after the loop if there are no row triggers */
326     if( !triggers_exist ){
327       for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
328         sqlite3VdbeAddOp(v, OP_Close, iCur + i, pIdx->tnum);
329       }
330       sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
331     }
332   }
333 
334   /*
335   ** Return the number of rows that were deleted. If this routine is
336   ** generating code because of a call to sqlite3NestedParse(), do not
337   ** invoke the callback function.
338   */
339   if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
340     sqlite3VdbeAddOp(v, OP_Callback, 1, 0);
341     sqlite3VdbeSetNumCols(v, 1);
342     sqlite3VdbeSetColName(v, 0, "rows deleted", P3_STATIC);
343   }
344 
345 delete_from_cleanup:
346   sqlite3AuthContextPop(&sContext);
347   sqlite3SrcListDelete(pTabList);
348   sqlite3ExprDelete(pWhere);
349   return;
350 }
351 
352 /*
353 ** This routine generates VDBE code that causes a single row of a
354 ** single table to be deleted.
355 **
356 ** The VDBE must be in a particular state when this routine is called.
357 ** These are the requirements:
358 **
359 **   1.  A read/write cursor pointing to pTab, the table containing the row
360 **       to be deleted, must be opened as cursor number "base".
361 **
362 **   2.  Read/write cursors for all indices of pTab must be open as
363 **       cursor number base+i for the i-th index.
364 **
365 **   3.  The record number of the row to be deleted must be on the top
366 **       of the stack.
367 **
368 ** This routine pops the top of the stack to remove the record number
369 ** and then generates code to remove both the table record and all index
370 ** entries that point to that record.
371 */
372 void sqlite3GenerateRowDelete(
373   sqlite3 *db,       /* The database containing the index */
374   Vdbe *v,           /* Generate code into this VDBE */
375   Table *pTab,       /* Table containing the row to be deleted */
376   int iCur,          /* Cursor number for the table */
377   int count          /* Increment the row change counter */
378 ){
379   int addr;
380   addr = sqlite3VdbeAddOp(v, OP_NotExists, iCur, 0);
381   sqlite3GenerateRowIndexDelete(db, v, pTab, iCur, 0);
382   sqlite3VdbeAddOp(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
383   sqlite3VdbeChangeP2(v, addr, sqlite3VdbeCurrentAddr(v));
384 }
385 
386 /*
387 ** This routine generates VDBE code that causes the deletion of all
388 ** index entries associated with a single row of a single table.
389 **
390 ** The VDBE must be in a particular state when this routine is called.
391 ** These are the requirements:
392 **
393 **   1.  A read/write cursor pointing to pTab, the table containing the row
394 **       to be deleted, must be opened as cursor number "iCur".
395 **
396 **   2.  Read/write cursors for all indices of pTab must be open as
397 **       cursor number iCur+i for the i-th index.
398 **
399 **   3.  The "iCur" cursor must be pointing to the row that is to be
400 **       deleted.
401 */
402 void sqlite3GenerateRowIndexDelete(
403   sqlite3 *db,       /* The database containing the index */
404   Vdbe *v,           /* Generate code into this VDBE */
405   Table *pTab,       /* Table containing the row to be deleted */
406   int iCur,          /* Cursor number for the table */
407   char *aIdxUsed     /* Only delete if aIdxUsed!=0 && aIdxUsed[i]!=0 */
408 ){
409   int i;
410   Index *pIdx;
411 
412   for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
413     if( aIdxUsed!=0 && aIdxUsed[i-1]==0 ) continue;
414     sqlite3GenerateIndexKey(v, pIdx, iCur);
415     sqlite3VdbeAddOp(v, OP_IdxDelete, iCur+i, 0);
416   }
417 }
418 
419 /*
420 ** Generate code that will assemble an index key and put it on the top
421 ** of the tack.  The key with be for index pIdx which is an index on pTab.
422 ** iCur is the index of a cursor open on the pTab table and pointing to
423 ** the entry that needs indexing.
424 */
425 void sqlite3GenerateIndexKey(
426   Vdbe *v,           /* Generate code into this VDBE */
427   Index *pIdx,       /* The index for which to generate a key */
428   int iCur           /* Cursor number for the pIdx->pTable table */
429 ){
430   int j;
431   Table *pTab = pIdx->pTable;
432 
433   sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
434   for(j=0; j<pIdx->nColumn; j++){
435     int idx = pIdx->aiColumn[j];
436     if( idx==pTab->iPKey ){
437       sqlite3VdbeAddOp(v, OP_Dup, j, 0);
438     }else{
439       sqlite3VdbeAddOp(v, OP_Column, iCur, idx);
440       sqlite3ColumnDefault(v, pTab, idx);
441     }
442   }
443   sqlite3VdbeAddOp(v, OP_MakeIdxRec, pIdx->nColumn, 0);
444   sqlite3IndexAffinityStr(v, pIdx);
445 }
446