xref: /sqlite-3.40.0/src/delete.c (revision e7952263)
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 #include "sqliteInt.h"
16 
17 /*
18 ** While a SrcList can in general represent multiple tables and subqueries
19 ** (as in the FROM clause of a SELECT statement) in this case it contains
20 ** the name of a single table, as one might find in an INSERT, DELETE,
21 ** or UPDATE statement.  Look up that table in the symbol table and
22 ** return a pointer.  Set an error message and return NULL if the table
23 ** name is not found or if any other error occurs.
24 **
25 ** The following fields are initialized appropriate in pSrc:
26 **
27 **    pSrc->a[0].pTab       Pointer to the Table object
28 **    pSrc->a[0].pIndex     Pointer to the INDEXED BY index, if there is one
29 **
30 */
31 Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
32   struct SrcList_item *pItem = pSrc->a;
33   Table *pTab;
34   assert( pItem && pSrc->nSrc==1 );
35   pTab = sqlite3LocateTableItem(pParse, 0, pItem);
36   sqlite3DeleteTable(pParse->db, pItem->pTab);
37   pItem->pTab = pTab;
38   if( pTab ){
39     pTab->nTabRef++;
40   }
41   if( sqlite3IndexedByLookup(pParse, pItem) ){
42     pTab = 0;
43   }
44   return pTab;
45 }
46 
47 /*
48 ** Check to make sure the given table is writable.  If it is not
49 ** writable, generate an error message and return 1.  If it is
50 ** writable return 0;
51 */
52 int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
53   /* A table is not writable under the following circumstances:
54   **
55   **   1) It is a virtual table and no implementation of the xUpdate method
56   **      has been provided, or
57   **   2) It is a system table (i.e. sqlite_master), this call is not
58   **      part of a nested parse and writable_schema pragma has not
59   **      been specified.
60   **
61   ** In either case leave an error message in pParse and return non-zero.
62   */
63   if( ( IsVirtual(pTab)
64      && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
65    || ( (pTab->tabFlags & TF_Readonly)!=0
66      && (pParse->db->flags & SQLITE_WriteSchema)==0
67      && pParse->nested==0 )
68   ){
69     sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
70     return 1;
71   }
72 
73 #ifndef SQLITE_OMIT_VIEW
74   if( !viewOk && pTab->pSelect ){
75     sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
76     return 1;
77   }
78 #endif
79   return 0;
80 }
81 
82 
83 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
84 /*
85 ** Evaluate a view and store its result in an ephemeral table.  The
86 ** pWhere argument is an optional WHERE clause that restricts the
87 ** set of rows in the view that are to be added to the ephemeral table.
88 */
89 void sqlite3MaterializeView(
90   Parse *pParse,       /* Parsing context */
91   Table *pView,        /* View definition */
92   Expr *pWhere,        /* Optional WHERE clause to be added */
93   ExprList *pOrderBy,  /* Optional ORDER BY clause */
94   Expr *pLimit,        /* Optional LIMIT clause */
95   int iCur             /* Cursor number for ephemeral table */
96 ){
97   SelectDest dest;
98   Select *pSel;
99   SrcList *pFrom;
100   sqlite3 *db = pParse->db;
101   int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
102   pWhere = sqlite3ExprDup(db, pWhere, 0);
103   pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
104   if( pFrom ){
105     assert( pFrom->nSrc==1 );
106     pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
107     pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zDbSName);
108     assert( pFrom->a[0].pOn==0 );
109     assert( pFrom->a[0].pUsing==0 );
110   }
111   pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, pOrderBy,
112                           SF_IncludeHidden, pLimit);
113   sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
114   sqlite3Select(pParse, pSel, &dest);
115   sqlite3SelectDelete(db, pSel);
116 }
117 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
118 
119 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
120 /*
121 ** Generate an expression tree to implement the WHERE, ORDER BY,
122 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
123 **
124 **     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
125 **                            \__________________________/
126 **                               pLimitWhere (pInClause)
127 */
128 Expr *sqlite3LimitWhere(
129   Parse *pParse,               /* The parser context */
130   SrcList *pSrc,               /* the FROM clause -- which tables to scan */
131   Expr *pWhere,                /* The WHERE clause.  May be null */
132   ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
133   Expr *pLimit,                /* The LIMIT clause.  May be null */
134   char *zStmtType              /* Either DELETE or UPDATE.  For err msgs. */
135 ){
136   sqlite3 *db = pParse->db;
137   Expr *pLhs = NULL;           /* LHS of IN(SELECT...) operator */
138   Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
139   ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
140   SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
141   Select *pSelect = NULL;      /* Complete SELECT tree */
142   Table *pTab;
143 
144   /* Check that there isn't an ORDER BY without a LIMIT clause.
145   */
146   if( pOrderBy && pLimit==0 ) {
147     sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
148     sqlite3ExprDelete(pParse->db, pWhere);
149     sqlite3ExprListDelete(pParse->db, pOrderBy);
150     return 0;
151   }
152 
153   /* We only need to generate a select expression if there
154   ** is a limit/offset term to enforce.
155   */
156   if( pLimit == 0 ) {
157     return pWhere;
158   }
159 
160   /* Generate a select expression tree to enforce the limit/offset
161   ** term for the DELETE or UPDATE statement.  For example:
162   **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
163   ** becomes:
164   **   DELETE FROM table_a WHERE rowid IN (
165   **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
166   **   );
167   */
168 
169   pTab = pSrc->a[0].pTab;
170   if( HasRowid(pTab) ){
171     pLhs = sqlite3PExpr(pParse, TK_ROW, 0, 0);
172     pEList = sqlite3ExprListAppend(
173         pParse, 0, sqlite3PExpr(pParse, TK_ROW, 0, 0)
174     );
175   }else{
176     Index *pPk = sqlite3PrimaryKeyIndex(pTab);
177     if( pPk->nKeyCol==1 ){
178       const char *zName = pTab->aCol[pPk->aiColumn[0]].zName;
179       pLhs = sqlite3Expr(db, TK_ID, zName);
180       pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, zName));
181     }else{
182       int i;
183       for(i=0; i<pPk->nKeyCol; i++){
184         Expr *p = sqlite3Expr(db, TK_ID, pTab->aCol[pPk->aiColumn[i]].zName);
185         pEList = sqlite3ExprListAppend(pParse, pEList, p);
186       }
187       pLhs = sqlite3PExpr(pParse, TK_VECTOR, 0, 0);
188       if( pLhs ){
189         pLhs->x.pList = sqlite3ExprListDup(db, pEList, 0);
190       }
191     }
192   }
193 
194   /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
195   ** and the SELECT subtree. */
196   pSrc->a[0].pTab = 0;
197   pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
198   pSrc->a[0].pTab = pTab;
199   pSrc->a[0].pIBIndex = 0;
200 
201   /* generate the SELECT expression tree. */
202   pSelect = sqlite3SelectNew(pParse, pEList, pSelectSrc, pWhere, 0 ,0,
203       pOrderBy,0,pLimit
204   );
205 
206   /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
207   pInClause = sqlite3PExpr(pParse, TK_IN, pLhs, 0);
208   sqlite3PExprAddSelect(pParse, pInClause, pSelect);
209   return pInClause;
210 }
211 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */
212        /*      && !defined(SQLITE_OMIT_SUBQUERY) */
213 
214 /*
215 ** Generate code for a DELETE FROM statement.
216 **
217 **     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
218 **                 \________/       \________________/
219 **                  pTabList              pWhere
220 */
221 void sqlite3DeleteFrom(
222   Parse *pParse,         /* The parser context */
223   SrcList *pTabList,     /* The table from which we should delete things */
224   Expr *pWhere,          /* The WHERE clause.  May be null */
225   ExprList *pOrderBy,    /* ORDER BY clause. May be null */
226   Expr *pLimit           /* LIMIT clause. May be null */
227 ){
228   Vdbe *v;               /* The virtual database engine */
229   Table *pTab;           /* The table from which records will be deleted */
230   int i;                 /* Loop counter */
231   WhereInfo *pWInfo;     /* Information about the WHERE clause */
232   Index *pIdx;           /* For looping over indices of the table */
233   int iTabCur;           /* Cursor number for the table */
234   int iDataCur = 0;      /* VDBE cursor for the canonical data source */
235   int iIdxCur = 0;       /* Cursor number of the first index */
236   int nIdx;              /* Number of indices */
237   sqlite3 *db;           /* Main database structure */
238   AuthContext sContext;  /* Authorization context */
239   NameContext sNC;       /* Name context to resolve expressions in */
240   int iDb;               /* Database number */
241   int memCnt = 0;        /* Memory cell used for change counting */
242   int rcauth;            /* Value returned by authorization callback */
243   int eOnePass;          /* ONEPASS_OFF or _SINGLE or _MULTI */
244   int aiCurOnePass[2];   /* The write cursors opened by WHERE_ONEPASS */
245   u8 *aToOpen = 0;       /* Open cursor iTabCur+j if aToOpen[j] is true */
246   Index *pPk;            /* The PRIMARY KEY index on the table */
247   int iPk = 0;           /* First of nPk registers holding PRIMARY KEY value */
248   i16 nPk = 1;           /* Number of columns in the PRIMARY KEY */
249   int iKey;              /* Memory cell holding key of row to be deleted */
250   i16 nKey;              /* Number of memory cells in the row key */
251   int iEphCur = 0;       /* Ephemeral table holding all primary key values */
252   int iRowSet = 0;       /* Register for rowset of rows to delete */
253   int addrBypass = 0;    /* Address of jump over the delete logic */
254   int addrLoop = 0;      /* Top of the delete loop */
255   int addrEphOpen = 0;   /* Instruction to open the Ephemeral table */
256   int bComplex;          /* True if there are triggers or FKs or
257                          ** subqueries in the WHERE clause */
258 
259 #ifndef SQLITE_OMIT_TRIGGER
260   int isView;                  /* True if attempting to delete from a view */
261   Trigger *pTrigger;           /* List of table triggers, if required */
262 #endif
263 
264   memset(&sContext, 0, sizeof(sContext));
265   db = pParse->db;
266   if( pParse->nErr || db->mallocFailed ){
267     goto delete_from_cleanup;
268   }
269   assert( pTabList->nSrc==1 );
270 
271 
272   /* Locate the table which we want to delete.  This table has to be
273   ** put in an SrcList structure because some of the subroutines we
274   ** will be calling are designed to work with multiple tables and expect
275   ** an SrcList* parameter instead of just a Table* parameter.
276   */
277   pTab = sqlite3SrcListLookup(pParse, pTabList);
278   if( pTab==0 )  goto delete_from_cleanup;
279 
280   /* Figure out if we have any triggers and if the table being
281   ** deleted from is a view
282   */
283 #ifndef SQLITE_OMIT_TRIGGER
284   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
285   isView = pTab->pSelect!=0;
286 #else
287 # define pTrigger 0
288 # define isView 0
289 #endif
290   bComplex = pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0);
291 #ifdef SQLITE_OMIT_VIEW
292 # undef isView
293 # define isView 0
294 #endif
295 
296 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
297   if( !isView ){
298     pWhere = sqlite3LimitWhere(
299         pParse, pTabList, pWhere, pOrderBy, pLimit, "DELETE"
300     );
301     pOrderBy = 0;
302     pLimit = 0;
303   }
304 #endif
305 
306   /* If pTab is really a view, make sure it has been initialized.
307   */
308   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
309     goto delete_from_cleanup;
310   }
311 
312   if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
313     goto delete_from_cleanup;
314   }
315   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
316   assert( iDb<db->nDb );
317   rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0,
318                             db->aDb[iDb].zDbSName);
319   assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
320   if( rcauth==SQLITE_DENY ){
321     goto delete_from_cleanup;
322   }
323   assert(!isView || pTrigger);
324 
325   /* Assign cursor numbers to the table and all its indices.
326   */
327   assert( pTabList->nSrc==1 );
328   iTabCur = pTabList->a[0].iCursor = pParse->nTab++;
329   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
330     pParse->nTab++;
331   }
332 
333   /* Start the view context
334   */
335   if( isView ){
336     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
337   }
338 
339   /* Begin generating code.
340   */
341   v = sqlite3GetVdbe(pParse);
342   if( v==0 ){
343     goto delete_from_cleanup;
344   }
345   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
346   sqlite3BeginWriteOperation(pParse, bComplex, iDb);
347 
348   /* If we are trying to delete from a view, realize that view into
349   ** an ephemeral table.
350   */
351 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
352   if( isView ){
353     sqlite3MaterializeView(pParse, pTab,
354         pWhere, pOrderBy, pLimit, iTabCur
355     );
356     iDataCur = iIdxCur = iTabCur;
357     pOrderBy = 0;
358     pLimit = 0;
359   }
360 #endif
361 
362   /* Resolve the column names in the WHERE clause.
363   */
364   memset(&sNC, 0, sizeof(sNC));
365   sNC.pParse = pParse;
366   sNC.pSrcList = pTabList;
367   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
368     goto delete_from_cleanup;
369   }
370 
371   /* Initialize the counter of the number of rows deleted, if
372   ** we are counting rows.
373   */
374   if( (db->flags & SQLITE_CountRows)!=0
375    && !pParse->nested
376    && !pParse->pTriggerTab
377   ){
378     memCnt = ++pParse->nMem;
379     sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
380   }
381 
382 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
383   /* Special case: A DELETE without a WHERE clause deletes everything.
384   ** It is easier just to erase the whole table. Prior to version 3.6.5,
385   ** this optimization caused the row change count (the value returned by
386   ** API function sqlite3_count_changes) to be set incorrectly.
387   **
388   ** The "rcauth==SQLITE_OK" terms is the
389   ** IMPLEMENTATION-OF: R-17228-37124 If the action code is SQLITE_DELETE and
390   ** the callback returns SQLITE_IGNORE then the DELETE operation proceeds but
391   ** the truncate optimization is disabled and all rows are deleted
392   ** individually.
393   */
394   if( rcauth==SQLITE_OK
395    && pWhere==0
396    && !bComplex
397    && !IsVirtual(pTab)
398 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
399    && db->xPreUpdateCallback==0
400 #endif
401   ){
402     assert( !isView );
403     sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
404     if( HasRowid(pTab) ){
405       sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt ? memCnt : -1,
406                         pTab->zName, P4_STATIC);
407     }
408     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
409       assert( pIdx->pSchema==pTab->pSchema );
410       sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
411     }
412   }else
413 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
414   {
415     u16 wcf = WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK|WHERE_SEEK_TABLE;
416     if( sNC.ncFlags & NC_VarSelect ) bComplex = 1;
417     wcf |= (bComplex ? 0 : WHERE_ONEPASS_MULTIROW);
418     if( HasRowid(pTab) ){
419       /* For a rowid table, initialize the RowSet to an empty set */
420       pPk = 0;
421       nPk = 1;
422       iRowSet = ++pParse->nMem;
423       sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
424     }else{
425       /* For a WITHOUT ROWID table, create an ephemeral table used to
426       ** hold all primary keys for rows to be deleted. */
427       pPk = sqlite3PrimaryKeyIndex(pTab);
428       assert( pPk!=0 );
429       nPk = pPk->nKeyCol;
430       iPk = pParse->nMem+1;
431       pParse->nMem += nPk;
432       iEphCur = pParse->nTab++;
433       addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk);
434       sqlite3VdbeSetP4KeyInfo(pParse, pPk);
435     }
436 
437     /* Construct a query to find the rowid or primary key for every row
438     ** to be deleted, based on the WHERE clause. Set variable eOnePass
439     ** to indicate the strategy used to implement this delete:
440     **
441     **  ONEPASS_OFF:    Two-pass approach - use a FIFO for rowids/PK values.
442     **  ONEPASS_SINGLE: One-pass approach - at most one row deleted.
443     **  ONEPASS_MULTI:  One-pass approach - any number of rows may be deleted.
444     */
445     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, wcf, iTabCur+1);
446     if( pWInfo==0 ) goto delete_from_cleanup;
447     eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
448     assert( IsVirtual(pTab)==0 || eOnePass!=ONEPASS_MULTI );
449     assert( IsVirtual(pTab) || bComplex || eOnePass!=ONEPASS_OFF );
450     if( eOnePass!=ONEPASS_SINGLE ) sqlite3MultiWrite(pParse);
451 
452     /* Keep track of the number of rows to be deleted */
453     if( memCnt ){
454       sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
455     }
456 
457     /* Extract the rowid or primary key for the current row */
458     if( pPk ){
459       for(i=0; i<nPk; i++){
460         assert( pPk->aiColumn[i]>=0 );
461         sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
462                                         pPk->aiColumn[i], iPk+i);
463       }
464       iKey = iPk;
465     }else{
466       iKey = pParse->nMem + 1;
467       iKey = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iTabCur, iKey, 0);
468       if( iKey>pParse->nMem ) pParse->nMem = iKey;
469     }
470 
471     if( eOnePass!=ONEPASS_OFF ){
472       /* For ONEPASS, no need to store the rowid/primary-key. There is only
473       ** one, so just keep it in its register(s) and fall through to the
474       ** delete code.  */
475       nKey = nPk; /* OP_Found will use an unpacked key */
476       aToOpen = sqlite3DbMallocRawNN(db, nIdx+2);
477       if( aToOpen==0 ){
478         sqlite3WhereEnd(pWInfo);
479         goto delete_from_cleanup;
480       }
481       memset(aToOpen, 1, nIdx+1);
482       aToOpen[nIdx+1] = 0;
483       if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
484       if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
485       if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);
486     }else{
487       if( pPk ){
488         /* Add the PK key for this row to the temporary table */
489         iKey = ++pParse->nMem;
490         nKey = 0;   /* Zero tells OP_Found to use a composite key */
491         sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey,
492             sqlite3IndexAffinityStr(pParse->db, pPk), nPk);
493         sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEphCur, iKey, iPk, nPk);
494       }else{
495         /* Add the rowid of the row to be deleted to the RowSet */
496         nKey = 1;  /* OP_DeferredSeek always uses a single rowid */
497         sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);
498       }
499     }
500 
501     /* If this DELETE cannot use the ONEPASS strategy, this is the
502     ** end of the WHERE loop */
503     if( eOnePass!=ONEPASS_OFF ){
504       addrBypass = sqlite3VdbeMakeLabel(v);
505     }else{
506       sqlite3WhereEnd(pWInfo);
507     }
508 
509     /* Unless this is a view, open cursors for the table we are
510     ** deleting from and all its indices. If this is a view, then the
511     ** only effect this statement has is to fire the INSTEAD OF
512     ** triggers.
513     */
514     if( !isView ){
515       int iAddrOnce = 0;
516       if( eOnePass==ONEPASS_MULTI ){
517         iAddrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
518       }
519       testcase( IsVirtual(pTab) );
520       sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, OPFLAG_FORDELETE,
521                                  iTabCur, aToOpen, &iDataCur, &iIdxCur);
522       assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur );
523       assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 );
524       if( eOnePass==ONEPASS_MULTI ) sqlite3VdbeJumpHere(v, iAddrOnce);
525     }
526 
527     /* Set up a loop over the rowids/primary-keys that were found in the
528     ** where-clause loop above.
529     */
530     if( eOnePass!=ONEPASS_OFF ){
531       assert( nKey==nPk );  /* OP_Found will use an unpacked key */
532       if( !IsVirtual(pTab) && aToOpen[iDataCur-iTabCur] ){
533         assert( pPk!=0 || pTab->pSelect!=0 );
534         sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);
535         VdbeCoverage(v);
536       }
537     }else if( pPk ){
538       addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v);
539       if( IsVirtual(pTab) ){
540         sqlite3VdbeAddOp3(v, OP_Column, iEphCur, 0, iKey);
541       }else{
542         sqlite3VdbeAddOp2(v, OP_RowData, iEphCur, iKey);
543       }
544       assert( nKey==0 );  /* OP_Found will use a composite key */
545     }else{
546       addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);
547       VdbeCoverage(v);
548       assert( nKey==1 );
549     }
550 
551     /* Delete the row */
552 #ifndef SQLITE_OMIT_VIRTUALTABLE
553     if( IsVirtual(pTab) ){
554       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
555       sqlite3VtabMakeWritable(pParse, pTab);
556       assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );
557       sqlite3MayAbort(pParse);
558       if( eOnePass==ONEPASS_SINGLE ){
559         sqlite3VdbeAddOp1(v, OP_Close, iTabCur);
560         if( sqlite3IsToplevel(pParse) ){
561           pParse->isMultiWrite = 0;
562         }
563       }
564       sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
565       sqlite3VdbeChangeP5(v, OE_Abort);
566     }else
567 #endif
568     {
569       int count = (pParse->nested==0);    /* True to count changes */
570       sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
571           iKey, nKey, count, OE_Default, eOnePass, aiCurOnePass[1]);
572     }
573 
574     /* End of the loop over all rowids/primary-keys. */
575     if( eOnePass!=ONEPASS_OFF ){
576       sqlite3VdbeResolveLabel(v, addrBypass);
577       sqlite3WhereEnd(pWInfo);
578     }else if( pPk ){
579       sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v);
580       sqlite3VdbeJumpHere(v, addrLoop);
581     }else{
582       sqlite3VdbeGoto(v, addrLoop);
583       sqlite3VdbeJumpHere(v, addrLoop);
584     }
585   } /* End non-truncate path */
586 
587   /* Update the sqlite_sequence table by storing the content of the
588   ** maximum rowid counter values recorded while inserting into
589   ** autoincrement tables.
590   */
591   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
592     sqlite3AutoincrementEnd(pParse);
593   }
594 
595   /* Return the number of rows that were deleted. If this routine is
596   ** generating code because of a call to sqlite3NestedParse(), do not
597   ** invoke the callback function.
598   */
599   if( memCnt ){
600     sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
601     sqlite3VdbeSetNumCols(v, 1);
602     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
603   }
604 
605 delete_from_cleanup:
606   sqlite3AuthContextPop(&sContext);
607   sqlite3SrcListDelete(db, pTabList);
608   sqlite3ExprDelete(db, pWhere);
609 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
610   sqlite3ExprListDelete(db, pOrderBy);
611   sqlite3ExprDelete(db, pLimit);
612 #endif
613   sqlite3DbFree(db, aToOpen);
614   return;
615 }
616 /* Make sure "isView" and other macros defined above are undefined. Otherwise
617 ** they may interfere with compilation of other functions in this file
618 ** (or in another file, if this file becomes part of the amalgamation).  */
619 #ifdef isView
620  #undef isView
621 #endif
622 #ifdef pTrigger
623  #undef pTrigger
624 #endif
625 
626 /*
627 ** This routine generates VDBE code that causes a single row of a
628 ** single table to be deleted.  Both the original table entry and
629 ** all indices are removed.
630 **
631 ** Preconditions:
632 **
633 **   1.  iDataCur is an open cursor on the btree that is the canonical data
634 **       store for the table.  (This will be either the table itself,
635 **       in the case of a rowid table, or the PRIMARY KEY index in the case
636 **       of a WITHOUT ROWID table.)
637 **
638 **   2.  Read/write cursors for all indices of pTab must be open as
639 **       cursor number iIdxCur+i for the i-th index.
640 **
641 **   3.  The primary key for the row to be deleted must be stored in a
642 **       sequence of nPk memory cells starting at iPk.  If nPk==0 that means
643 **       that a search record formed from OP_MakeRecord is contained in the
644 **       single memory location iPk.
645 **
646 ** eMode:
647 **   Parameter eMode may be passed either ONEPASS_OFF (0), ONEPASS_SINGLE, or
648 **   ONEPASS_MULTI.  If eMode is not ONEPASS_OFF, then the cursor
649 **   iDataCur already points to the row to delete. If eMode is ONEPASS_OFF
650 **   then this function must seek iDataCur to the entry identified by iPk
651 **   and nPk before reading from it.
652 **
653 **   If eMode is ONEPASS_MULTI, then this call is being made as part
654 **   of a ONEPASS delete that affects multiple rows. In this case, if
655 **   iIdxNoSeek is a valid cursor number (>=0) and is not the same as
656 **   iDataCur, then its position should be preserved following the delete
657 **   operation. Or, if iIdxNoSeek is not a valid cursor number, the
658 **   position of iDataCur should be preserved instead.
659 **
660 ** iIdxNoSeek:
661 **   If iIdxNoSeek is a valid cursor number (>=0) not equal to iDataCur,
662 **   then it identifies an index cursor (from within array of cursors
663 **   starting at iIdxCur) that already points to the index entry to be deleted.
664 **   Except, this optimization is disabled if there are BEFORE triggers since
665 **   the trigger body might have moved the cursor.
666 */
667 void sqlite3GenerateRowDelete(
668   Parse *pParse,     /* Parsing context */
669   Table *pTab,       /* Table containing the row to be deleted */
670   Trigger *pTrigger, /* List of triggers to (potentially) fire */
671   int iDataCur,      /* Cursor from which column data is extracted */
672   int iIdxCur,       /* First index cursor */
673   int iPk,           /* First memory cell containing the PRIMARY KEY */
674   i16 nPk,           /* Number of PRIMARY KEY memory cells */
675   u8 count,          /* If non-zero, increment the row change counter */
676   u8 onconf,         /* Default ON CONFLICT policy for triggers */
677   u8 eMode,          /* ONEPASS_OFF, _SINGLE, or _MULTI.  See above */
678   int iIdxNoSeek     /* Cursor number of cursor that does not need seeking */
679 ){
680   Vdbe *v = pParse->pVdbe;        /* Vdbe */
681   int iOld = 0;                   /* First register in OLD.* array */
682   int iLabel;                     /* Label resolved to end of generated code */
683   u8 opSeek;                      /* Seek opcode */
684 
685   /* Vdbe is guaranteed to have been allocated by this stage. */
686   assert( v );
687   VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)",
688                          iDataCur, iIdxCur, iPk, (int)nPk));
689 
690   /* Seek cursor iCur to the row to delete. If this row no longer exists
691   ** (this can happen if a trigger program has already deleted it), do
692   ** not attempt to delete it or fire any DELETE triggers.  */
693   iLabel = sqlite3VdbeMakeLabel(v);
694   opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
695   if( eMode==ONEPASS_OFF ){
696     sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
697     VdbeCoverageIf(v, opSeek==OP_NotExists);
698     VdbeCoverageIf(v, opSeek==OP_NotFound);
699   }
700 
701   /* If there are any triggers to fire, allocate a range of registers to
702   ** use for the old.* references in the triggers.  */
703   if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
704     u32 mask;                     /* Mask of OLD.* columns in use */
705     int iCol;                     /* Iterator used while populating OLD.* */
706     int addrStart;                /* Start of BEFORE trigger programs */
707 
708     /* TODO: Could use temporary registers here. Also could attempt to
709     ** avoid copying the contents of the rowid register.  */
710     mask = sqlite3TriggerColmask(
711         pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
712     );
713     mask |= sqlite3FkOldmask(pParse, pTab);
714     iOld = pParse->nMem+1;
715     pParse->nMem += (1 + pTab->nCol);
716 
717     /* Populate the OLD.* pseudo-table register array. These values will be
718     ** used by any BEFORE and AFTER triggers that exist.  */
719     sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);
720     for(iCol=0; iCol<pTab->nCol; iCol++){
721       testcase( mask!=0xffffffff && iCol==31 );
722       testcase( mask!=0xffffffff && iCol==32 );
723       if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){
724         sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+iCol+1);
725       }
726     }
727 
728     /* Invoke BEFORE DELETE trigger programs. */
729     addrStart = sqlite3VdbeCurrentAddr(v);
730     sqlite3CodeRowTrigger(pParse, pTrigger,
731         TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
732     );
733 
734     /* If any BEFORE triggers were coded, then seek the cursor to the
735     ** row to be deleted again. It may be that the BEFORE triggers moved
736     ** the cursor or already deleted the row that the cursor was
737     ** pointing to.
738     **
739     ** Also disable the iIdxNoSeek optimization since the BEFORE trigger
740     ** may have moved that cursor.
741     */
742     if( addrStart<sqlite3VdbeCurrentAddr(v) ){
743       sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
744       VdbeCoverageIf(v, opSeek==OP_NotExists);
745       VdbeCoverageIf(v, opSeek==OP_NotFound);
746       testcase( iIdxNoSeek>=0 );
747       iIdxNoSeek = -1;
748     }
749 
750     /* Do FK processing. This call checks that any FK constraints that
751     ** refer to this table (i.e. constraints attached to other tables)
752     ** are not violated by deleting this row.  */
753     sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
754   }
755 
756   /* Delete the index and table entries. Skip this step if pTab is really
757   ** a view (in which case the only effect of the DELETE statement is to
758   ** fire the INSTEAD OF triggers).
759   **
760   ** If variable 'count' is non-zero, then this OP_Delete instruction should
761   ** invoke the update-hook. The pre-update-hook, on the other hand should
762   ** be invoked unless table pTab is a system table. The difference is that
763   ** the update-hook is not invoked for rows removed by REPLACE, but the
764   ** pre-update-hook is.
765   */
766   if( pTab->pSelect==0 ){
767     u8 p5 = 0;
768     sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,iIdxNoSeek);
769     sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
770     if( pParse->nested==0 || 0==sqlite3_stricmp(pTab->zName, "sqlite_stat1") ){
771       sqlite3VdbeAppendP4(v, (char*)pTab, P4_TABLE);
772     }
773     if( eMode!=ONEPASS_OFF ){
774       sqlite3VdbeChangeP5(v, OPFLAG_AUXDELETE);
775     }
776     if( iIdxNoSeek>=0 && iIdxNoSeek!=iDataCur ){
777       sqlite3VdbeAddOp1(v, OP_Delete, iIdxNoSeek);
778     }
779     if( eMode==ONEPASS_MULTI ) p5 |= OPFLAG_SAVEPOSITION;
780     sqlite3VdbeChangeP5(v, p5);
781   }
782 
783   /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
784   ** handle rows (possibly in other tables) that refer via a foreign key
785   ** to the row just deleted. */
786   sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
787 
788   /* Invoke AFTER DELETE trigger programs. */
789   sqlite3CodeRowTrigger(pParse, pTrigger,
790       TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
791   );
792 
793   /* Jump here if the row had already been deleted before any BEFORE
794   ** trigger programs were invoked. Or if a trigger program throws a
795   ** RAISE(IGNORE) exception.  */
796   sqlite3VdbeResolveLabel(v, iLabel);
797   VdbeModuleComment((v, "END: GenRowDel()"));
798 }
799 
800 /*
801 ** This routine generates VDBE code that causes the deletion of all
802 ** index entries associated with a single row of a single table, pTab
803 **
804 ** Preconditions:
805 **
806 **   1.  A read/write cursor "iDataCur" must be open on the canonical storage
807 **       btree for the table pTab.  (This will be either the table itself
808 **       for rowid tables or to the primary key index for WITHOUT ROWID
809 **       tables.)
810 **
811 **   2.  Read/write cursors for all indices of pTab must be open as
812 **       cursor number iIdxCur+i for the i-th index.  (The pTab->pIndex
813 **       index is the 0-th index.)
814 **
815 **   3.  The "iDataCur" cursor must be already be positioned on the row
816 **       that is to be deleted.
817 */
818 void sqlite3GenerateRowIndexDelete(
819   Parse *pParse,     /* Parsing and code generating context */
820   Table *pTab,       /* Table containing the row to be deleted */
821   int iDataCur,      /* Cursor of table holding data. */
822   int iIdxCur,       /* First index cursor */
823   int *aRegIdx,      /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
824   int iIdxNoSeek     /* Do not delete from this cursor */
825 ){
826   int i;             /* Index loop counter */
827   int r1 = -1;       /* Register holding an index key */
828   int iPartIdxLabel; /* Jump destination for skipping partial index entries */
829   Index *pIdx;       /* Current index */
830   Index *pPrior = 0; /* Prior index */
831   Vdbe *v;           /* The prepared statement under construction */
832   Index *pPk;        /* PRIMARY KEY index, or NULL for rowid tables */
833 
834   v = pParse->pVdbe;
835   pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
836   for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
837     assert( iIdxCur+i!=iDataCur || pPk==pIdx );
838     if( aRegIdx!=0 && aRegIdx[i]==0 ) continue;
839     if( pIdx==pPk ) continue;
840     if( iIdxCur+i==iIdxNoSeek ) continue;
841     VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
842     r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,
843         &iPartIdxLabel, pPrior, r1);
844     sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
845         pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
846     sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
847     pPrior = pIdx;
848   }
849 }
850 
851 /*
852 ** Generate code that will assemble an index key and stores it in register
853 ** regOut.  The key with be for index pIdx which is an index on pTab.
854 ** iCur is the index of a cursor open on the pTab table and pointing to
855 ** the entry that needs indexing.  If pTab is a WITHOUT ROWID table, then
856 ** iCur must be the cursor of the PRIMARY KEY index.
857 **
858 ** Return a register number which is the first in a block of
859 ** registers that holds the elements of the index key.  The
860 ** block of registers has already been deallocated by the time
861 ** this routine returns.
862 **
863 ** If *piPartIdxLabel is not NULL, fill it in with a label and jump
864 ** to that label if pIdx is a partial index that should be skipped.
865 ** The label should be resolved using sqlite3ResolvePartIdxLabel().
866 ** A partial index should be skipped if its WHERE clause evaluates
867 ** to false or null.  If pIdx is not a partial index, *piPartIdxLabel
868 ** will be set to zero which is an empty label that is ignored by
869 ** sqlite3ResolvePartIdxLabel().
870 **
871 ** The pPrior and regPrior parameters are used to implement a cache to
872 ** avoid unnecessary register loads.  If pPrior is not NULL, then it is
873 ** a pointer to a different index for which an index key has just been
874 ** computed into register regPrior.  If the current pIdx index is generating
875 ** its key into the same sequence of registers and if pPrior and pIdx share
876 ** a column in common, then the register corresponding to that column already
877 ** holds the correct value and the loading of that register is skipped.
878 ** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK
879 ** on a table with multiple indices, and especially with the ROWID or
880 ** PRIMARY KEY columns of the index.
881 */
882 int sqlite3GenerateIndexKey(
883   Parse *pParse,       /* Parsing context */
884   Index *pIdx,         /* The index for which to generate a key */
885   int iDataCur,        /* Cursor number from which to take column data */
886   int regOut,          /* Put the new key into this register if not 0 */
887   int prefixOnly,      /* Compute only a unique prefix of the key */
888   int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */
889   Index *pPrior,       /* Previously generated index key */
890   int regPrior         /* Register holding previous generated key */
891 ){
892   Vdbe *v = pParse->pVdbe;
893   int j;
894   int regBase;
895   int nCol;
896 
897   if( piPartIdxLabel ){
898     if( pIdx->pPartIdxWhere ){
899       *piPartIdxLabel = sqlite3VdbeMakeLabel(v);
900       pParse->iSelfTab = iDataCur + 1;
901       sqlite3ExprCachePush(pParse);
902       sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
903                             SQLITE_JUMPIFNULL);
904       pParse->iSelfTab = 0;
905     }else{
906       *piPartIdxLabel = 0;
907     }
908   }
909   nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
910   regBase = sqlite3GetTempRange(pParse, nCol);
911   if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
912   for(j=0; j<nCol; j++){
913     if( pPrior
914      && pPrior->aiColumn[j]==pIdx->aiColumn[j]
915      && pPrior->aiColumn[j]!=XN_EXPR
916     ){
917       /* This column was already computed by the previous index */
918       continue;
919     }
920     sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iDataCur, j, regBase+j);
921     /* If the column affinity is REAL but the number is an integer, then it
922     ** might be stored in the table as an integer (using a compact
923     ** representation) then converted to REAL by an OP_RealAffinity opcode.
924     ** But we are getting ready to store this value back into an index, where
925     ** it should be converted by to INTEGER again.  So omit the OP_RealAffinity
926     ** opcode if it is present */
927     sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
928   }
929   if( regOut ){
930     sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
931     if( pIdx->pTable->pSelect ){
932       const char *zAff = sqlite3IndexAffinityStr(pParse->db, pIdx);
933       sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);
934     }
935   }
936   sqlite3ReleaseTempRange(pParse, regBase, nCol);
937   return regBase;
938 }
939 
940 /*
941 ** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
942 ** because it was a partial index, then this routine should be called to
943 ** resolve that label.
944 */
945 void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){
946   if( iLabel ){
947     sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel);
948     sqlite3ExprCachePop(pParse);
949   }
950 }
951