xref: /sqlite-3.40.0/src/delete.c (revision 8a29dfde)
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.167 2008/04/11 19:18:25 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, 0, pItem->zName, pItem->zDatabase);
30     sqlite3DeleteTable(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 #ifndef SQLITE_OMIT_VIRTUALTABLE
48       || (pTab->pMod && pTab->pMod->pModule->xUpdate==0)
49 #endif
50   ){
51     sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
52     return 1;
53   }
54 #ifndef SQLITE_OMIT_VIEW
55   if( !viewOk && pTab->pSelect ){
56     sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
57     return 1;
58   }
59 #endif
60   return 0;
61 }
62 
63 /*
64 ** Generate code that will open a table for reading.
65 */
66 void sqlite3OpenTable(
67   Parse *p,       /* Generate code into this VDBE */
68   int iCur,       /* The cursor number of the table */
69   int iDb,        /* The database index in sqlite3.aDb[] */
70   Table *pTab,    /* The table to be opened */
71   int opcode      /* OP_OpenRead or OP_OpenWrite */
72 ){
73   Vdbe *v;
74   if( IsVirtual(pTab) ) return;
75   v = sqlite3GetVdbe(p);
76   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
77   sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite), pTab->zName);
78   sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol);
79   sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
80   VdbeComment((v, "%s", pTab->zName));
81 }
82 
83 
84 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
85 /*
86 ** Evaluate a view and store its result in an ephemeral table.  The
87 ** pWhere argument is an optional WHERE clause that restricts the
88 ** set of rows in the view that are to be added to the ephemeral table.
89 */
90 void sqlite3MaterializeView(
91   Parse *pParse,       /* Parsing context */
92   Select *pView,       /* View definition */
93   Expr *pWhere,        /* Optional WHERE clause to be added */
94   u32 col_mask,        /* Render only the columns in this mask. */
95   int iCur             /* Cursor number for ephemerial table */
96 ){
97   SelectDest dest;
98   Select *pDup;
99   sqlite3 *db = pParse->db;
100 
101   pDup = sqlite3SelectDup(db, pView);
102   if( pWhere ){
103     SrcList *pFrom;
104 
105     pWhere = sqlite3ExprDup(db, pWhere);
106     pFrom = sqlite3SrcListAppendFromTerm(pParse, 0, 0, 0, 0, pDup, 0, 0);
107     pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
108   }
109   sqlite3SelectMask(pParse, pDup, col_mask);
110   sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
111   sqlite3Select(pParse, pDup, &dest, 0, 0, 0, 0);
112   sqlite3SelectDelete(pDup);
113 }
114 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
115 
116 
117 /*
118 ** Generate code for a DELETE FROM statement.
119 **
120 **     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
121 **                 \________/       \________________/
122 **                  pTabList              pWhere
123 */
124 void sqlite3DeleteFrom(
125   Parse *pParse,         /* The parser context */
126   SrcList *pTabList,     /* The table from which we should delete things */
127   Expr *pWhere           /* The WHERE clause.  May be null */
128 ){
129   Vdbe *v;               /* The virtual database engine */
130   Table *pTab;           /* The table from which records will be deleted */
131   const char *zDb;       /* Name of database holding pTab */
132   int end, addr = 0;     /* A couple addresses of generated code */
133   int i;                 /* Loop counter */
134   WhereInfo *pWInfo;     /* Information about the WHERE clause */
135   Index *pIdx;           /* For looping over indices of the table */
136   int iCur;              /* VDBE Cursor number for pTab */
137   sqlite3 *db;           /* Main database structure */
138   AuthContext sContext;  /* Authorization context */
139   int oldIdx = -1;       /* Cursor for the OLD table of AFTER triggers */
140   NameContext sNC;       /* Name context to resolve expressions in */
141   int iDb;               /* Database number */
142   int memCnt = 0;        /* Memory cell used for change counting */
143 
144 #ifndef SQLITE_OMIT_TRIGGER
145   int isView;                  /* True if attempting to delete from a view */
146   int triggers_exist = 0;      /* True if any triggers exist */
147 #endif
148   int iBeginAfterTrigger;      /* Address of after trigger program */
149   int iEndAfterTrigger;        /* Exit of after trigger program */
150   int iBeginBeforeTrigger;     /* Address of before trigger program */
151   int iEndBeforeTrigger;       /* Exit of before trigger program */
152   u32 old_col_mask = 0;        /* Mask of OLD.* columns in use */
153 
154   sContext.pParse = 0;
155   db = pParse->db;
156   if( pParse->nErr || db->mallocFailed ){
157     goto delete_from_cleanup;
158   }
159   assert( pTabList->nSrc==1 );
160 
161   /* Locate the table which we want to delete.  This table has to be
162   ** put in an SrcList structure because some of the subroutines we
163   ** will be calling are designed to work with multiple tables and expect
164   ** an SrcList* parameter instead of just a Table* parameter.
165   */
166   pTab = sqlite3SrcListLookup(pParse, pTabList);
167   if( pTab==0 )  goto delete_from_cleanup;
168 
169   /* Figure out if we have any triggers and if the table being
170   ** deleted from is a view
171   */
172 #ifndef SQLITE_OMIT_TRIGGER
173   triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0);
174   isView = pTab->pSelect!=0;
175 #else
176 # define triggers_exist 0
177 # define isView 0
178 #endif
179 #ifdef SQLITE_OMIT_VIEW
180 # undef isView
181 # define isView 0
182 #endif
183 
184   if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
185     goto delete_from_cleanup;
186   }
187   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
188   assert( iDb<db->nDb );
189   zDb = db->aDb[iDb].zName;
190   if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
191     goto delete_from_cleanup;
192   }
193 
194   /* If pTab is really a view, make sure it has been initialized.
195   */
196   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
197     goto delete_from_cleanup;
198   }
199 
200   /* Allocate a cursor used to store the old.* data for a trigger.
201   */
202   if( triggers_exist ){
203     oldIdx = pParse->nTab++;
204   }
205 
206   /* Assign  cursor number to the table and all its indices.
207   */
208   assert( pTabList->nSrc==1 );
209   iCur = pTabList->a[0].iCursor = pParse->nTab++;
210   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
211     pParse->nTab++;
212   }
213 
214   /* Start the view context
215   */
216   if( isView ){
217     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
218   }
219 
220   /* Begin generating code.
221   */
222   v = sqlite3GetVdbe(pParse);
223   if( v==0 ){
224     goto delete_from_cleanup;
225   }
226   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
227   sqlite3BeginWriteOperation(pParse, triggers_exist, iDb);
228 
229   if( triggers_exist ){
230     int orconf = ((pParse->trigStack)?pParse->trigStack->orconf:OE_Default);
231     int iGoto = sqlite3VdbeAddOp0(v, OP_Goto);
232     addr = sqlite3VdbeMakeLabel(v);
233 
234     iBeginBeforeTrigger = sqlite3VdbeCurrentAddr(v);
235     (void)sqlite3CodeRowTrigger(pParse, TK_DELETE, 0, TRIGGER_BEFORE, pTab,
236         -1, oldIdx, orconf, addr, &old_col_mask, 0);
237     iEndBeforeTrigger = sqlite3VdbeAddOp0(v, OP_Goto);
238 
239     iBeginAfterTrigger = sqlite3VdbeCurrentAddr(v);
240     (void)sqlite3CodeRowTrigger(pParse, TK_DELETE, 0, TRIGGER_AFTER, pTab, -1,
241         oldIdx, orconf, addr, &old_col_mask, 0);
242     iEndAfterTrigger = sqlite3VdbeAddOp0(v, OP_Goto);
243 
244     sqlite3VdbeJumpHere(v, iGoto);
245   }
246 
247   /* If we are trying to delete from a view, realize that view into
248   ** a ephemeral table.
249   */
250   if( isView ){
251     sqlite3MaterializeView(pParse, pTab->pSelect, pWhere, old_col_mask, iCur);
252   }
253 
254   /* Resolve the column names in the WHERE clause.
255   */
256   memset(&sNC, 0, sizeof(sNC));
257   sNC.pParse = pParse;
258   sNC.pSrcList = pTabList;
259   if( sqlite3ExprResolveNames(&sNC, pWhere) ){
260     goto delete_from_cleanup;
261   }
262 
263   /* Initialize the counter of the number of rows deleted, if
264   ** we are counting rows.
265   */
266   if( db->flags & SQLITE_CountRows ){
267     memCnt = ++pParse->nMem;
268     sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
269   }
270 
271   /* Special case: A DELETE without a WHERE clause deletes everything.
272   ** It is easier just to erase the whole table.  Note, however, that
273   ** this means that the row change count will be incorrect.
274   */
275   if( pWhere==0 && !triggers_exist && !IsVirtual(pTab) ){
276     if( db->flags & SQLITE_CountRows ){
277       /* If counting rows deleted, just count the total number of
278       ** entries in the table. */
279       int addr2;
280       if( !isView ){
281         sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
282       }
283       sqlite3VdbeAddOp2(v, OP_Rewind, iCur, sqlite3VdbeCurrentAddr(v)+2);
284       addr2 = sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
285       sqlite3VdbeAddOp2(v, OP_Next, iCur, addr2);
286       sqlite3VdbeAddOp1(v, OP_Close, iCur);
287     }
288     if( !isView ){
289       sqlite3VdbeAddOp2(v, OP_Clear, pTab->tnum, iDb);
290       if( !pParse->nested ){
291         sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
292       }
293       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
294         assert( pIdx->pSchema==pTab->pSchema );
295         sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
296       }
297     }
298   }
299   /* The usual case: There is a WHERE clause so we have to scan through
300   ** the table and pick which records to delete.
301   */
302   else{
303     int iRowid = ++pParse->nMem;    /* Used for storing rowid values. */
304 
305     /* Begin the database scan
306     */
307     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0);
308     if( pWInfo==0 ) goto delete_from_cleanup;
309 
310     /* Remember the rowid of every item to be deleted.
311     */
312     sqlite3VdbeAddOp2(v, IsVirtual(pTab) ? OP_VRowid : OP_Rowid, iCur, iRowid);
313     sqlite3VdbeAddOp1(v, OP_FifoWrite, iRowid);
314     if( db->flags & SQLITE_CountRows ){
315       sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
316     }
317 
318     /* End the database scan loop.
319     */
320     sqlite3WhereEnd(pWInfo);
321 
322     /* Open the pseudo-table used to store OLD if there are triggers.
323     */
324     if( triggers_exist ){
325       sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol);
326       sqlite3VdbeAddOp1(v, OP_OpenPseudo, oldIdx);
327     }
328 
329     /* Delete every item whose key was written to the list during the
330     ** database scan.  We have to delete items after the scan is complete
331     ** because deleting an item can change the scan order.
332     */
333     end = sqlite3VdbeMakeLabel(v);
334 
335     if( !isView ){
336       /* Open cursors for the table we are deleting from and
337       ** all its indices.
338       */
339       sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
340     }
341 
342     /* This is the beginning of the delete loop. If a trigger encounters
343     ** an IGNORE constraint, it jumps back to here.
344     */
345     if( triggers_exist ){
346       sqlite3VdbeResolveLabel(v, addr);
347     }
348     addr = sqlite3VdbeAddOp2(v, OP_FifoRead, iRowid, end);
349 
350     if( triggers_exist ){
351       int iData = ++pParse->nMem;   /* For storing row data of OLD table */
352 
353       /* If the record is no longer present in the table, jump to the
354       ** next iteration of the loop through the contents of the fifo.
355       */
356       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, iRowid);
357 
358       /* Populate the OLD.* pseudo-table */
359       if( old_col_mask ){
360         sqlite3VdbeAddOp2(v, OP_RowData, iCur, iData);
361       }else{
362         sqlite3VdbeAddOp2(v, OP_Null, 0, iData);
363       }
364       sqlite3VdbeAddOp3(v, OP_Insert, oldIdx, iData, iRowid);
365 
366       /* Jump back and run the BEFORE triggers */
367       sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginBeforeTrigger);
368       sqlite3VdbeJumpHere(v, iEndBeforeTrigger);
369     }
370 
371     if( !isView ){
372       /* Delete the row */
373 #ifndef SQLITE_OMIT_VIRTUALTABLE
374       if( IsVirtual(pTab) ){
375         const char *pVtab = (const char *)pTab->pVtab;
376         pParse->pVirtualLock = pTab;
377         sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVtab, P4_VTAB);
378       }else
379 #endif
380       {
381         sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, pParse->nested==0);
382       }
383     }
384 
385     /* If there are row triggers, close all cursors then invoke
386     ** the AFTER triggers
387     */
388     if( triggers_exist ){
389       /* Jump back and run the AFTER triggers */
390       sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginAfterTrigger);
391       sqlite3VdbeJumpHere(v, iEndAfterTrigger);
392     }
393 
394     /* End of the delete loop */
395     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
396     sqlite3VdbeResolveLabel(v, end);
397 
398     /* Close the cursors after the loop if there are no row triggers */
399     if( !isView  && !IsVirtual(pTab) ){
400       for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
401         sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
402       }
403       sqlite3VdbeAddOp1(v, OP_Close, iCur);
404     }
405   }
406 
407   /*
408   ** Return the number of rows that were deleted. If this routine is
409   ** generating code because of a call to sqlite3NestedParse(), do not
410   ** invoke the callback function.
411   */
412   if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
413     sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
414     sqlite3VdbeSetNumCols(v, 1);
415     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", P4_STATIC);
416   }
417 
418 delete_from_cleanup:
419   sqlite3AuthContextPop(&sContext);
420   sqlite3SrcListDelete(pTabList);
421   sqlite3ExprDelete(pWhere);
422   return;
423 }
424 
425 /*
426 ** This routine generates VDBE code that causes a single row of a
427 ** single table to be deleted.
428 **
429 ** The VDBE must be in a particular state when this routine is called.
430 ** These are the requirements:
431 **
432 **   1.  A read/write cursor pointing to pTab, the table containing the row
433 **       to be deleted, must be opened as cursor number "base".
434 **
435 **   2.  Read/write cursors for all indices of pTab must be open as
436 **       cursor number base+i for the i-th index.
437 **
438 **   3.  The record number of the row to be deleted must be stored in
439 **       memory cell iRowid.
440 **
441 ** This routine pops the top of the stack to remove the record number
442 ** and then generates code to remove both the table record and all index
443 ** entries that point to that record.
444 */
445 void sqlite3GenerateRowDelete(
446   Parse *pParse,     /* Parsing context */
447   Table *pTab,       /* Table containing the row to be deleted */
448   int iCur,          /* Cursor number for the table */
449   int iRowid,        /* Memory cell that contains the rowid to delete */
450   int count          /* Increment the row change counter */
451 ){
452   int addr;
453   Vdbe *v;
454 
455   v = pParse->pVdbe;
456   addr = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowid);
457   sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
458   sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
459   if( count ){
460     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
461   }
462   sqlite3VdbeJumpHere(v, addr);
463 }
464 
465 /*
466 ** This routine generates VDBE code that causes the deletion of all
467 ** index entries associated with a single row of a single table.
468 **
469 ** The VDBE must be in a particular state when this routine is called.
470 ** These are the requirements:
471 **
472 **   1.  A read/write cursor pointing to pTab, the table containing the row
473 **       to be deleted, must be opened as cursor number "iCur".
474 **
475 **   2.  Read/write cursors for all indices of pTab must be open as
476 **       cursor number iCur+i for the i-th index.
477 **
478 **   3.  The "iCur" cursor must be pointing to the row that is to be
479 **       deleted.
480 */
481 void sqlite3GenerateRowIndexDelete(
482   Parse *pParse,     /* Parsing and code generating context */
483   Table *pTab,       /* Table containing the row to be deleted */
484   int iCur,          /* Cursor number for the table */
485   int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
486 ){
487   int i;
488   Index *pIdx;
489   int r1;
490 
491   for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
492     if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
493     r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
494     sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
495   }
496 }
497 
498 /*
499 ** Generate code that will assemble an index key and put it in register
500 ** regOut.  The key with be for index pIdx which is an index on pTab.
501 ** iCur is the index of a cursor open on the pTab table and pointing to
502 ** the entry that needs indexing.
503 **
504 ** Return a register number which is the first in a block of
505 ** registers that holds the elements of the index key.  The
506 ** block of registers has already been deallocated by the time
507 ** this routine returns.
508 */
509 int sqlite3GenerateIndexKey(
510   Parse *pParse,     /* Parsing context */
511   Index *pIdx,       /* The index for which to generate a key */
512   int iCur,          /* Cursor number for the pIdx->pTable table */
513   int regOut,        /* Write the new index key to this register */
514   int doMakeRec      /* Run the OP_MakeRecord instruction if true */
515 ){
516   Vdbe *v = pParse->pVdbe;
517   int j;
518   Table *pTab = pIdx->pTable;
519   int regBase;
520   int nCol;
521 
522   nCol = pIdx->nColumn;
523   regBase = sqlite3GetTempRange(pParse, nCol+1);
524   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
525   for(j=0; j<nCol; j++){
526     int idx = pIdx->aiColumn[j];
527     if( idx==pTab->iPKey ){
528       sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
529     }else{
530       sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
531       sqlite3ColumnDefault(v, pTab, idx);
532     }
533   }
534   if( doMakeRec ){
535     sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
536     sqlite3IndexAffinityStr(v, pIdx);
537     sqlite3ExprCacheAffinityChange(pParse, regBase, nCol+1);
538   }
539   sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
540   return regBase;
541 }
542 
543 /* Make sure "isView" gets undefined in case this file becomes part of
544 ** the amalgamation - so that subsequent files do not see isView as a
545 ** macro. */
546 #undef isView
547