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