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