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