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