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