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