xref: /sqlite-3.40.0/src/delete.c (revision fb32c44e)
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       sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
557       sqlite3VdbeChangeP5(v, OE_Abort);
558       assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );
559       sqlite3MayAbort(pParse);
560       if( eOnePass==ONEPASS_SINGLE && sqlite3IsToplevel(pParse) ){
561         pParse->isMultiWrite = 0;
562       }
563     }else
564 #endif
565     {
566       int count = (pParse->nested==0);    /* True to count changes */
567       sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
568           iKey, nKey, count, OE_Default, eOnePass, aiCurOnePass[1]);
569     }
570 
571     /* End of the loop over all rowids/primary-keys. */
572     if( eOnePass!=ONEPASS_OFF ){
573       sqlite3VdbeResolveLabel(v, addrBypass);
574       sqlite3WhereEnd(pWInfo);
575     }else if( pPk ){
576       sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v);
577       sqlite3VdbeJumpHere(v, addrLoop);
578     }else{
579       sqlite3VdbeGoto(v, addrLoop);
580       sqlite3VdbeJumpHere(v, addrLoop);
581     }
582   } /* End non-truncate path */
583 
584   /* Update the sqlite_sequence table by storing the content of the
585   ** maximum rowid counter values recorded while inserting into
586   ** autoincrement tables.
587   */
588   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
589     sqlite3AutoincrementEnd(pParse);
590   }
591 
592   /* Return the number of rows that were deleted. If this routine is
593   ** generating code because of a call to sqlite3NestedParse(), do not
594   ** invoke the callback function.
595   */
596   if( memCnt ){
597     sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
598     sqlite3VdbeSetNumCols(v, 1);
599     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
600   }
601 
602 delete_from_cleanup:
603   sqlite3AuthContextPop(&sContext);
604   sqlite3SrcListDelete(db, pTabList);
605   sqlite3ExprDelete(db, pWhere);
606 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
607   sqlite3ExprListDelete(db, pOrderBy);
608   sqlite3ExprDelete(db, pLimit);
609 #endif
610   sqlite3DbFree(db, aToOpen);
611   return;
612 }
613 /* Make sure "isView" and other macros defined above are undefined. Otherwise
614 ** they may interfere with compilation of other functions in this file
615 ** (or in another file, if this file becomes part of the amalgamation).  */
616 #ifdef isView
617  #undef isView
618 #endif
619 #ifdef pTrigger
620  #undef pTrigger
621 #endif
622 
623 /*
624 ** This routine generates VDBE code that causes a single row of a
625 ** single table to be deleted.  Both the original table entry and
626 ** all indices are removed.
627 **
628 ** Preconditions:
629 **
630 **   1.  iDataCur is an open cursor on the btree that is the canonical data
631 **       store for the table.  (This will be either the table itself,
632 **       in the case of a rowid table, or the PRIMARY KEY index in the case
633 **       of a WITHOUT ROWID table.)
634 **
635 **   2.  Read/write cursors for all indices of pTab must be open as
636 **       cursor number iIdxCur+i for the i-th index.
637 **
638 **   3.  The primary key for the row to be deleted must be stored in a
639 **       sequence of nPk memory cells starting at iPk.  If nPk==0 that means
640 **       that a search record formed from OP_MakeRecord is contained in the
641 **       single memory location iPk.
642 **
643 ** eMode:
644 **   Parameter eMode may be passed either ONEPASS_OFF (0), ONEPASS_SINGLE, or
645 **   ONEPASS_MULTI.  If eMode is not ONEPASS_OFF, then the cursor
646 **   iDataCur already points to the row to delete. If eMode is ONEPASS_OFF
647 **   then this function must seek iDataCur to the entry identified by iPk
648 **   and nPk before reading from it.
649 **
650 **   If eMode is ONEPASS_MULTI, then this call is being made as part
651 **   of a ONEPASS delete that affects multiple rows. In this case, if
652 **   iIdxNoSeek is a valid cursor number (>=0) and is not the same as
653 **   iDataCur, then its position should be preserved following the delete
654 **   operation. Or, if iIdxNoSeek is not a valid cursor number, the
655 **   position of iDataCur should be preserved instead.
656 **
657 ** iIdxNoSeek:
658 **   If iIdxNoSeek is a valid cursor number (>=0) not equal to iDataCur,
659 **   then it identifies an index cursor (from within array of cursors
660 **   starting at iIdxCur) that already points to the index entry to be deleted.
661 **   Except, this optimization is disabled if there are BEFORE triggers since
662 **   the trigger body might have moved the cursor.
663 */
664 void sqlite3GenerateRowDelete(
665   Parse *pParse,     /* Parsing context */
666   Table *pTab,       /* Table containing the row to be deleted */
667   Trigger *pTrigger, /* List of triggers to (potentially) fire */
668   int iDataCur,      /* Cursor from which column data is extracted */
669   int iIdxCur,       /* First index cursor */
670   int iPk,           /* First memory cell containing the PRIMARY KEY */
671   i16 nPk,           /* Number of PRIMARY KEY memory cells */
672   u8 count,          /* If non-zero, increment the row change counter */
673   u8 onconf,         /* Default ON CONFLICT policy for triggers */
674   u8 eMode,          /* ONEPASS_OFF, _SINGLE, or _MULTI.  See above */
675   int iIdxNoSeek     /* Cursor number of cursor that does not need seeking */
676 ){
677   Vdbe *v = pParse->pVdbe;        /* Vdbe */
678   int iOld = 0;                   /* First register in OLD.* array */
679   int iLabel;                     /* Label resolved to end of generated code */
680   u8 opSeek;                      /* Seek opcode */
681 
682   /* Vdbe is guaranteed to have been allocated by this stage. */
683   assert( v );
684   VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)",
685                          iDataCur, iIdxCur, iPk, (int)nPk));
686 
687   /* Seek cursor iCur to the row to delete. If this row no longer exists
688   ** (this can happen if a trigger program has already deleted it), do
689   ** not attempt to delete it or fire any DELETE triggers.  */
690   iLabel = sqlite3VdbeMakeLabel(v);
691   opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
692   if( eMode==ONEPASS_OFF ){
693     sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
694     VdbeCoverageIf(v, opSeek==OP_NotExists);
695     VdbeCoverageIf(v, opSeek==OP_NotFound);
696   }
697 
698   /* If there are any triggers to fire, allocate a range of registers to
699   ** use for the old.* references in the triggers.  */
700   if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
701     u32 mask;                     /* Mask of OLD.* columns in use */
702     int iCol;                     /* Iterator used while populating OLD.* */
703     int addrStart;                /* Start of BEFORE trigger programs */
704 
705     /* TODO: Could use temporary registers here. Also could attempt to
706     ** avoid copying the contents of the rowid register.  */
707     mask = sqlite3TriggerColmask(
708         pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
709     );
710     mask |= sqlite3FkOldmask(pParse, pTab);
711     iOld = pParse->nMem+1;
712     pParse->nMem += (1 + pTab->nCol);
713 
714     /* Populate the OLD.* pseudo-table register array. These values will be
715     ** used by any BEFORE and AFTER triggers that exist.  */
716     sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);
717     for(iCol=0; iCol<pTab->nCol; iCol++){
718       testcase( mask!=0xffffffff && iCol==31 );
719       testcase( mask!=0xffffffff && iCol==32 );
720       if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){
721         sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+iCol+1);
722       }
723     }
724 
725     /* Invoke BEFORE DELETE trigger programs. */
726     addrStart = sqlite3VdbeCurrentAddr(v);
727     sqlite3CodeRowTrigger(pParse, pTrigger,
728         TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
729     );
730 
731     /* If any BEFORE triggers were coded, then seek the cursor to the
732     ** row to be deleted again. It may be that the BEFORE triggers moved
733     ** the cursor or already deleted the row that the cursor was
734     ** pointing to.
735     **
736     ** Also disable the iIdxNoSeek optimization since the BEFORE trigger
737     ** may have moved that cursor.
738     */
739     if( addrStart<sqlite3VdbeCurrentAddr(v) ){
740       sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
741       VdbeCoverageIf(v, opSeek==OP_NotExists);
742       VdbeCoverageIf(v, opSeek==OP_NotFound);
743       testcase( iIdxNoSeek>=0 );
744       iIdxNoSeek = -1;
745     }
746 
747     /* Do FK processing. This call checks that any FK constraints that
748     ** refer to this table (i.e. constraints attached to other tables)
749     ** are not violated by deleting this row.  */
750     sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
751   }
752 
753   /* Delete the index and table entries. Skip this step if pTab is really
754   ** a view (in which case the only effect of the DELETE statement is to
755   ** fire the INSTEAD OF triggers).
756   **
757   ** If variable 'count' is non-zero, then this OP_Delete instruction should
758   ** invoke the update-hook. The pre-update-hook, on the other hand should
759   ** be invoked unless table pTab is a system table. The difference is that
760   ** the update-hook is not invoked for rows removed by REPLACE, but the
761   ** pre-update-hook is.
762   */
763   if( pTab->pSelect==0 ){
764     u8 p5 = 0;
765     sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,iIdxNoSeek);
766     sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
767     if( pParse->nested==0 || 0==sqlite3_stricmp(pTab->zName, "sqlite_stat1") ){
768       sqlite3VdbeAppendP4(v, (char*)pTab, P4_TABLE);
769     }
770     if( eMode!=ONEPASS_OFF ){
771       sqlite3VdbeChangeP5(v, OPFLAG_AUXDELETE);
772     }
773     if( iIdxNoSeek>=0 && iIdxNoSeek!=iDataCur ){
774       sqlite3VdbeAddOp1(v, OP_Delete, iIdxNoSeek);
775     }
776     if( eMode==ONEPASS_MULTI ) p5 |= OPFLAG_SAVEPOSITION;
777     sqlite3VdbeChangeP5(v, p5);
778   }
779 
780   /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
781   ** handle rows (possibly in other tables) that refer via a foreign key
782   ** to the row just deleted. */
783   sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
784 
785   /* Invoke AFTER DELETE trigger programs. */
786   sqlite3CodeRowTrigger(pParse, pTrigger,
787       TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
788   );
789 
790   /* Jump here if the row had already been deleted before any BEFORE
791   ** trigger programs were invoked. Or if a trigger program throws a
792   ** RAISE(IGNORE) exception.  */
793   sqlite3VdbeResolveLabel(v, iLabel);
794   VdbeModuleComment((v, "END: GenRowDel()"));
795 }
796 
797 /*
798 ** This routine generates VDBE code that causes the deletion of all
799 ** index entries associated with a single row of a single table, pTab
800 **
801 ** Preconditions:
802 **
803 **   1.  A read/write cursor "iDataCur" must be open on the canonical storage
804 **       btree for the table pTab.  (This will be either the table itself
805 **       for rowid tables or to the primary key index for WITHOUT ROWID
806 **       tables.)
807 **
808 **   2.  Read/write cursors for all indices of pTab must be open as
809 **       cursor number iIdxCur+i for the i-th index.  (The pTab->pIndex
810 **       index is the 0-th index.)
811 **
812 **   3.  The "iDataCur" cursor must be already be positioned on the row
813 **       that is to be deleted.
814 */
815 void sqlite3GenerateRowIndexDelete(
816   Parse *pParse,     /* Parsing and code generating context */
817   Table *pTab,       /* Table containing the row to be deleted */
818   int iDataCur,      /* Cursor of table holding data. */
819   int iIdxCur,       /* First index cursor */
820   int *aRegIdx,      /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
821   int iIdxNoSeek     /* Do not delete from this cursor */
822 ){
823   int i;             /* Index loop counter */
824   int r1 = -1;       /* Register holding an index key */
825   int iPartIdxLabel; /* Jump destination for skipping partial index entries */
826   Index *pIdx;       /* Current index */
827   Index *pPrior = 0; /* Prior index */
828   Vdbe *v;           /* The prepared statement under construction */
829   Index *pPk;        /* PRIMARY KEY index, or NULL for rowid tables */
830 
831   v = pParse->pVdbe;
832   pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
833   for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
834     assert( iIdxCur+i!=iDataCur || pPk==pIdx );
835     if( aRegIdx!=0 && aRegIdx[i]==0 ) continue;
836     if( pIdx==pPk ) continue;
837     if( iIdxCur+i==iIdxNoSeek ) continue;
838     VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
839     r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,
840         &iPartIdxLabel, pPrior, r1);
841     sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
842         pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
843     sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
844     pPrior = pIdx;
845   }
846 }
847 
848 /*
849 ** Generate code that will assemble an index key and stores it in register
850 ** regOut.  The key with be for index pIdx which is an index on pTab.
851 ** iCur is the index of a cursor open on the pTab table and pointing to
852 ** the entry that needs indexing.  If pTab is a WITHOUT ROWID table, then
853 ** iCur must be the cursor of the PRIMARY KEY index.
854 **
855 ** Return a register number which is the first in a block of
856 ** registers that holds the elements of the index key.  The
857 ** block of registers has already been deallocated by the time
858 ** this routine returns.
859 **
860 ** If *piPartIdxLabel is not NULL, fill it in with a label and jump
861 ** to that label if pIdx is a partial index that should be skipped.
862 ** The label should be resolved using sqlite3ResolvePartIdxLabel().
863 ** A partial index should be skipped if its WHERE clause evaluates
864 ** to false or null.  If pIdx is not a partial index, *piPartIdxLabel
865 ** will be set to zero which is an empty label that is ignored by
866 ** sqlite3ResolvePartIdxLabel().
867 **
868 ** The pPrior and regPrior parameters are used to implement a cache to
869 ** avoid unnecessary register loads.  If pPrior is not NULL, then it is
870 ** a pointer to a different index for which an index key has just been
871 ** computed into register regPrior.  If the current pIdx index is generating
872 ** its key into the same sequence of registers and if pPrior and pIdx share
873 ** a column in common, then the register corresponding to that column already
874 ** holds the correct value and the loading of that register is skipped.
875 ** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK
876 ** on a table with multiple indices, and especially with the ROWID or
877 ** PRIMARY KEY columns of the index.
878 */
879 int sqlite3GenerateIndexKey(
880   Parse *pParse,       /* Parsing context */
881   Index *pIdx,         /* The index for which to generate a key */
882   int iDataCur,        /* Cursor number from which to take column data */
883   int regOut,          /* Put the new key into this register if not 0 */
884   int prefixOnly,      /* Compute only a unique prefix of the key */
885   int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */
886   Index *pPrior,       /* Previously generated index key */
887   int regPrior         /* Register holding previous generated key */
888 ){
889   Vdbe *v = pParse->pVdbe;
890   int j;
891   int regBase;
892   int nCol;
893 
894   if( piPartIdxLabel ){
895     if( pIdx->pPartIdxWhere ){
896       *piPartIdxLabel = sqlite3VdbeMakeLabel(v);
897       pParse->iSelfTab = iDataCur + 1;
898       sqlite3ExprCachePush(pParse);
899       sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
900                             SQLITE_JUMPIFNULL);
901       pParse->iSelfTab = 0;
902     }else{
903       *piPartIdxLabel = 0;
904     }
905   }
906   nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
907   regBase = sqlite3GetTempRange(pParse, nCol);
908   if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
909   for(j=0; j<nCol; j++){
910     if( pPrior
911      && pPrior->aiColumn[j]==pIdx->aiColumn[j]
912      && pPrior->aiColumn[j]!=XN_EXPR
913     ){
914       /* This column was already computed by the previous index */
915       continue;
916     }
917     sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iDataCur, j, regBase+j);
918     /* If the column affinity is REAL but the number is an integer, then it
919     ** might be stored in the table as an integer (using a compact
920     ** representation) then converted to REAL by an OP_RealAffinity opcode.
921     ** But we are getting ready to store this value back into an index, where
922     ** it should be converted by to INTEGER again.  So omit the OP_RealAffinity
923     ** opcode if it is present */
924     sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
925   }
926   if( regOut ){
927     sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
928     if( pIdx->pTable->pSelect ){
929       const char *zAff = sqlite3IndexAffinityStr(pParse->db, pIdx);
930       sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);
931     }
932   }
933   sqlite3ReleaseTempRange(pParse, regBase, nCol);
934   return regBase;
935 }
936 
937 /*
938 ** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
939 ** because it was a partial index, then this routine should be called to
940 ** resolve that label.
941 */
942 void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){
943   if( iLabel ){
944     sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel);
945     sqlite3ExprCachePop(pParse);
946   }
947 }
948