xref: /sqlite-3.40.0/src/delete.c (revision c8e9f681)
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       if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
451         sqlite3VdbeAddOp3(v, OP_Clear, pIdx->tnum, iDb, memCnt ? memCnt : -1);
452       }else{
453         sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
454       }
455     }
456   }else
457 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
458   {
459     u16 wcf = WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK;
460     if( sNC.ncFlags & NC_VarSelect ) bComplex = 1;
461     wcf |= (bComplex ? 0 : WHERE_ONEPASS_MULTIROW);
462     if( HasRowid(pTab) ){
463       /* For a rowid table, initialize the RowSet to an empty set */
464       pPk = 0;
465       nPk = 1;
466       iRowSet = ++pParse->nMem;
467       sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
468     }else{
469       /* For a WITHOUT ROWID table, create an ephemeral table used to
470       ** hold all primary keys for rows to be deleted. */
471       pPk = sqlite3PrimaryKeyIndex(pTab);
472       assert( pPk!=0 );
473       nPk = pPk->nKeyCol;
474       iPk = pParse->nMem+1;
475       pParse->nMem += nPk;
476       iEphCur = pParse->nTab++;
477       addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk);
478       sqlite3VdbeSetP4KeyInfo(pParse, pPk);
479     }
480 
481     /* Construct a query to find the rowid or primary key for every row
482     ** to be deleted, based on the WHERE clause. Set variable eOnePass
483     ** to indicate the strategy used to implement this delete:
484     **
485     **  ONEPASS_OFF:    Two-pass approach - use a FIFO for rowids/PK values.
486     **  ONEPASS_SINGLE: One-pass approach - at most one row deleted.
487     **  ONEPASS_MULTI:  One-pass approach - any number of rows may be deleted.
488     */
489     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0,0,wcf,iTabCur+1);
490     if( pWInfo==0 ) goto delete_from_cleanup;
491     eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
492     assert( IsVirtual(pTab)==0 || eOnePass!=ONEPASS_MULTI );
493     assert( IsVirtual(pTab) || bComplex || eOnePass!=ONEPASS_OFF );
494     if( eOnePass!=ONEPASS_SINGLE ) sqlite3MultiWrite(pParse);
495     if( sqlite3WhereUsesDeferredSeek(pWInfo) ){
496       sqlite3VdbeAddOp1(v, OP_FinishSeek, iTabCur);
497     }
498 
499     /* Keep track of the number of rows to be deleted */
500     if( memCnt ){
501       sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
502     }
503 
504     /* Extract the rowid or primary key for the current row */
505     if( pPk ){
506       for(i=0; i<nPk; i++){
507         assert( pPk->aiColumn[i]>=0 );
508         sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
509                                         pPk->aiColumn[i], iPk+i);
510       }
511       iKey = iPk;
512     }else{
513       iKey = ++pParse->nMem;
514       sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, -1, iKey);
515     }
516 
517     if( eOnePass!=ONEPASS_OFF ){
518       /* For ONEPASS, no need to store the rowid/primary-key. There is only
519       ** one, so just keep it in its register(s) and fall through to the
520       ** delete code.  */
521       nKey = nPk; /* OP_Found will use an unpacked key */
522       aToOpen = sqlite3DbMallocRawNN(db, nIdx+2);
523       if( aToOpen==0 ){
524         sqlite3WhereEnd(pWInfo);
525         goto delete_from_cleanup;
526       }
527       memset(aToOpen, 1, nIdx+1);
528       aToOpen[nIdx+1] = 0;
529       if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
530       if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
531       if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);
532       addrBypass = sqlite3VdbeMakeLabel(pParse);
533     }else{
534       if( pPk ){
535         /* Add the PK key for this row to the temporary table */
536         iKey = ++pParse->nMem;
537         nKey = 0;   /* Zero tells OP_Found to use a composite key */
538         sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey,
539             sqlite3IndexAffinityStr(pParse->db, pPk), nPk);
540         sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEphCur, iKey, iPk, nPk);
541       }else{
542         /* Add the rowid of the row to be deleted to the RowSet */
543         nKey = 1;  /* OP_DeferredSeek always uses a single rowid */
544         sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);
545       }
546       sqlite3WhereEnd(pWInfo);
547     }
548 
549     /* Unless this is a view, open cursors for the table we are
550     ** deleting from and all its indices. If this is a view, then the
551     ** only effect this statement has is to fire the INSTEAD OF
552     ** triggers.
553     */
554     if( !isView ){
555       int iAddrOnce = 0;
556       if( eOnePass==ONEPASS_MULTI ){
557         iAddrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
558       }
559       testcase( IsVirtual(pTab) );
560       sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, OPFLAG_FORDELETE,
561                                  iTabCur, aToOpen, &iDataCur, &iIdxCur);
562       assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur );
563       assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 );
564       if( eOnePass==ONEPASS_MULTI ){
565         sqlite3VdbeJumpHereOrPopInst(v, iAddrOnce);
566       }
567     }
568 
569     /* Set up a loop over the rowids/primary-keys that were found in the
570     ** where-clause loop above.
571     */
572     if( eOnePass!=ONEPASS_OFF ){
573       assert( nKey==nPk );  /* OP_Found will use an unpacked key */
574       if( !IsVirtual(pTab) && aToOpen[iDataCur-iTabCur] ){
575         assert( pPk!=0 || IsView(pTab) );
576         sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);
577         VdbeCoverage(v);
578       }
579     }else if( pPk ){
580       addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v);
581       if( IsVirtual(pTab) ){
582         sqlite3VdbeAddOp3(v, OP_Column, iEphCur, 0, iKey);
583       }else{
584         sqlite3VdbeAddOp2(v, OP_RowData, iEphCur, iKey);
585       }
586       assert( nKey==0 );  /* OP_Found will use a composite key */
587     }else{
588       addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);
589       VdbeCoverage(v);
590       assert( nKey==1 );
591     }
592 
593     /* Delete the row */
594 #ifndef SQLITE_OMIT_VIRTUALTABLE
595     if( IsVirtual(pTab) ){
596       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
597       sqlite3VtabMakeWritable(pParse, pTab);
598       assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );
599       sqlite3MayAbort(pParse);
600       if( eOnePass==ONEPASS_SINGLE ){
601         sqlite3VdbeAddOp1(v, OP_Close, iTabCur);
602         if( sqlite3IsToplevel(pParse) ){
603           pParse->isMultiWrite = 0;
604         }
605       }
606       sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
607       sqlite3VdbeChangeP5(v, OE_Abort);
608     }else
609 #endif
610     {
611       int count = (pParse->nested==0);    /* True to count changes */
612       sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
613           iKey, nKey, count, OE_Default, eOnePass, aiCurOnePass[1]);
614     }
615 
616     /* End of the loop over all rowids/primary-keys. */
617     if( eOnePass!=ONEPASS_OFF ){
618       sqlite3VdbeResolveLabel(v, addrBypass);
619       sqlite3WhereEnd(pWInfo);
620     }else if( pPk ){
621       sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v);
622       sqlite3VdbeJumpHere(v, addrLoop);
623     }else{
624       sqlite3VdbeGoto(v, addrLoop);
625       sqlite3VdbeJumpHere(v, addrLoop);
626     }
627   } /* End non-truncate path */
628 
629   /* Update the sqlite_sequence table by storing the content of the
630   ** maximum rowid counter values recorded while inserting into
631   ** autoincrement tables.
632   */
633   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
634     sqlite3AutoincrementEnd(pParse);
635   }
636 
637   /* Return the number of rows that were deleted. If this routine is
638   ** generating code because of a call to sqlite3NestedParse(), do not
639   ** invoke the callback function.
640   */
641   if( memCnt ){
642     sqlite3CodeChangeCount(v, memCnt, "rows deleted");
643   }
644 
645 delete_from_cleanup:
646   sqlite3AuthContextPop(&sContext);
647   sqlite3SrcListDelete(db, pTabList);
648   sqlite3ExprDelete(db, pWhere);
649 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
650   sqlite3ExprListDelete(db, pOrderBy);
651   sqlite3ExprDelete(db, pLimit);
652 #endif
653   sqlite3DbFree(db, aToOpen);
654   return;
655 }
656 /* Make sure "isView" and other macros defined above are undefined. Otherwise
657 ** they may interfere with compilation of other functions in this file
658 ** (or in another file, if this file becomes part of the amalgamation).  */
659 #ifdef isView
660  #undef isView
661 #endif
662 #ifdef pTrigger
663  #undef pTrigger
664 #endif
665 
666 /*
667 ** This routine generates VDBE code that causes a single row of a
668 ** single table to be deleted.  Both the original table entry and
669 ** all indices are removed.
670 **
671 ** Preconditions:
672 **
673 **   1.  iDataCur is an open cursor on the btree that is the canonical data
674 **       store for the table.  (This will be either the table itself,
675 **       in the case of a rowid table, or the PRIMARY KEY index in the case
676 **       of a WITHOUT ROWID table.)
677 **
678 **   2.  Read/write cursors for all indices of pTab must be open as
679 **       cursor number iIdxCur+i for the i-th index.
680 **
681 **   3.  The primary key for the row to be deleted must be stored in a
682 **       sequence of nPk memory cells starting at iPk.  If nPk==0 that means
683 **       that a search record formed from OP_MakeRecord is contained in the
684 **       single memory location iPk.
685 **
686 ** eMode:
687 **   Parameter eMode may be passed either ONEPASS_OFF (0), ONEPASS_SINGLE, or
688 **   ONEPASS_MULTI.  If eMode is not ONEPASS_OFF, then the cursor
689 **   iDataCur already points to the row to delete. If eMode is ONEPASS_OFF
690 **   then this function must seek iDataCur to the entry identified by iPk
691 **   and nPk before reading from it.
692 **
693 **   If eMode is ONEPASS_MULTI, then this call is being made as part
694 **   of a ONEPASS delete that affects multiple rows. In this case, if
695 **   iIdxNoSeek is a valid cursor number (>=0) and is not the same as
696 **   iDataCur, then its position should be preserved following the delete
697 **   operation. Or, if iIdxNoSeek is not a valid cursor number, the
698 **   position of iDataCur should be preserved instead.
699 **
700 ** iIdxNoSeek:
701 **   If iIdxNoSeek is a valid cursor number (>=0) not equal to iDataCur,
702 **   then it identifies an index cursor (from within array of cursors
703 **   starting at iIdxCur) that already points to the index entry to be deleted.
704 **   Except, this optimization is disabled if there are BEFORE triggers since
705 **   the trigger body might have moved the cursor.
706 */
707 void sqlite3GenerateRowDelete(
708   Parse *pParse,     /* Parsing context */
709   Table *pTab,       /* Table containing the row to be deleted */
710   Trigger *pTrigger, /* List of triggers to (potentially) fire */
711   int iDataCur,      /* Cursor from which column data is extracted */
712   int iIdxCur,       /* First index cursor */
713   int iPk,           /* First memory cell containing the PRIMARY KEY */
714   i16 nPk,           /* Number of PRIMARY KEY memory cells */
715   u8 count,          /* If non-zero, increment the row change counter */
716   u8 onconf,         /* Default ON CONFLICT policy for triggers */
717   u8 eMode,          /* ONEPASS_OFF, _SINGLE, or _MULTI.  See above */
718   int iIdxNoSeek     /* Cursor number of cursor that does not need seeking */
719 ){
720   Vdbe *v = pParse->pVdbe;        /* Vdbe */
721   int iOld = 0;                   /* First register in OLD.* array */
722   int iLabel;                     /* Label resolved to end of generated code */
723   u8 opSeek;                      /* Seek opcode */
724 
725   /* Vdbe is guaranteed to have been allocated by this stage. */
726   assert( v );
727   VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)",
728                          iDataCur, iIdxCur, iPk, (int)nPk));
729 
730   /* Seek cursor iCur to the row to delete. If this row no longer exists
731   ** (this can happen if a trigger program has already deleted it), do
732   ** not attempt to delete it or fire any DELETE triggers.  */
733   iLabel = sqlite3VdbeMakeLabel(pParse);
734   opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
735   if( eMode==ONEPASS_OFF ){
736     sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
737     VdbeCoverageIf(v, opSeek==OP_NotExists);
738     VdbeCoverageIf(v, opSeek==OP_NotFound);
739   }
740 
741   /* If there are any triggers to fire, allocate a range of registers to
742   ** use for the old.* references in the triggers.  */
743   if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
744     u32 mask;                     /* Mask of OLD.* columns in use */
745     int iCol;                     /* Iterator used while populating OLD.* */
746     int addrStart;                /* Start of BEFORE trigger programs */
747 
748     /* TODO: Could use temporary registers here. Also could attempt to
749     ** avoid copying the contents of the rowid register.  */
750     mask = sqlite3TriggerColmask(
751         pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
752     );
753     mask |= sqlite3FkOldmask(pParse, pTab);
754     iOld = pParse->nMem+1;
755     pParse->nMem += (1 + pTab->nCol);
756 
757     /* Populate the OLD.* pseudo-table register array. These values will be
758     ** used by any BEFORE and AFTER triggers that exist.  */
759     sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);
760     for(iCol=0; iCol<pTab->nCol; iCol++){
761       testcase( mask!=0xffffffff && iCol==31 );
762       testcase( mask!=0xffffffff && iCol==32 );
763       if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){
764         int kk = sqlite3TableColumnToStorage(pTab, iCol);
765         sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+kk+1);
766       }
767     }
768 
769     /* Invoke BEFORE DELETE trigger programs. */
770     addrStart = sqlite3VdbeCurrentAddr(v);
771     sqlite3CodeRowTrigger(pParse, pTrigger,
772         TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
773     );
774 
775     /* If any BEFORE triggers were coded, then seek the cursor to the
776     ** row to be deleted again. It may be that the BEFORE triggers moved
777     ** the cursor or already deleted the row that the cursor was
778     ** pointing to.
779     **
780     ** Also disable the iIdxNoSeek optimization since the BEFORE trigger
781     ** may have moved that cursor.
782     */
783     if( addrStart<sqlite3VdbeCurrentAddr(v) ){
784       sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
785       VdbeCoverageIf(v, opSeek==OP_NotExists);
786       VdbeCoverageIf(v, opSeek==OP_NotFound);
787       testcase( iIdxNoSeek>=0 );
788       iIdxNoSeek = -1;
789     }
790 
791     /* Do FK processing. This call checks that any FK constraints that
792     ** refer to this table (i.e. constraints attached to other tables)
793     ** are not violated by deleting this row.  */
794     sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
795   }
796 
797   /* Delete the index and table entries. Skip this step if pTab is really
798   ** a view (in which case the only effect of the DELETE statement is to
799   ** fire the INSTEAD OF triggers).
800   **
801   ** If variable 'count' is non-zero, then this OP_Delete instruction should
802   ** invoke the update-hook. The pre-update-hook, on the other hand should
803   ** be invoked unless table pTab is a system table. The difference is that
804   ** the update-hook is not invoked for rows removed by REPLACE, but the
805   ** pre-update-hook is.
806   */
807   if( !IsView(pTab) ){
808     u8 p5 = 0;
809     sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,iIdxNoSeek);
810     sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
811     if( pParse->nested==0 || 0==sqlite3_stricmp(pTab->zName, "sqlite_stat1") ){
812       sqlite3VdbeAppendP4(v, (char*)pTab, P4_TABLE);
813     }
814     if( eMode!=ONEPASS_OFF ){
815       sqlite3VdbeChangeP5(v, OPFLAG_AUXDELETE);
816     }
817     if( iIdxNoSeek>=0 && iIdxNoSeek!=iDataCur ){
818       sqlite3VdbeAddOp1(v, OP_Delete, iIdxNoSeek);
819     }
820     if( eMode==ONEPASS_MULTI ) p5 |= OPFLAG_SAVEPOSITION;
821     sqlite3VdbeChangeP5(v, p5);
822   }
823 
824   /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
825   ** handle rows (possibly in other tables) that refer via a foreign key
826   ** to the row just deleted. */
827   sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
828 
829   /* Invoke AFTER DELETE trigger programs. */
830   sqlite3CodeRowTrigger(pParse, pTrigger,
831       TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
832   );
833 
834   /* Jump here if the row had already been deleted before any BEFORE
835   ** trigger programs were invoked. Or if a trigger program throws a
836   ** RAISE(IGNORE) exception.  */
837   sqlite3VdbeResolveLabel(v, iLabel);
838   VdbeModuleComment((v, "END: GenRowDel()"));
839 }
840 
841 /*
842 ** This routine generates VDBE code that causes the deletion of all
843 ** index entries associated with a single row of a single table, pTab
844 **
845 ** Preconditions:
846 **
847 **   1.  A read/write cursor "iDataCur" must be open on the canonical storage
848 **       btree for the table pTab.  (This will be either the table itself
849 **       for rowid tables or to the primary key index for WITHOUT ROWID
850 **       tables.)
851 **
852 **   2.  Read/write cursors for all indices of pTab must be open as
853 **       cursor number iIdxCur+i for the i-th index.  (The pTab->pIndex
854 **       index is the 0-th index.)
855 **
856 **   3.  The "iDataCur" cursor must be already be positioned on the row
857 **       that is to be deleted.
858 */
859 void sqlite3GenerateRowIndexDelete(
860   Parse *pParse,     /* Parsing and code generating context */
861   Table *pTab,       /* Table containing the row to be deleted */
862   int iDataCur,      /* Cursor of table holding data. */
863   int iIdxCur,       /* First index cursor */
864   int *aRegIdx,      /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
865   int iIdxNoSeek     /* Do not delete from this cursor */
866 ){
867   int i;             /* Index loop counter */
868   int r1 = -1;       /* Register holding an index key */
869   int iPartIdxLabel; /* Jump destination for skipping partial index entries */
870   Index *pIdx;       /* Current index */
871   Index *pPrior = 0; /* Prior index */
872   Vdbe *v;           /* The prepared statement under construction */
873   Index *pPk;        /* PRIMARY KEY index, or NULL for rowid tables */
874 
875   v = pParse->pVdbe;
876   pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
877   for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
878     assert( iIdxCur+i!=iDataCur || pPk==pIdx );
879     if( aRegIdx!=0 && aRegIdx[i]==0 ) continue;
880     if( pIdx==pPk ) continue;
881     if( iIdxCur+i==iIdxNoSeek ) continue;
882     VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
883     r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,
884         &iPartIdxLabel, pPrior, r1);
885     sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
886         pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
887     sqlite3VdbeChangeP5(v, 1);  /* Cause IdxDelete to error if no entry found */
888     sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
889     pPrior = pIdx;
890   }
891 }
892 
893 /*
894 ** Generate code that will assemble an index key and stores it in register
895 ** regOut.  The key with be for index pIdx which is an index on pTab.
896 ** iCur is the index of a cursor open on the pTab table and pointing to
897 ** the entry that needs indexing.  If pTab is a WITHOUT ROWID table, then
898 ** iCur must be the cursor of the PRIMARY KEY index.
899 **
900 ** Return a register number which is the first in a block of
901 ** registers that holds the elements of the index key.  The
902 ** block of registers has already been deallocated by the time
903 ** this routine returns.
904 **
905 ** If *piPartIdxLabel is not NULL, fill it in with a label and jump
906 ** to that label if pIdx is a partial index that should be skipped.
907 ** The label should be resolved using sqlite3ResolvePartIdxLabel().
908 ** A partial index should be skipped if its WHERE clause evaluates
909 ** to false or null.  If pIdx is not a partial index, *piPartIdxLabel
910 ** will be set to zero which is an empty label that is ignored by
911 ** sqlite3ResolvePartIdxLabel().
912 **
913 ** The pPrior and regPrior parameters are used to implement a cache to
914 ** avoid unnecessary register loads.  If pPrior is not NULL, then it is
915 ** a pointer to a different index for which an index key has just been
916 ** computed into register regPrior.  If the current pIdx index is generating
917 ** its key into the same sequence of registers and if pPrior and pIdx share
918 ** a column in common, then the register corresponding to that column already
919 ** holds the correct value and the loading of that register is skipped.
920 ** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK
921 ** on a table with multiple indices, and especially with the ROWID or
922 ** PRIMARY KEY columns of the index.
923 */
924 int sqlite3GenerateIndexKey(
925   Parse *pParse,       /* Parsing context */
926   Index *pIdx,         /* The index for which to generate a key */
927   int iDataCur,        /* Cursor number from which to take column data */
928   int regOut,          /* Put the new key into this register if not 0 */
929   int prefixOnly,      /* Compute only a unique prefix of the key */
930   int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */
931   Index *pPrior,       /* Previously generated index key */
932   int regPrior         /* Register holding previous generated key */
933 ){
934   Vdbe *v = pParse->pVdbe;
935   int j;
936   int regBase;
937   int nCol;
938 
939   if( piPartIdxLabel ){
940     if( pIdx->pPartIdxWhere ){
941       *piPartIdxLabel = sqlite3VdbeMakeLabel(pParse);
942       pParse->iSelfTab = iDataCur + 1;
943       sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
944                             SQLITE_JUMPIFNULL);
945       pParse->iSelfTab = 0;
946       pPrior = 0; /* Ticket a9efb42811fa41ee 2019-11-02;
947                   ** pPartIdxWhere may have corrupted regPrior registers */
948     }else{
949       *piPartIdxLabel = 0;
950     }
951   }
952   nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
953   regBase = sqlite3GetTempRange(pParse, nCol);
954   if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
955   for(j=0; j<nCol; j++){
956     if( pPrior
957      && pPrior->aiColumn[j]==pIdx->aiColumn[j]
958      && pPrior->aiColumn[j]!=XN_EXPR
959     ){
960       /* This column was already computed by the previous index */
961       continue;
962     }
963     sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iDataCur, j, regBase+j);
964     if( pIdx->aiColumn[j]>=0 ){
965       /* If the column affinity is REAL but the number is an integer, then it
966       ** might be stored in the table as an integer (using a compact
967       ** representation) then converted to REAL by an OP_RealAffinity opcode.
968       ** But we are getting ready to store this value back into an index, where
969       ** it should be converted by to INTEGER again.  So omit the
970       ** OP_RealAffinity opcode if it is present */
971       sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
972     }
973   }
974   if( regOut ){
975     sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
976   }
977   sqlite3ReleaseTempRange(pParse, regBase, nCol);
978   return regBase;
979 }
980 
981 /*
982 ** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
983 ** because it was a partial index, then this routine should be called to
984 ** resolve that label.
985 */
986 void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){
987   if( iLabel ){
988     sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel);
989   }
990 }
991