4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
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
;
34 assert( pItem
&& pSrc
->nSrc
>=1 );
35 pTab
= sqlite3LocateTableItem(pParse
, 0, pItem
);
36 if( pItem
->pTab
) sqlite3DeleteTable(pParse
->db
, pItem
->pTab
);
41 if( pItem
->fg
.isIndexedBy
&& sqlite3IndexedByLookup(pParse
, pItem
) ){
48 /* Generate byte-code that will report the number of rows modified
49 ** by a DELETE, INSERT, or UPDATE statement.
51 void sqlite3CodeChangeCount(Vdbe
*v
, int regCounter
, const char *zColName
){
52 sqlite3VdbeAddOp0(v
, OP_FkCheck
);
53 sqlite3VdbeAddOp2(v
, OP_ResultRow
, regCounter
, 1);
54 sqlite3VdbeSetNumCols(v
, 1);
55 sqlite3VdbeSetColName(v
, 0, COLNAME_NAME
, zColName
, SQLITE_STATIC
);
58 /* Return true if table pTab is read-only.
60 ** A table is read-only if any of the following are true:
62 ** 1) It is a virtual table and no implementation of the xUpdate method
65 ** 2) A trigger is currently being coded and the table is a virtual table
66 ** that is SQLITE_VTAB_DIRECTONLY or if PRAGMA trusted_schema=OFF and
67 ** the table is not SQLITE_VTAB_INNOCUOUS.
69 ** 3) It is a system table (i.e. sqlite_schema), this call is not
70 ** part of a nested parse and writable_schema pragma has not
73 ** 4) The table is a shadow table, the database connection is in
74 ** defensive mode, and the current sqlite3_prepare()
75 ** is for a top-level SQL statement.
77 static int vtabIsReadOnly(Parse
*pParse
, Table
*pTab
){
78 if( sqlite3GetVTable(pParse
->db
, pTab
)->pMod
->pModule
->xUpdate
==0 ){
83 ** * Do not allow DELETE, INSERT, or UPDATE of SQLITE_VTAB_DIRECTONLY
85 ** * Only allow DELETE, INSERT, or UPDATE of non-SQLITE_VTAB_INNOCUOUS
86 ** virtual tables if PRAGMA trusted_schema=ON.
88 if( pParse
->pToplevel
!=0
89 && pTab
->u
.vtab
.p
->eVtabRisk
>
90 ((pParse
->db
->flags
& SQLITE_TrustedSchema
)!=0)
92 sqlite3ErrorMsg(pParse
, "unsafe use of virtual table \"%s\"",
97 static int tabIsReadOnly(Parse
*pParse
, Table
*pTab
){
99 if( IsVirtual(pTab
) ){
100 return vtabIsReadOnly(pParse
, pTab
);
102 if( (pTab
->tabFlags
& (TF_Readonly
|TF_Shadow
))==0 ) return 0;
104 if( (pTab
->tabFlags
& TF_Readonly
)!=0 ){
105 return sqlite3WritableSchema(db
)==0 && pParse
->nested
==0;
107 assert( pTab
->tabFlags
& TF_Shadow
);
108 return sqlite3ReadOnlyShadowTables(db
);
112 ** Check to make sure the given table is writable.
114 ** If pTab is not writable -> generate an error message and return 1.
115 ** If pTab is writable but other errors have occurred -> return 1.
116 ** If pTab is writable and no prior errors -> return 0;
118 int sqlite3IsReadOnly(Parse
*pParse
, Table
*pTab
, Trigger
*pTrigger
){
119 if( tabIsReadOnly(pParse
, pTab
) ){
120 sqlite3ErrorMsg(pParse
, "table %s may not be modified", pTab
->zName
);
123 #ifndef SQLITE_OMIT_VIEW
125 && (pTrigger
==0 || (pTrigger
->bReturning
&& pTrigger
->pNext
==0))
127 sqlite3ErrorMsg(pParse
,"cannot modify %s because it is a view",pTab
->zName
);
135 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
137 ** Evaluate a view and store its result in an ephemeral table. The
138 ** pWhere argument is an optional WHERE clause that restricts the
139 ** set of rows in the view that are to be added to the ephemeral table.
141 void sqlite3MaterializeView(
142 Parse
*pParse
, /* Parsing context */
143 Table
*pView
, /* View definition */
144 Expr
*pWhere
, /* Optional WHERE clause to be added */
145 ExprList
*pOrderBy
, /* Optional ORDER BY clause */
146 Expr
*pLimit
, /* Optional LIMIT clause */
147 int iCur
/* Cursor number for ephemeral table */
152 sqlite3
*db
= pParse
->db
;
153 int iDb
= sqlite3SchemaToIndex(db
, pView
->pSchema
);
154 pWhere
= sqlite3ExprDup(db
, pWhere
, 0);
155 pFrom
= sqlite3SrcListAppend(pParse
, 0, 0, 0);
157 assert( pFrom
->nSrc
==1 );
158 pFrom
->a
[0].zName
= sqlite3DbStrDup(db
, pView
->zName
);
159 pFrom
->a
[0].zDatabase
= sqlite3DbStrDup(db
, db
->aDb
[iDb
].zDbSName
);
160 assert( pFrom
->a
[0].fg
.isUsing
==0 );
161 assert( pFrom
->a
[0].u3
.pOn
==0 );
163 pSel
= sqlite3SelectNew(pParse
, 0, pFrom
, pWhere
, 0, 0, pOrderBy
,
164 SF_IncludeHidden
, pLimit
);
165 sqlite3SelectDestInit(&dest
, SRT_EphemTab
, iCur
);
166 sqlite3Select(pParse
, pSel
, &dest
);
167 sqlite3SelectDelete(db
, pSel
);
169 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
171 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
173 ** Generate an expression tree to implement the WHERE, ORDER BY,
174 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
176 ** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
177 ** \__________________________/
178 ** pLimitWhere (pInClause)
180 Expr
*sqlite3LimitWhere(
181 Parse
*pParse
, /* The parser context */
182 SrcList
*pSrc
, /* the FROM clause -- which tables to scan */
183 Expr
*pWhere
, /* The WHERE clause. May be null */
184 ExprList
*pOrderBy
, /* The ORDER BY clause. May be null */
185 Expr
*pLimit
, /* The LIMIT clause. May be null */
186 char *zStmtType
/* Either DELETE or UPDATE. For err msgs. */
188 sqlite3
*db
= pParse
->db
;
189 Expr
*pLhs
= NULL
; /* LHS of IN(SELECT...) operator */
190 Expr
*pInClause
= NULL
; /* WHERE rowid IN ( select ) */
191 ExprList
*pEList
= NULL
; /* Expression list containing only pSelectRowid*/
192 SrcList
*pSelectSrc
= NULL
; /* SELECT rowid FROM x ... (dup of pSrc) */
193 Select
*pSelect
= NULL
; /* Complete SELECT tree */
196 /* Check that there isn't an ORDER BY without a LIMIT clause.
198 if( pOrderBy
&& pLimit
==0 ) {
199 sqlite3ErrorMsg(pParse
, "ORDER BY without LIMIT on %s", zStmtType
);
200 sqlite3ExprDelete(pParse
->db
, pWhere
);
201 sqlite3ExprListDelete(pParse
->db
, pOrderBy
);
205 /* We only need to generate a select expression if there
206 ** is a limit/offset term to enforce.
212 /* Generate a select expression tree to enforce the limit/offset
213 ** term for the DELETE or UPDATE statement. For example:
214 ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
216 ** DELETE FROM table_a WHERE rowid IN (
217 ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
221 pTab
= pSrc
->a
[0].pTab
;
222 if( HasRowid(pTab
) ){
223 pLhs
= sqlite3PExpr(pParse
, TK_ROW
, 0, 0);
224 pEList
= sqlite3ExprListAppend(
225 pParse
, 0, sqlite3PExpr(pParse
, TK_ROW
, 0, 0)
228 Index
*pPk
= sqlite3PrimaryKeyIndex(pTab
);
230 assert( pPk
->nKeyCol
>=1 );
231 if( pPk
->nKeyCol
==1 ){
233 assert( pPk
->aiColumn
[0]>=0 && pPk
->aiColumn
[0]<pTab
->nCol
);
234 zName
= pTab
->aCol
[pPk
->aiColumn
[0]].zCnName
;
235 pLhs
= sqlite3Expr(db
, TK_ID
, zName
);
236 pEList
= sqlite3ExprListAppend(pParse
, 0, sqlite3Expr(db
, TK_ID
, zName
));
239 for(i
=0; i
<pPk
->nKeyCol
; i
++){
241 assert( pPk
->aiColumn
[i
]>=0 && pPk
->aiColumn
[i
]<pTab
->nCol
);
242 p
= sqlite3Expr(db
, TK_ID
, pTab
->aCol
[pPk
->aiColumn
[i
]].zCnName
);
243 pEList
= sqlite3ExprListAppend(pParse
, pEList
, p
);
245 pLhs
= sqlite3PExpr(pParse
, TK_VECTOR
, 0, 0);
247 pLhs
->x
.pList
= sqlite3ExprListDup(db
, pEList
, 0);
252 /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
253 ** and the SELECT subtree. */
255 pSelectSrc
= sqlite3SrcListDup(db
, pSrc
, 0);
256 pSrc
->a
[0].pTab
= pTab
;
257 if( pSrc
->a
[0].fg
.isIndexedBy
){
258 assert( pSrc
->a
[0].fg
.isCte
==0 );
259 pSrc
->a
[0].u2
.pIBIndex
= 0;
260 pSrc
->a
[0].fg
.isIndexedBy
= 0;
261 sqlite3DbFree(db
, pSrc
->a
[0].u1
.zIndexedBy
);
262 }else if( pSrc
->a
[0].fg
.isCte
){
263 pSrc
->a
[0].u2
.pCteUse
->nUse
++;
266 /* generate the SELECT expression tree. */
267 pSelect
= sqlite3SelectNew(pParse
, pEList
, pSelectSrc
, pWhere
, 0 ,0,
271 /* now generate the new WHERE rowid IN clause for the DELETE/UPDATE */
272 pInClause
= sqlite3PExpr(pParse
, TK_IN
, pLhs
, 0);
273 sqlite3PExprAddSelect(pParse
, pInClause
, pSelect
);
276 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */
277 /* && !defined(SQLITE_OMIT_SUBQUERY) */
280 ** Generate code for a DELETE FROM statement.
282 ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
283 ** \________/ \________________/
286 void sqlite3DeleteFrom(
287 Parse
*pParse
, /* The parser context */
288 SrcList
*pTabList
, /* The table from which we should delete things */
289 Expr
*pWhere
, /* The WHERE clause. May be null */
290 ExprList
*pOrderBy
, /* ORDER BY clause. May be null */
291 Expr
*pLimit
/* LIMIT clause. May be null */
293 Vdbe
*v
; /* The virtual database engine */
294 Table
*pTab
; /* The table from which records will be deleted */
295 int i
; /* Loop counter */
296 WhereInfo
*pWInfo
; /* Information about the WHERE clause */
297 Index
*pIdx
; /* For looping over indices of the table */
298 int iTabCur
; /* Cursor number for the table */
299 int iDataCur
= 0; /* VDBE cursor for the canonical data source */
300 int iIdxCur
= 0; /* Cursor number of the first index */
301 int nIdx
; /* Number of indices */
302 sqlite3
*db
; /* Main database structure */
303 AuthContext sContext
; /* Authorization context */
304 NameContext sNC
; /* Name context to resolve expressions in */
305 int iDb
; /* Database number */
306 int memCnt
= 0; /* Memory cell used for change counting */
307 int rcauth
; /* Value returned by authorization callback */
308 int eOnePass
; /* ONEPASS_OFF or _SINGLE or _MULTI */
309 int aiCurOnePass
[2]; /* The write cursors opened by WHERE_ONEPASS */
310 u8
*aToOpen
= 0; /* Open cursor iTabCur+j if aToOpen[j] is true */
311 Index
*pPk
; /* The PRIMARY KEY index on the table */
312 int iPk
= 0; /* First of nPk registers holding PRIMARY KEY value */
313 i16 nPk
= 1; /* Number of columns in the PRIMARY KEY */
314 int iKey
; /* Memory cell holding key of row to be deleted */
315 i16 nKey
; /* Number of memory cells in the row key */
316 int iEphCur
= 0; /* Ephemeral table holding all primary key values */
317 int iRowSet
= 0; /* Register for rowset of rows to delete */
318 int addrBypass
= 0; /* Address of jump over the delete logic */
319 int addrLoop
= 0; /* Top of the delete loop */
320 int addrEphOpen
= 0; /* Instruction to open the Ephemeral table */
321 int bComplex
; /* True if there are triggers or FKs or
322 ** subqueries in the WHERE clause */
324 #ifndef SQLITE_OMIT_TRIGGER
325 int isView
; /* True if attempting to delete from a view */
326 Trigger
*pTrigger
; /* List of table triggers, if required */
329 memset(&sContext
, 0, sizeof(sContext
));
331 assert( db
->pParse
==pParse
);
333 goto delete_from_cleanup
;
335 assert( db
->mallocFailed
==0 );
336 assert( pTabList
->nSrc
==1 );
338 /* Locate the table which we want to delete. This table has to be
339 ** put in an SrcList structure because some of the subroutines we
340 ** will be calling are designed to work with multiple tables and expect
341 ** an SrcList* parameter instead of just a Table* parameter.
343 pTab
= sqlite3SrcListLookup(pParse
, pTabList
);
344 if( pTab
==0 ) goto delete_from_cleanup
;
346 /* Figure out if we have any triggers and if the table being
347 ** deleted from is a view
349 #ifndef SQLITE_OMIT_TRIGGER
350 pTrigger
= sqlite3TriggersExist(pParse
, pTab
, TK_DELETE
, 0, 0);
351 isView
= IsView(pTab
);
356 bComplex
= pTrigger
|| sqlite3FkRequired(pParse
, pTab
, 0, 0);
357 #ifdef SQLITE_OMIT_VIEW
362 #if TREETRACE_ENABLED
363 if( sqlite3TreeTrace
& 0x10000 ){
364 sqlite3TreeViewLine(0, "In sqlite3Delete() at %s:%d", __FILE__
, __LINE__
);
365 sqlite3TreeViewDelete(pParse
->pWith
, pTabList
, pWhere
,
366 pOrderBy
, pLimit
, pTrigger
);
370 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
372 pWhere
= sqlite3LimitWhere(
373 pParse
, pTabList
, pWhere
, pOrderBy
, pLimit
, "DELETE"
380 /* If pTab is really a view, make sure it has been initialized.
382 if( sqlite3ViewGetColumnNames(pParse
, pTab
) ){
383 goto delete_from_cleanup
;
386 if( sqlite3IsReadOnly(pParse
, pTab
, pTrigger
) ){
387 goto delete_from_cleanup
;
389 iDb
= sqlite3SchemaToIndex(db
, pTab
->pSchema
);
390 assert( iDb
<db
->nDb
);
391 rcauth
= sqlite3AuthCheck(pParse
, SQLITE_DELETE
, pTab
->zName
, 0,
392 db
->aDb
[iDb
].zDbSName
);
393 assert( rcauth
==SQLITE_OK
|| rcauth
==SQLITE_DENY
|| rcauth
==SQLITE_IGNORE
);
394 if( rcauth
==SQLITE_DENY
){
395 goto delete_from_cleanup
;
397 assert(!isView
|| pTrigger
);
399 /* Assign cursor numbers to the table and all its indices.
401 assert( pTabList
->nSrc
==1 );
402 iTabCur
= pTabList
->a
[0].iCursor
= pParse
->nTab
++;
403 for(nIdx
=0, pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
, nIdx
++){
407 /* Start the view context
410 sqlite3AuthContextPush(pParse
, &sContext
, pTab
->zName
);
413 /* Begin generating code.
415 v
= sqlite3GetVdbe(pParse
);
417 goto delete_from_cleanup
;
419 if( pParse
->nested
==0 ) sqlite3VdbeCountChanges(v
);
420 sqlite3BeginWriteOperation(pParse
, bComplex
, iDb
);
422 /* If we are trying to delete from a view, realize that view into
423 ** an ephemeral table.
425 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
427 sqlite3MaterializeView(pParse
, pTab
,
428 pWhere
, pOrderBy
, pLimit
, iTabCur
430 iDataCur
= iIdxCur
= iTabCur
;
436 /* Resolve the column names in the WHERE clause.
438 memset(&sNC
, 0, sizeof(sNC
));
440 sNC
.pSrcList
= pTabList
;
441 if( sqlite3ResolveExprNames(&sNC
, pWhere
) ){
442 goto delete_from_cleanup
;
445 /* Initialize the counter of the number of rows deleted, if
446 ** we are counting rows.
448 if( (db
->flags
& SQLITE_CountRows
)!=0
450 && !pParse
->pTriggerTab
451 && !pParse
->bReturning
453 memCnt
= ++pParse
->nMem
;
454 sqlite3VdbeAddOp2(v
, OP_Integer
, 0, memCnt
);
457 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
458 /* Special case: A DELETE without a WHERE clause deletes everything.
459 ** It is easier just to erase the whole table. Prior to version 3.6.5,
460 ** this optimization caused the row change count (the value returned by
461 ** API function sqlite3_count_changes) to be set incorrectly.
463 ** The "rcauth==SQLITE_OK" terms is the
464 ** IMPLEMENTATION-OF: R-17228-37124 If the action code is SQLITE_DELETE and
465 ** the callback returns SQLITE_IGNORE then the DELETE operation proceeds but
466 ** the truncate optimization is disabled and all rows are deleted
469 if( rcauth
==SQLITE_OK
473 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
474 && db
->xPreUpdateCallback
==0
478 sqlite3TableLock(pParse
, iDb
, pTab
->tnum
, 1, pTab
->zName
);
479 if( HasRowid(pTab
) ){
480 sqlite3VdbeAddOp4(v
, OP_Clear
, pTab
->tnum
, iDb
, memCnt
? memCnt
: -1,
481 pTab
->zName
, P4_STATIC
);
483 for(pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
){
484 assert( pIdx
->pSchema
==pTab
->pSchema
);
485 if( IsPrimaryKeyIndex(pIdx
) && !HasRowid(pTab
) ){
486 sqlite3VdbeAddOp3(v
, OP_Clear
, pIdx
->tnum
, iDb
, memCnt
? memCnt
: -1);
488 sqlite3VdbeAddOp2(v
, OP_Clear
, pIdx
->tnum
, iDb
);
492 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
494 u16 wcf
= WHERE_ONEPASS_DESIRED
|WHERE_DUPLICATES_OK
;
495 if( sNC
.ncFlags
& NC_Subquery
) bComplex
= 1;
496 wcf
|= (bComplex
? 0 : WHERE_ONEPASS_MULTIROW
);
497 if( HasRowid(pTab
) ){
498 /* For a rowid table, initialize the RowSet to an empty set */
501 iRowSet
= ++pParse
->nMem
;
502 sqlite3VdbeAddOp2(v
, OP_Null
, 0, iRowSet
);
504 /* For a WITHOUT ROWID table, create an ephemeral table used to
505 ** hold all primary keys for rows to be deleted. */
506 pPk
= sqlite3PrimaryKeyIndex(pTab
);
509 iPk
= pParse
->nMem
+1;
511 iEphCur
= pParse
->nTab
++;
512 addrEphOpen
= sqlite3VdbeAddOp2(v
, OP_OpenEphemeral
, iEphCur
, nPk
);
513 sqlite3VdbeSetP4KeyInfo(pParse
, pPk
);
516 /* Construct a query to find the rowid or primary key for every row
517 ** to be deleted, based on the WHERE clause. Set variable eOnePass
518 ** to indicate the strategy used to implement this delete:
520 ** ONEPASS_OFF: Two-pass approach - use a FIFO for rowids/PK values.
521 ** ONEPASS_SINGLE: One-pass approach - at most one row deleted.
522 ** ONEPASS_MULTI: One-pass approach - any number of rows may be deleted.
524 pWInfo
= sqlite3WhereBegin(pParse
, pTabList
, pWhere
, 0, 0,0,wcf
,iTabCur
+1);
525 if( pWInfo
==0 ) goto delete_from_cleanup
;
526 eOnePass
= sqlite3WhereOkOnePass(pWInfo
, aiCurOnePass
);
527 assert( IsVirtual(pTab
)==0 || eOnePass
!=ONEPASS_MULTI
);
528 assert( IsVirtual(pTab
) || bComplex
|| eOnePass
!=ONEPASS_OFF
529 || OptimizationDisabled(db
, SQLITE_OnePass
) );
530 if( eOnePass
!=ONEPASS_SINGLE
) sqlite3MultiWrite(pParse
);
531 if( sqlite3WhereUsesDeferredSeek(pWInfo
) ){
532 sqlite3VdbeAddOp1(v
, OP_FinishSeek
, iTabCur
);
535 /* Keep track of the number of rows to be deleted */
537 sqlite3VdbeAddOp2(v
, OP_AddImm
, memCnt
, 1);
540 /* Extract the rowid or primary key for the current row */
542 for(i
=0; i
<nPk
; i
++){
543 assert( pPk
->aiColumn
[i
]>=0 );
544 sqlite3ExprCodeGetColumnOfTable(v
, pTab
, iTabCur
,
545 pPk
->aiColumn
[i
], iPk
+i
);
549 iKey
= ++pParse
->nMem
;
550 sqlite3ExprCodeGetColumnOfTable(v
, pTab
, iTabCur
, -1, iKey
);
553 if( eOnePass
!=ONEPASS_OFF
){
554 /* For ONEPASS, no need to store the rowid/primary-key. There is only
555 ** one, so just keep it in its register(s) and fall through to the
557 nKey
= nPk
; /* OP_Found will use an unpacked key */
558 aToOpen
= sqlite3DbMallocRawNN(db
, nIdx
+2);
560 sqlite3WhereEnd(pWInfo
);
561 goto delete_from_cleanup
;
563 memset(aToOpen
, 1, nIdx
+1);
565 if( aiCurOnePass
[0]>=0 ) aToOpen
[aiCurOnePass
[0]-iTabCur
] = 0;
566 if( aiCurOnePass
[1]>=0 ) aToOpen
[aiCurOnePass
[1]-iTabCur
] = 0;
567 if( addrEphOpen
) sqlite3VdbeChangeToNoop(v
, addrEphOpen
);
568 addrBypass
= sqlite3VdbeMakeLabel(pParse
);
571 /* Add the PK key for this row to the temporary table */
572 iKey
= ++pParse
->nMem
;
573 nKey
= 0; /* Zero tells OP_Found to use a composite key */
574 sqlite3VdbeAddOp4(v
, OP_MakeRecord
, iPk
, nPk
, iKey
,
575 sqlite3IndexAffinityStr(pParse
->db
, pPk
), nPk
);
576 sqlite3VdbeAddOp4Int(v
, OP_IdxInsert
, iEphCur
, iKey
, iPk
, nPk
);
578 /* Add the rowid of the row to be deleted to the RowSet */
579 nKey
= 1; /* OP_DeferredSeek always uses a single rowid */
580 sqlite3VdbeAddOp2(v
, OP_RowSetAdd
, iRowSet
, iKey
);
582 sqlite3WhereEnd(pWInfo
);
585 /* Unless this is a view, open cursors for the table we are
586 ** deleting from and all its indices. If this is a view, then the
587 ** only effect this statement has is to fire the INSTEAD OF
592 if( eOnePass
==ONEPASS_MULTI
){
593 iAddrOnce
= sqlite3VdbeAddOp0(v
, OP_Once
); VdbeCoverage(v
);
595 testcase( IsVirtual(pTab
) );
596 sqlite3OpenTableAndIndices(pParse
, pTab
, OP_OpenWrite
, OPFLAG_FORDELETE
,
597 iTabCur
, aToOpen
, &iDataCur
, &iIdxCur
);
598 assert( pPk
|| IsVirtual(pTab
) || iDataCur
==iTabCur
);
599 assert( pPk
|| IsVirtual(pTab
) || iIdxCur
==iDataCur
+1 );
600 if( eOnePass
==ONEPASS_MULTI
){
601 sqlite3VdbeJumpHereOrPopInst(v
, iAddrOnce
);
605 /* Set up a loop over the rowids/primary-keys that were found in the
606 ** where-clause loop above.
608 if( eOnePass
!=ONEPASS_OFF
){
609 assert( nKey
==nPk
); /* OP_Found will use an unpacked key */
610 if( !IsVirtual(pTab
) && aToOpen
[iDataCur
-iTabCur
] ){
611 assert( pPk
!=0 || IsView(pTab
) );
612 sqlite3VdbeAddOp4Int(v
, OP_NotFound
, iDataCur
, addrBypass
, iKey
, nKey
);
616 addrLoop
= sqlite3VdbeAddOp1(v
, OP_Rewind
, iEphCur
); VdbeCoverage(v
);
617 if( IsVirtual(pTab
) ){
618 sqlite3VdbeAddOp3(v
, OP_Column
, iEphCur
, 0, iKey
);
620 sqlite3VdbeAddOp2(v
, OP_RowData
, iEphCur
, iKey
);
622 assert( nKey
==0 ); /* OP_Found will use a composite key */
624 addrLoop
= sqlite3VdbeAddOp3(v
, OP_RowSetRead
, iRowSet
, 0, iKey
);
630 #ifndef SQLITE_OMIT_VIRTUALTABLE
631 if( IsVirtual(pTab
) ){
632 const char *pVTab
= (const char *)sqlite3GetVTable(db
, pTab
);
633 sqlite3VtabMakeWritable(pParse
, pTab
);
634 assert( eOnePass
==ONEPASS_OFF
|| eOnePass
==ONEPASS_SINGLE
);
635 sqlite3MayAbort(pParse
);
636 if( eOnePass
==ONEPASS_SINGLE
){
637 sqlite3VdbeAddOp1(v
, OP_Close
, iTabCur
);
638 if( sqlite3IsToplevel(pParse
) ){
639 pParse
->isMultiWrite
= 0;
642 sqlite3VdbeAddOp4(v
, OP_VUpdate
, 0, 1, iKey
, pVTab
, P4_VTAB
);
643 sqlite3VdbeChangeP5(v
, OE_Abort
);
647 int count
= (pParse
->nested
==0); /* True to count changes */
648 sqlite3GenerateRowDelete(pParse
, pTab
, pTrigger
, iDataCur
, iIdxCur
,
649 iKey
, nKey
, count
, OE_Default
, eOnePass
, aiCurOnePass
[1]);
652 /* End of the loop over all rowids/primary-keys. */
653 if( eOnePass
!=ONEPASS_OFF
){
654 sqlite3VdbeResolveLabel(v
, addrBypass
);
655 sqlite3WhereEnd(pWInfo
);
657 sqlite3VdbeAddOp2(v
, OP_Next
, iEphCur
, addrLoop
+1); VdbeCoverage(v
);
658 sqlite3VdbeJumpHere(v
, addrLoop
);
660 sqlite3VdbeGoto(v
, addrLoop
);
661 sqlite3VdbeJumpHere(v
, addrLoop
);
663 } /* End non-truncate path */
665 /* Update the sqlite_sequence table by storing the content of the
666 ** maximum rowid counter values recorded while inserting into
667 ** autoincrement tables.
669 if( pParse
->nested
==0 && pParse
->pTriggerTab
==0 ){
670 sqlite3AutoincrementEnd(pParse
);
673 /* Return the number of rows that were deleted. If this routine is
674 ** generating code because of a call to sqlite3NestedParse(), do not
675 ** invoke the callback function.
678 sqlite3CodeChangeCount(v
, memCnt
, "rows deleted");
682 sqlite3AuthContextPop(&sContext
);
683 sqlite3SrcListDelete(db
, pTabList
);
684 sqlite3ExprDelete(db
, pWhere
);
685 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
686 sqlite3ExprListDelete(db
, pOrderBy
);
687 sqlite3ExprDelete(db
, pLimit
);
689 if( aToOpen
) sqlite3DbNNFreeNN(db
, aToOpen
);
692 /* Make sure "isView" and other macros defined above are undefined. Otherwise
693 ** they may interfere with compilation of other functions in this file
694 ** (or in another file, if this file becomes part of the amalgamation). */
703 ** This routine generates VDBE code that causes a single row of a
704 ** single table to be deleted. Both the original table entry and
705 ** all indices are removed.
709 ** 1. iDataCur is an open cursor on the btree that is the canonical data
710 ** store for the table. (This will be either the table itself,
711 ** in the case of a rowid table, or the PRIMARY KEY index in the case
712 ** of a WITHOUT ROWID table.)
714 ** 2. Read/write cursors for all indices of pTab must be open as
715 ** cursor number iIdxCur+i for the i-th index.
717 ** 3. The primary key for the row to be deleted must be stored in a
718 ** sequence of nPk memory cells starting at iPk. If nPk==0 that means
719 ** that a search record formed from OP_MakeRecord is contained in the
720 ** single memory location iPk.
723 ** Parameter eMode may be passed either ONEPASS_OFF (0), ONEPASS_SINGLE, or
724 ** ONEPASS_MULTI. If eMode is not ONEPASS_OFF, then the cursor
725 ** iDataCur already points to the row to delete. If eMode is ONEPASS_OFF
726 ** then this function must seek iDataCur to the entry identified by iPk
727 ** and nPk before reading from it.
729 ** If eMode is ONEPASS_MULTI, then this call is being made as part
730 ** of a ONEPASS delete that affects multiple rows. In this case, if
731 ** iIdxNoSeek is a valid cursor number (>=0) and is not the same as
732 ** iDataCur, then its position should be preserved following the delete
733 ** operation. Or, if iIdxNoSeek is not a valid cursor number, the
734 ** position of iDataCur should be preserved instead.
737 ** If iIdxNoSeek is a valid cursor number (>=0) not equal to iDataCur,
738 ** then it identifies an index cursor (from within array of cursors
739 ** starting at iIdxCur) that already points to the index entry to be deleted.
740 ** Except, this optimization is disabled if there are BEFORE triggers since
741 ** the trigger body might have moved the cursor.
743 void sqlite3GenerateRowDelete(
744 Parse
*pParse
, /* Parsing context */
745 Table
*pTab
, /* Table containing the row to be deleted */
746 Trigger
*pTrigger
, /* List of triggers to (potentially) fire */
747 int iDataCur
, /* Cursor from which column data is extracted */
748 int iIdxCur
, /* First index cursor */
749 int iPk
, /* First memory cell containing the PRIMARY KEY */
750 i16 nPk
, /* Number of PRIMARY KEY memory cells */
751 u8 count
, /* If non-zero, increment the row change counter */
752 u8 onconf
, /* Default ON CONFLICT policy for triggers */
753 u8 eMode
, /* ONEPASS_OFF, _SINGLE, or _MULTI. See above */
754 int iIdxNoSeek
/* Cursor number of cursor that does not need seeking */
756 Vdbe
*v
= pParse
->pVdbe
; /* Vdbe */
757 int iOld
= 0; /* First register in OLD.* array */
758 int iLabel
; /* Label resolved to end of generated code */
759 u8 opSeek
; /* Seek opcode */
761 /* Vdbe is guaranteed to have been allocated by this stage. */
763 VdbeModuleComment((v
, "BEGIN: GenRowDel(%d,%d,%d,%d)",
764 iDataCur
, iIdxCur
, iPk
, (int)nPk
));
766 /* Seek cursor iCur to the row to delete. If this row no longer exists
767 ** (this can happen if a trigger program has already deleted it), do
768 ** not attempt to delete it or fire any DELETE triggers. */
769 iLabel
= sqlite3VdbeMakeLabel(pParse
);
770 opSeek
= HasRowid(pTab
) ? OP_NotExists
: OP_NotFound
;
771 if( eMode
==ONEPASS_OFF
){
772 sqlite3VdbeAddOp4Int(v
, opSeek
, iDataCur
, iLabel
, iPk
, nPk
);
773 VdbeCoverageIf(v
, opSeek
==OP_NotExists
);
774 VdbeCoverageIf(v
, opSeek
==OP_NotFound
);
777 /* If there are any triggers to fire, allocate a range of registers to
778 ** use for the old.* references in the triggers. */
779 if( sqlite3FkRequired(pParse
, pTab
, 0, 0) || pTrigger
){
780 u32 mask
; /* Mask of OLD.* columns in use */
781 int iCol
; /* Iterator used while populating OLD.* */
782 int addrStart
; /* Start of BEFORE trigger programs */
784 /* TODO: Could use temporary registers here. Also could attempt to
785 ** avoid copying the contents of the rowid register. */
786 mask
= sqlite3TriggerColmask(
787 pParse
, pTrigger
, 0, 0, TRIGGER_BEFORE
|TRIGGER_AFTER
, pTab
, onconf
789 mask
|= sqlite3FkOldmask(pParse
, pTab
);
790 iOld
= pParse
->nMem
+1;
791 pParse
->nMem
+= (1 + pTab
->nCol
);
793 /* Populate the OLD.* pseudo-table register array. These values will be
794 ** used by any BEFORE and AFTER triggers that exist. */
795 sqlite3VdbeAddOp2(v
, OP_Copy
, iPk
, iOld
);
796 for(iCol
=0; iCol
<pTab
->nCol
; iCol
++){
797 testcase( mask
!=0xffffffff && iCol
==31 );
798 testcase( mask
!=0xffffffff && iCol
==32 );
799 if( mask
==0xffffffff || (iCol
<=31 && (mask
& MASKBIT32(iCol
))!=0) ){
800 int kk
= sqlite3TableColumnToStorage(pTab
, iCol
);
801 sqlite3ExprCodeGetColumnOfTable(v
, pTab
, iDataCur
, iCol
, iOld
+kk
+1);
805 /* Invoke BEFORE DELETE trigger programs. */
806 addrStart
= sqlite3VdbeCurrentAddr(v
);
807 sqlite3CodeRowTrigger(pParse
, pTrigger
,
808 TK_DELETE
, 0, TRIGGER_BEFORE
, pTab
, iOld
, onconf
, iLabel
811 /* If any BEFORE triggers were coded, then seek the cursor to the
812 ** row to be deleted again. It may be that the BEFORE triggers moved
813 ** the cursor or already deleted the row that the cursor was
816 ** Also disable the iIdxNoSeek optimization since the BEFORE trigger
817 ** may have moved that cursor.
819 if( addrStart
<sqlite3VdbeCurrentAddr(v
) ){
820 sqlite3VdbeAddOp4Int(v
, opSeek
, iDataCur
, iLabel
, iPk
, nPk
);
821 VdbeCoverageIf(v
, opSeek
==OP_NotExists
);
822 VdbeCoverageIf(v
, opSeek
==OP_NotFound
);
823 testcase( iIdxNoSeek
>=0 );
827 /* Do FK processing. This call checks that any FK constraints that
828 ** refer to this table (i.e. constraints attached to other tables)
829 ** are not violated by deleting this row. */
830 sqlite3FkCheck(pParse
, pTab
, iOld
, 0, 0, 0);
833 /* Delete the index and table entries. Skip this step if pTab is really
834 ** a view (in which case the only effect of the DELETE statement is to
835 ** fire the INSTEAD OF triggers).
837 ** If variable 'count' is non-zero, then this OP_Delete instruction should
838 ** invoke the update-hook. The pre-update-hook, on the other hand should
839 ** be invoked unless table pTab is a system table. The difference is that
840 ** the update-hook is not invoked for rows removed by REPLACE, but the
841 ** pre-update-hook is.
845 sqlite3GenerateRowIndexDelete(pParse
, pTab
, iDataCur
, iIdxCur
,0,iIdxNoSeek
);
846 sqlite3VdbeAddOp2(v
, OP_Delete
, iDataCur
, (count
?OPFLAG_NCHANGE
:0));
847 if( pParse
->nested
==0 || 0==sqlite3_stricmp(pTab
->zName
, "sqlite_stat1") ){
848 sqlite3VdbeAppendP4(v
, (char*)pTab
, P4_TABLE
);
850 if( eMode
!=ONEPASS_OFF
){
851 sqlite3VdbeChangeP5(v
, OPFLAG_AUXDELETE
);
853 if( iIdxNoSeek
>=0 && iIdxNoSeek
!=iDataCur
){
854 sqlite3VdbeAddOp1(v
, OP_Delete
, iIdxNoSeek
);
856 if( eMode
==ONEPASS_MULTI
) p5
|= OPFLAG_SAVEPOSITION
;
857 sqlite3VdbeChangeP5(v
, p5
);
860 /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
861 ** handle rows (possibly in other tables) that refer via a foreign key
862 ** to the row just deleted. */
863 sqlite3FkActions(pParse
, pTab
, 0, iOld
, 0, 0);
865 /* Invoke AFTER DELETE trigger programs. */
867 sqlite3CodeRowTrigger(pParse
, pTrigger
,
868 TK_DELETE
, 0, TRIGGER_AFTER
, pTab
, iOld
, onconf
, iLabel
872 /* Jump here if the row had already been deleted before any BEFORE
873 ** trigger programs were invoked. Or if a trigger program throws a
874 ** RAISE(IGNORE) exception. */
875 sqlite3VdbeResolveLabel(v
, iLabel
);
876 VdbeModuleComment((v
, "END: GenRowDel()"));
880 ** This routine generates VDBE code that causes the deletion of all
881 ** index entries associated with a single row of a single table, pTab
885 ** 1. A read/write cursor "iDataCur" must be open on the canonical storage
886 ** btree for the table pTab. (This will be either the table itself
887 ** for rowid tables or to the primary key index for WITHOUT ROWID
890 ** 2. Read/write cursors for all indices of pTab must be open as
891 ** cursor number iIdxCur+i for the i-th index. (The pTab->pIndex
892 ** index is the 0-th index.)
894 ** 3. The "iDataCur" cursor must be already be positioned on the row
895 ** that is to be deleted.
897 void sqlite3GenerateRowIndexDelete(
898 Parse
*pParse
, /* Parsing and code generating context */
899 Table
*pTab
, /* Table containing the row to be deleted */
900 int iDataCur
, /* Cursor of table holding data. */
901 int iIdxCur
, /* First index cursor */
902 int *aRegIdx
, /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
903 int iIdxNoSeek
/* Do not delete from this cursor */
905 int i
; /* Index loop counter */
906 int r1
= -1; /* Register holding an index key */
907 int iPartIdxLabel
; /* Jump destination for skipping partial index entries */
908 Index
*pIdx
; /* Current index */
909 Index
*pPrior
= 0; /* Prior index */
910 Vdbe
*v
; /* The prepared statement under construction */
911 Index
*pPk
; /* PRIMARY KEY index, or NULL for rowid tables */
914 pPk
= HasRowid(pTab
) ? 0 : sqlite3PrimaryKeyIndex(pTab
);
915 for(i
=0, pIdx
=pTab
->pIndex
; pIdx
; i
++, pIdx
=pIdx
->pNext
){
916 assert( iIdxCur
+i
!=iDataCur
|| pPk
==pIdx
);
917 if( aRegIdx
!=0 && aRegIdx
[i
]==0 ) continue;
918 if( pIdx
==pPk
) continue;
919 if( iIdxCur
+i
==iIdxNoSeek
) continue;
920 VdbeModuleComment((v
, "GenRowIdxDel for %s", pIdx
->zName
));
921 r1
= sqlite3GenerateIndexKey(pParse
, pIdx
, iDataCur
, 0, 1,
922 &iPartIdxLabel
, pPrior
, r1
);
923 sqlite3VdbeAddOp3(v
, OP_IdxDelete
, iIdxCur
+i
, r1
,
924 pIdx
->uniqNotNull
? pIdx
->nKeyCol
: pIdx
->nColumn
);
925 sqlite3VdbeChangeP5(v
, 1); /* Cause IdxDelete to error if no entry found */
926 sqlite3ResolvePartIdxLabel(pParse
, iPartIdxLabel
);
932 ** Generate code that will assemble an index key and stores it in register
933 ** regOut. The key with be for index pIdx which is an index on pTab.
934 ** iCur is the index of a cursor open on the pTab table and pointing to
935 ** the entry that needs indexing. If pTab is a WITHOUT ROWID table, then
936 ** iCur must be the cursor of the PRIMARY KEY index.
938 ** Return a register number which is the first in a block of
939 ** registers that holds the elements of the index key. The
940 ** block of registers has already been deallocated by the time
941 ** this routine returns.
943 ** If *piPartIdxLabel is not NULL, fill it in with a label and jump
944 ** to that label if pIdx is a partial index that should be skipped.
945 ** The label should be resolved using sqlite3ResolvePartIdxLabel().
946 ** A partial index should be skipped if its WHERE clause evaluates
947 ** to false or null. If pIdx is not a partial index, *piPartIdxLabel
948 ** will be set to zero which is an empty label that is ignored by
949 ** sqlite3ResolvePartIdxLabel().
951 ** The pPrior and regPrior parameters are used to implement a cache to
952 ** avoid unnecessary register loads. If pPrior is not NULL, then it is
953 ** a pointer to a different index for which an index key has just been
954 ** computed into register regPrior. If the current pIdx index is generating
955 ** its key into the same sequence of registers and if pPrior and pIdx share
956 ** a column in common, then the register corresponding to that column already
957 ** holds the correct value and the loading of that register is skipped.
958 ** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK
959 ** on a table with multiple indices, and especially with the ROWID or
960 ** PRIMARY KEY columns of the index.
962 int sqlite3GenerateIndexKey(
963 Parse
*pParse
, /* Parsing context */
964 Index
*pIdx
, /* The index for which to generate a key */
965 int iDataCur
, /* Cursor number from which to take column data */
966 int regOut
, /* Put the new key into this register if not 0 */
967 int prefixOnly
, /* Compute only a unique prefix of the key */
968 int *piPartIdxLabel
, /* OUT: Jump to this label to skip partial index */
969 Index
*pPrior
, /* Previously generated index key */
970 int regPrior
/* Register holding previous generated key */
972 Vdbe
*v
= pParse
->pVdbe
;
977 if( piPartIdxLabel
){
978 if( pIdx
->pPartIdxWhere
){
979 *piPartIdxLabel
= sqlite3VdbeMakeLabel(pParse
);
980 pParse
->iSelfTab
= iDataCur
+ 1;
981 sqlite3ExprIfFalseDup(pParse
, pIdx
->pPartIdxWhere
, *piPartIdxLabel
,
983 pParse
->iSelfTab
= 0;
984 pPrior
= 0; /* Ticket a9efb42811fa41ee 2019-11-02;
985 ** pPartIdxWhere may have corrupted regPrior registers */
990 nCol
= (prefixOnly
&& pIdx
->uniqNotNull
) ? pIdx
->nKeyCol
: pIdx
->nColumn
;
991 regBase
= sqlite3GetTempRange(pParse
, nCol
);
992 if( pPrior
&& (regBase
!=regPrior
|| pPrior
->pPartIdxWhere
) ) pPrior
= 0;
993 for(j
=0; j
<nCol
; j
++){
995 && pPrior
->aiColumn
[j
]==pIdx
->aiColumn
[j
]
996 && pPrior
->aiColumn
[j
]!=XN_EXPR
998 /* This column was already computed by the previous index */
1001 sqlite3ExprCodeLoadIndexColumn(pParse
, pIdx
, iDataCur
, j
, regBase
+j
);
1002 if( pIdx
->aiColumn
[j
]>=0 ){
1003 /* If the column affinity is REAL but the number is an integer, then it
1004 ** might be stored in the table as an integer (using a compact
1005 ** representation) then converted to REAL by an OP_RealAffinity opcode.
1006 ** But we are getting ready to store this value back into an index, where
1007 ** it should be converted by to INTEGER again. So omit the
1008 ** OP_RealAffinity opcode if it is present */
1009 sqlite3VdbeDeletePriorOpcode(v
, OP_RealAffinity
);
1013 sqlite3VdbeAddOp3(v
, OP_MakeRecord
, regBase
, nCol
, regOut
);
1015 sqlite3ReleaseTempRange(pParse
, regBase
, nCol
);
1020 ** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
1021 ** because it was a partial index, then this routine should be called to
1022 ** resolve that label.
1024 void sqlite3ResolvePartIdxLabel(Parse
*pParse
, int iLabel
){
1026 sqlite3VdbeResolveLabel(pParse
->pVdbe
, iLabel
);