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