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 sqlite3DeleteTable(pParse
->db
, pItem
->pTab
);
40 if( pItem
->fg
.isIndexedBy
&& sqlite3IndexedByLookup(pParse
, pItem
) ){
47 /* Generate byte-code that will report the number of rows modified
48 ** by a DELETE, INSERT, or UPDATE statement.
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
);
57 /* Return true if table pTab is read-only.
59 ** A table is read-only if any of the following are true:
61 ** 1) It is a virtual table and no implementation of the xUpdate method
64 ** 2) A trigger is currently being coded and the table is a virtual table
65 ** that is SQLITE_VTAB_DIRECTONLY or if PRAGMA trusted_schema=OFF and
66 ** the table is not SQLITE_VTAB_INNOCUOUS.
68 ** 3) It is a system table (i.e. sqlite_schema), this call is not
69 ** part of a nested parse and writable_schema pragma has not
72 ** 4) The table is a shadow table, the database connection is in
73 ** defensive mode, and the current sqlite3_prepare()
74 ** is for a top-level SQL statement.
76 static int vtabIsReadOnly(Parse
*pParse
, Table
*pTab
){
77 if( sqlite3GetVTable(pParse
->db
, pTab
)->pMod
->pModule
->xUpdate
==0 ){
82 ** * Do not allow DELETE, INSERT, or UPDATE of SQLITE_VTAB_DIRECTONLY
84 ** * Only allow DELETE, INSERT, or UPDATE of non-SQLITE_VTAB_INNOCUOUS
85 ** virtual tables if PRAGMA trusted_schema=ON.
87 if( pParse
->pToplevel
!=0
88 && pTab
->u
.vtab
.p
->eVtabRisk
>
89 ((pParse
->db
->flags
& SQLITE_TrustedSchema
)!=0)
91 sqlite3ErrorMsg(pParse
, "unsafe use of virtual table \"%s\"",
96 static int tabIsReadOnly(Parse
*pParse
, Table
*pTab
){
98 if( IsVirtual(pTab
) ){
99 return vtabIsReadOnly(pParse
, pTab
);
101 if( (pTab
->tabFlags
& (TF_Readonly
|TF_Shadow
))==0 ) return 0;
103 if( (pTab
->tabFlags
& TF_Readonly
)!=0 ){
104 return sqlite3WritableSchema(db
)==0 && pParse
->nested
==0;
106 assert( pTab
->tabFlags
& TF_Shadow
);
107 return sqlite3ReadOnlyShadowTables(db
);
111 ** Check to make sure the given table is writable.
113 ** If pTab is not writable -> generate an error message and return 1.
114 ** If pTab is writable but other errors have occurred -> return 1.
115 ** If pTab is writable and no prior errors -> return 0;
117 int sqlite3IsReadOnly(Parse
*pParse
, Table
*pTab
, Trigger
*pTrigger
){
118 if( tabIsReadOnly(pParse
, pTab
) ){
119 sqlite3ErrorMsg(pParse
, "table %s may not be modified", pTab
->zName
);
122 #ifndef SQLITE_OMIT_VIEW
124 && (pTrigger
==0 || (pTrigger
->bReturning
&& pTrigger
->pNext
==0))
126 sqlite3ErrorMsg(pParse
,"cannot modify %s because it is a view",pTab
->zName
);
134 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
136 ** Evaluate a view and store its result in an ephemeral table. The
137 ** pWhere argument is an optional WHERE clause that restricts the
138 ** set of rows in the view that are to be added to the ephemeral table.
140 void sqlite3MaterializeView(
141 Parse
*pParse
, /* Parsing context */
142 Table
*pView
, /* View definition */
143 Expr
*pWhere
, /* Optional WHERE clause to be added */
144 ExprList
*pOrderBy
, /* Optional ORDER BY clause */
145 Expr
*pLimit
, /* Optional LIMIT clause */
146 int iCur
/* Cursor number for ephemeral table */
151 sqlite3
*db
= pParse
->db
;
152 int iDb
= sqlite3SchemaToIndex(db
, pView
->pSchema
);
153 pWhere
= sqlite3ExprDup(db
, pWhere
, 0);
154 pFrom
= sqlite3SrcListAppend(pParse
, 0, 0, 0);
156 assert( pFrom
->nSrc
==1 );
157 pFrom
->a
[0].zName
= sqlite3DbStrDup(db
, pView
->zName
);
158 pFrom
->a
[0].zDatabase
= sqlite3DbStrDup(db
, db
->aDb
[iDb
].zDbSName
);
159 assert( pFrom
->a
[0].fg
.isUsing
==0 );
160 assert( pFrom
->a
[0].u3
.pOn
==0 );
162 pSel
= sqlite3SelectNew(pParse
, 0, pFrom
, pWhere
, 0, 0, pOrderBy
,
163 SF_IncludeHidden
, pLimit
);
164 sqlite3SelectDestInit(&dest
, SRT_EphemTab
, iCur
);
165 sqlite3Select(pParse
, pSel
, &dest
);
166 sqlite3SelectDelete(db
, pSel
);
168 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
170 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
172 ** Generate an expression tree to implement the WHERE, ORDER BY,
173 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
175 ** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
176 ** \__________________________/
177 ** pLimitWhere (pInClause)
179 Expr
*sqlite3LimitWhere(
180 Parse
*pParse
, /* The parser context */
181 SrcList
*pSrc
, /* the FROM clause -- which tables to scan */
182 Expr
*pWhere
, /* The WHERE clause. May be null */
183 ExprList
*pOrderBy
, /* The ORDER BY clause. May be null */
184 Expr
*pLimit
, /* The LIMIT clause. May be null */
185 char *zStmtType
/* Either DELETE or UPDATE. For err msgs. */
187 sqlite3
*db
= pParse
->db
;
188 Expr
*pLhs
= NULL
; /* LHS of IN(SELECT...) operator */
189 Expr
*pInClause
= NULL
; /* WHERE rowid IN ( select ) */
190 ExprList
*pEList
= NULL
; /* Expression list contaning only pSelectRowid */
191 SrcList
*pSelectSrc
= NULL
; /* SELECT rowid FROM x ... (dup of pSrc) */
192 Select
*pSelect
= NULL
; /* Complete SELECT tree */
195 /* Check that there isn't an ORDER BY without a LIMIT clause.
197 if( pOrderBy
&& pLimit
==0 ) {
198 sqlite3ErrorMsg(pParse
, "ORDER BY without LIMIT on %s", zStmtType
);
199 sqlite3ExprDelete(pParse
->db
, pWhere
);
200 sqlite3ExprListDelete(pParse
->db
, pOrderBy
);
204 /* We only need to generate a select expression if there
205 ** is a limit/offset term to enforce.
211 /* Generate a select expression tree to enforce the limit/offset
212 ** term for the DELETE or UPDATE statement. For example:
213 ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
215 ** DELETE FROM table_a WHERE rowid IN (
216 ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
220 pTab
= pSrc
->a
[0].pTab
;
221 if( HasRowid(pTab
) ){
222 pLhs
= sqlite3PExpr(pParse
, TK_ROW
, 0, 0);
223 pEList
= sqlite3ExprListAppend(
224 pParse
, 0, sqlite3PExpr(pParse
, TK_ROW
, 0, 0)
227 Index
*pPk
= sqlite3PrimaryKeyIndex(pTab
);
228 if( pPk
->nKeyCol
==1 ){
229 const char *zName
= pTab
->aCol
[pPk
->aiColumn
[0]].zCnName
;
230 pLhs
= sqlite3Expr(db
, TK_ID
, zName
);
231 pEList
= sqlite3ExprListAppend(pParse
, 0, sqlite3Expr(db
, TK_ID
, zName
));
234 for(i
=0; i
<pPk
->nKeyCol
; i
++){
235 Expr
*p
= sqlite3Expr(db
, TK_ID
, pTab
->aCol
[pPk
->aiColumn
[i
]].zCnName
);
236 pEList
= sqlite3ExprListAppend(pParse
, pEList
, p
);
238 pLhs
= sqlite3PExpr(pParse
, TK_VECTOR
, 0, 0);
240 pLhs
->x
.pList
= sqlite3ExprListDup(db
, pEList
, 0);
245 /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
246 ** and the SELECT subtree. */
248 pSelectSrc
= sqlite3SrcListDup(db
, pSrc
, 0);
249 pSrc
->a
[0].pTab
= pTab
;
250 if( pSrc
->a
[0].fg
.isIndexedBy
){
251 assert( pSrc
->a
[0].fg
.isCte
==0 );
252 pSrc
->a
[0].u2
.pIBIndex
= 0;
253 pSrc
->a
[0].fg
.isIndexedBy
= 0;
254 sqlite3DbFree(db
, pSrc
->a
[0].u1
.zIndexedBy
);
255 }else if( pSrc
->a
[0].fg
.isCte
){
256 pSrc
->a
[0].u2
.pCteUse
->nUse
++;
259 /* generate the SELECT expression tree. */
260 pSelect
= sqlite3SelectNew(pParse
, pEList
, pSelectSrc
, pWhere
, 0 ,0,
264 /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
265 pInClause
= sqlite3PExpr(pParse
, TK_IN
, pLhs
, 0);
266 sqlite3PExprAddSelect(pParse
, pInClause
, pSelect
);
269 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */
270 /* && !defined(SQLITE_OMIT_SUBQUERY) */
273 ** Generate code for a DELETE FROM statement.
275 ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
276 ** \________/ \________________/
279 void sqlite3DeleteFrom(
280 Parse
*pParse
, /* The parser context */
281 SrcList
*pTabList
, /* The table from which we should delete things */
282 Expr
*pWhere
, /* The WHERE clause. May be null */
283 ExprList
*pOrderBy
, /* ORDER BY clause. May be null */
284 Expr
*pLimit
/* LIMIT clause. May be null */
286 Vdbe
*v
; /* The virtual database engine */
287 Table
*pTab
; /* The table from which records will be deleted */
288 int i
; /* Loop counter */
289 WhereInfo
*pWInfo
; /* Information about the WHERE clause */
290 Index
*pIdx
; /* For looping over indices of the table */
291 int iTabCur
; /* Cursor number for the table */
292 int iDataCur
= 0; /* VDBE cursor for the canonical data source */
293 int iIdxCur
= 0; /* Cursor number of the first index */
294 int nIdx
; /* Number of indices */
295 sqlite3
*db
; /* Main database structure */
296 AuthContext sContext
; /* Authorization context */
297 NameContext sNC
; /* Name context to resolve expressions in */
298 int iDb
; /* Database number */
299 int memCnt
= 0; /* Memory cell used for change counting */
300 int rcauth
; /* Value returned by authorization callback */
301 int eOnePass
; /* ONEPASS_OFF or _SINGLE or _MULTI */
302 int aiCurOnePass
[2]; /* The write cursors opened by WHERE_ONEPASS */
303 u8
*aToOpen
= 0; /* Open cursor iTabCur+j if aToOpen[j] is true */
304 Index
*pPk
; /* The PRIMARY KEY index on the table */
305 int iPk
= 0; /* First of nPk registers holding PRIMARY KEY value */
306 i16 nPk
= 1; /* Number of columns in the PRIMARY KEY */
307 int iKey
; /* Memory cell holding key of row to be deleted */
308 i16 nKey
; /* Number of memory cells in the row key */
309 int iEphCur
= 0; /* Ephemeral table holding all primary key values */
310 int iRowSet
= 0; /* Register for rowset of rows to delete */
311 int addrBypass
= 0; /* Address of jump over the delete logic */
312 int addrLoop
= 0; /* Top of the delete loop */
313 int addrEphOpen
= 0; /* Instruction to open the Ephemeral table */
314 int bComplex
; /* True if there are triggers or FKs or
315 ** subqueries in the WHERE clause */
317 #ifndef SQLITE_OMIT_TRIGGER
318 int isView
; /* True if attempting to delete from a view */
319 Trigger
*pTrigger
; /* List of table triggers, if required */
322 memset(&sContext
, 0, sizeof(sContext
));
324 assert( db
->pParse
==pParse
);
326 goto delete_from_cleanup
;
328 assert( db
->mallocFailed
==0 );
329 assert( pTabList
->nSrc
==1 );
331 /* Locate the table which we want to delete. This table has to be
332 ** put in an SrcList structure because some of the subroutines we
333 ** will be calling are designed to work with multiple tables and expect
334 ** an SrcList* parameter instead of just a Table* parameter.
336 pTab
= sqlite3SrcListLookup(pParse
, pTabList
);
337 if( pTab
==0 ) goto delete_from_cleanup
;
339 /* Figure out if we have any triggers and if the table being
340 ** deleted from is a view
342 #ifndef SQLITE_OMIT_TRIGGER
343 pTrigger
= sqlite3TriggersExist(pParse
, pTab
, TK_DELETE
, 0, 0);
344 isView
= IsView(pTab
);
349 bComplex
= pTrigger
|| sqlite3FkRequired(pParse
, pTab
, 0, 0);
350 #ifdef SQLITE_OMIT_VIEW
355 #if TREETRACE_ENABLED
356 if( sqlite3TreeTrace
& 0x10000 ){
357 sqlite3TreeViewLine(0, "In sqlite3Delete() at %s:%d", __FILE__
, __LINE__
);
358 sqlite3TreeViewDelete(pParse
->pWith
, pTabList
, pWhere
,
359 pOrderBy
, pLimit
, pTrigger
);
363 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
365 pWhere
= sqlite3LimitWhere(
366 pParse
, pTabList
, pWhere
, pOrderBy
, pLimit
, "DELETE"
373 /* If pTab is really a view, make sure it has been initialized.
375 if( sqlite3ViewGetColumnNames(pParse
, pTab
) ){
376 goto delete_from_cleanup
;
379 if( sqlite3IsReadOnly(pParse
, pTab
, pTrigger
) ){
380 goto delete_from_cleanup
;
382 iDb
= sqlite3SchemaToIndex(db
, pTab
->pSchema
);
383 assert( iDb
<db
->nDb
);
384 rcauth
= sqlite3AuthCheck(pParse
, SQLITE_DELETE
, pTab
->zName
, 0,
385 db
->aDb
[iDb
].zDbSName
);
386 assert( rcauth
==SQLITE_OK
|| rcauth
==SQLITE_DENY
|| rcauth
==SQLITE_IGNORE
);
387 if( rcauth
==SQLITE_DENY
){
388 goto delete_from_cleanup
;
390 assert(!isView
|| pTrigger
);
392 /* Assign cursor numbers to the table and all its indices.
394 assert( pTabList
->nSrc
==1 );
395 iTabCur
= pTabList
->a
[0].iCursor
= pParse
->nTab
++;
396 for(nIdx
=0, pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
, nIdx
++){
400 /* Start the view context
403 sqlite3AuthContextPush(pParse
, &sContext
, pTab
->zName
);
406 /* Begin generating code.
408 v
= sqlite3GetVdbe(pParse
);
410 goto delete_from_cleanup
;
412 if( pParse
->nested
==0 ) sqlite3VdbeCountChanges(v
);
413 sqlite3BeginWriteOperation(pParse
, bComplex
, iDb
);
415 /* If we are trying to delete from a view, realize that view into
416 ** an ephemeral table.
418 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
420 sqlite3MaterializeView(pParse
, pTab
,
421 pWhere
, pOrderBy
, pLimit
, iTabCur
423 iDataCur
= iIdxCur
= iTabCur
;
429 /* Resolve the column names in the WHERE clause.
431 memset(&sNC
, 0, sizeof(sNC
));
433 sNC
.pSrcList
= pTabList
;
434 if( sqlite3ResolveExprNames(&sNC
, pWhere
) ){
435 goto delete_from_cleanup
;
438 /* Initialize the counter of the number of rows deleted, if
439 ** we are counting rows.
441 if( (db
->flags
& SQLITE_CountRows
)!=0
443 && !pParse
->pTriggerTab
444 && !pParse
->bReturning
446 memCnt
= ++pParse
->nMem
;
447 sqlite3VdbeAddOp2(v
, OP_Integer
, 0, memCnt
);
450 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
451 /* Special case: A DELETE without a WHERE clause deletes everything.
452 ** It is easier just to erase the whole table. Prior to version 3.6.5,
453 ** this optimization caused the row change count (the value returned by
454 ** API function sqlite3_count_changes) to be set incorrectly.
456 ** The "rcauth==SQLITE_OK" terms is the
457 ** IMPLEMENTATION-OF: R-17228-37124 If the action code is SQLITE_DELETE and
458 ** the callback returns SQLITE_IGNORE then the DELETE operation proceeds but
459 ** the truncate optimization is disabled and all rows are deleted
462 if( rcauth
==SQLITE_OK
466 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
467 && db
->xPreUpdateCallback
==0
471 sqlite3TableLock(pParse
, iDb
, pTab
->tnum
, 1, pTab
->zName
);
472 if( HasRowid(pTab
) ){
473 sqlite3VdbeAddOp4(v
, OP_Clear
, pTab
->tnum
, iDb
, memCnt
? memCnt
: -1,
474 pTab
->zName
, P4_STATIC
);
476 for(pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
){
477 assert( pIdx
->pSchema
==pTab
->pSchema
);
478 if( IsPrimaryKeyIndex(pIdx
) && !HasRowid(pTab
) ){
479 sqlite3VdbeAddOp3(v
, OP_Clear
, pIdx
->tnum
, iDb
, memCnt
? memCnt
: -1);
481 sqlite3VdbeAddOp2(v
, OP_Clear
, pIdx
->tnum
, iDb
);
485 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
487 u16 wcf
= WHERE_ONEPASS_DESIRED
|WHERE_DUPLICATES_OK
;
488 if( sNC
.ncFlags
& NC_Subquery
) bComplex
= 1;
489 wcf
|= (bComplex
? 0 : WHERE_ONEPASS_MULTIROW
);
490 if( HasRowid(pTab
) ){
491 /* For a rowid table, initialize the RowSet to an empty set */
494 iRowSet
= ++pParse
->nMem
;
495 sqlite3VdbeAddOp2(v
, OP_Null
, 0, iRowSet
);
497 /* For a WITHOUT ROWID table, create an ephemeral table used to
498 ** hold all primary keys for rows to be deleted. */
499 pPk
= sqlite3PrimaryKeyIndex(pTab
);
502 iPk
= pParse
->nMem
+1;
504 iEphCur
= pParse
->nTab
++;
505 addrEphOpen
= sqlite3VdbeAddOp2(v
, OP_OpenEphemeral
, iEphCur
, nPk
);
506 sqlite3VdbeSetP4KeyInfo(pParse
, pPk
);
509 /* Construct a query to find the rowid or primary key for every row
510 ** to be deleted, based on the WHERE clause. Set variable eOnePass
511 ** to indicate the strategy used to implement this delete:
513 ** ONEPASS_OFF: Two-pass approach - use a FIFO for rowids/PK values.
514 ** ONEPASS_SINGLE: One-pass approach - at most one row deleted.
515 ** ONEPASS_MULTI: One-pass approach - any number of rows may be deleted.
517 pWInfo
= sqlite3WhereBegin(pParse
, pTabList
, pWhere
, 0, 0,0,wcf
,iTabCur
+1);
518 if( pWInfo
==0 ) goto delete_from_cleanup
;
519 eOnePass
= sqlite3WhereOkOnePass(pWInfo
, aiCurOnePass
);
520 assert( IsVirtual(pTab
)==0 || eOnePass
!=ONEPASS_MULTI
);
521 assert( IsVirtual(pTab
) || bComplex
|| eOnePass
!=ONEPASS_OFF
);
522 if( eOnePass
!=ONEPASS_SINGLE
) sqlite3MultiWrite(pParse
);
523 if( sqlite3WhereUsesDeferredSeek(pWInfo
) ){
524 sqlite3VdbeAddOp1(v
, OP_FinishSeek
, iTabCur
);
527 /* Keep track of the number of rows to be deleted */
529 sqlite3VdbeAddOp2(v
, OP_AddImm
, memCnt
, 1);
532 /* Extract the rowid or primary key for the current row */
534 for(i
=0; i
<nPk
; i
++){
535 assert( pPk
->aiColumn
[i
]>=0 );
536 sqlite3ExprCodeGetColumnOfTable(v
, pTab
, iTabCur
,
537 pPk
->aiColumn
[i
], iPk
+i
);
541 iKey
= ++pParse
->nMem
;
542 sqlite3ExprCodeGetColumnOfTable(v
, pTab
, iTabCur
, -1, iKey
);
545 if( eOnePass
!=ONEPASS_OFF
){
546 /* For ONEPASS, no need to store the rowid/primary-key. There is only
547 ** one, so just keep it in its register(s) and fall through to the
549 nKey
= nPk
; /* OP_Found will use an unpacked key */
550 aToOpen
= sqlite3DbMallocRawNN(db
, nIdx
+2);
552 sqlite3WhereEnd(pWInfo
);
553 goto delete_from_cleanup
;
555 memset(aToOpen
, 1, nIdx
+1);
557 if( aiCurOnePass
[0]>=0 ) aToOpen
[aiCurOnePass
[0]-iTabCur
] = 0;
558 if( aiCurOnePass
[1]>=0 ) aToOpen
[aiCurOnePass
[1]-iTabCur
] = 0;
559 if( addrEphOpen
) sqlite3VdbeChangeToNoop(v
, addrEphOpen
);
560 addrBypass
= sqlite3VdbeMakeLabel(pParse
);
563 /* Add the PK key for this row to the temporary table */
564 iKey
= ++pParse
->nMem
;
565 nKey
= 0; /* Zero tells OP_Found to use a composite key */
566 sqlite3VdbeAddOp4(v
, OP_MakeRecord
, iPk
, nPk
, iKey
,
567 sqlite3IndexAffinityStr(pParse
->db
, pPk
), nPk
);
568 sqlite3VdbeAddOp4Int(v
, OP_IdxInsert
, iEphCur
, iKey
, iPk
, nPk
);
570 /* Add the rowid of the row to be deleted to the RowSet */
571 nKey
= 1; /* OP_DeferredSeek always uses a single rowid */
572 sqlite3VdbeAddOp2(v
, OP_RowSetAdd
, iRowSet
, iKey
);
574 sqlite3WhereEnd(pWInfo
);
577 /* Unless this is a view, open cursors for the table we are
578 ** deleting from and all its indices. If this is a view, then the
579 ** only effect this statement has is to fire the INSTEAD OF
584 if( eOnePass
==ONEPASS_MULTI
){
585 iAddrOnce
= sqlite3VdbeAddOp0(v
, OP_Once
); VdbeCoverage(v
);
587 testcase( IsVirtual(pTab
) );
588 sqlite3OpenTableAndIndices(pParse
, pTab
, OP_OpenWrite
, OPFLAG_FORDELETE
,
589 iTabCur
, aToOpen
, &iDataCur
, &iIdxCur
);
590 assert( pPk
|| IsVirtual(pTab
) || iDataCur
==iTabCur
);
591 assert( pPk
|| IsVirtual(pTab
) || iIdxCur
==iDataCur
+1 );
592 if( eOnePass
==ONEPASS_MULTI
){
593 sqlite3VdbeJumpHereOrPopInst(v
, iAddrOnce
);
597 /* Set up a loop over the rowids/primary-keys that were found in the
598 ** where-clause loop above.
600 if( eOnePass
!=ONEPASS_OFF
){
601 assert( nKey
==nPk
); /* OP_Found will use an unpacked key */
602 if( !IsVirtual(pTab
) && aToOpen
[iDataCur
-iTabCur
] ){
603 assert( pPk
!=0 || IsView(pTab
) );
604 sqlite3VdbeAddOp4Int(v
, OP_NotFound
, iDataCur
, addrBypass
, iKey
, nKey
);
608 addrLoop
= sqlite3VdbeAddOp1(v
, OP_Rewind
, iEphCur
); VdbeCoverage(v
);
609 if( IsVirtual(pTab
) ){
610 sqlite3VdbeAddOp3(v
, OP_Column
, iEphCur
, 0, iKey
);
612 sqlite3VdbeAddOp2(v
, OP_RowData
, iEphCur
, iKey
);
614 assert( nKey
==0 ); /* OP_Found will use a composite key */
616 addrLoop
= sqlite3VdbeAddOp3(v
, OP_RowSetRead
, iRowSet
, 0, iKey
);
622 #ifndef SQLITE_OMIT_VIRTUALTABLE
623 if( IsVirtual(pTab
) ){
624 const char *pVTab
= (const char *)sqlite3GetVTable(db
, pTab
);
625 sqlite3VtabMakeWritable(pParse
, pTab
);
626 assert( eOnePass
==ONEPASS_OFF
|| eOnePass
==ONEPASS_SINGLE
);
627 sqlite3MayAbort(pParse
);
628 if( eOnePass
==ONEPASS_SINGLE
){
629 sqlite3VdbeAddOp1(v
, OP_Close
, iTabCur
);
630 if( sqlite3IsToplevel(pParse
) ){
631 pParse
->isMultiWrite
= 0;
634 sqlite3VdbeAddOp4(v
, OP_VUpdate
, 0, 1, iKey
, pVTab
, P4_VTAB
);
635 sqlite3VdbeChangeP5(v
, OE_Abort
);
639 int count
= (pParse
->nested
==0); /* True to count changes */
640 sqlite3GenerateRowDelete(pParse
, pTab
, pTrigger
, iDataCur
, iIdxCur
,
641 iKey
, nKey
, count
, OE_Default
, eOnePass
, aiCurOnePass
[1]);
644 /* End of the loop over all rowids/primary-keys. */
645 if( eOnePass
!=ONEPASS_OFF
){
646 sqlite3VdbeResolveLabel(v
, addrBypass
);
647 sqlite3WhereEnd(pWInfo
);
649 sqlite3VdbeAddOp2(v
, OP_Next
, iEphCur
, addrLoop
+1); VdbeCoverage(v
);
650 sqlite3VdbeJumpHere(v
, addrLoop
);
652 sqlite3VdbeGoto(v
, addrLoop
);
653 sqlite3VdbeJumpHere(v
, addrLoop
);
655 } /* End non-truncate path */
657 /* Update the sqlite_sequence table by storing the content of the
658 ** maximum rowid counter values recorded while inserting into
659 ** autoincrement tables.
661 if( pParse
->nested
==0 && pParse
->pTriggerTab
==0 ){
662 sqlite3AutoincrementEnd(pParse
);
665 /* Return the number of rows that were deleted. If this routine is
666 ** generating code because of a call to sqlite3NestedParse(), do not
667 ** invoke the callback function.
670 sqlite3CodeChangeCount(v
, memCnt
, "rows deleted");
674 sqlite3AuthContextPop(&sContext
);
675 sqlite3SrcListDelete(db
, pTabList
);
676 sqlite3ExprDelete(db
, pWhere
);
677 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
678 sqlite3ExprListDelete(db
, pOrderBy
);
679 sqlite3ExprDelete(db
, pLimit
);
681 if( aToOpen
) sqlite3DbNNFreeNN(db
, aToOpen
);
684 /* Make sure "isView" and other macros defined above are undefined. Otherwise
685 ** they may interfere with compilation of other functions in this file
686 ** (or in another file, if this file becomes part of the amalgamation). */
695 ** This routine generates VDBE code that causes a single row of a
696 ** single table to be deleted. Both the original table entry and
697 ** all indices are removed.
701 ** 1. iDataCur is an open cursor on the btree that is the canonical data
702 ** store for the table. (This will be either the table itself,
703 ** in the case of a rowid table, or the PRIMARY KEY index in the case
704 ** of a WITHOUT ROWID table.)
706 ** 2. Read/write cursors for all indices of pTab must be open as
707 ** cursor number iIdxCur+i for the i-th index.
709 ** 3. The primary key for the row to be deleted must be stored in a
710 ** sequence of nPk memory cells starting at iPk. If nPk==0 that means
711 ** that a search record formed from OP_MakeRecord is contained in the
712 ** single memory location iPk.
715 ** Parameter eMode may be passed either ONEPASS_OFF (0), ONEPASS_SINGLE, or
716 ** ONEPASS_MULTI. If eMode is not ONEPASS_OFF, then the cursor
717 ** iDataCur already points to the row to delete. If eMode is ONEPASS_OFF
718 ** then this function must seek iDataCur to the entry identified by iPk
719 ** and nPk before reading from it.
721 ** If eMode is ONEPASS_MULTI, then this call is being made as part
722 ** of a ONEPASS delete that affects multiple rows. In this case, if
723 ** iIdxNoSeek is a valid cursor number (>=0) and is not the same as
724 ** iDataCur, then its position should be preserved following the delete
725 ** operation. Or, if iIdxNoSeek is not a valid cursor number, the
726 ** position of iDataCur should be preserved instead.
729 ** If iIdxNoSeek is a valid cursor number (>=0) not equal to iDataCur,
730 ** then it identifies an index cursor (from within array of cursors
731 ** starting at iIdxCur) that already points to the index entry to be deleted.
732 ** Except, this optimization is disabled if there are BEFORE triggers since
733 ** the trigger body might have moved the cursor.
735 void sqlite3GenerateRowDelete(
736 Parse
*pParse
, /* Parsing context */
737 Table
*pTab
, /* Table containing the row to be deleted */
738 Trigger
*pTrigger
, /* List of triggers to (potentially) fire */
739 int iDataCur
, /* Cursor from which column data is extracted */
740 int iIdxCur
, /* First index cursor */
741 int iPk
, /* First memory cell containing the PRIMARY KEY */
742 i16 nPk
, /* Number of PRIMARY KEY memory cells */
743 u8 count
, /* If non-zero, increment the row change counter */
744 u8 onconf
, /* Default ON CONFLICT policy for triggers */
745 u8 eMode
, /* ONEPASS_OFF, _SINGLE, or _MULTI. See above */
746 int iIdxNoSeek
/* Cursor number of cursor that does not need seeking */
748 Vdbe
*v
= pParse
->pVdbe
; /* Vdbe */
749 int iOld
= 0; /* First register in OLD.* array */
750 int iLabel
; /* Label resolved to end of generated code */
751 u8 opSeek
; /* Seek opcode */
753 /* Vdbe is guaranteed to have been allocated by this stage. */
755 VdbeModuleComment((v
, "BEGIN: GenRowDel(%d,%d,%d,%d)",
756 iDataCur
, iIdxCur
, iPk
, (int)nPk
));
758 /* Seek cursor iCur to the row to delete. If this row no longer exists
759 ** (this can happen if a trigger program has already deleted it), do
760 ** not attempt to delete it or fire any DELETE triggers. */
761 iLabel
= sqlite3VdbeMakeLabel(pParse
);
762 opSeek
= HasRowid(pTab
) ? OP_NotExists
: OP_NotFound
;
763 if( eMode
==ONEPASS_OFF
){
764 sqlite3VdbeAddOp4Int(v
, opSeek
, iDataCur
, iLabel
, iPk
, nPk
);
765 VdbeCoverageIf(v
, opSeek
==OP_NotExists
);
766 VdbeCoverageIf(v
, opSeek
==OP_NotFound
);
769 /* If there are any triggers to fire, allocate a range of registers to
770 ** use for the old.* references in the triggers. */
771 if( sqlite3FkRequired(pParse
, pTab
, 0, 0) || pTrigger
){
772 u32 mask
; /* Mask of OLD.* columns in use */
773 int iCol
; /* Iterator used while populating OLD.* */
774 int addrStart
; /* Start of BEFORE trigger programs */
776 /* TODO: Could use temporary registers here. Also could attempt to
777 ** avoid copying the contents of the rowid register. */
778 mask
= sqlite3TriggerColmask(
779 pParse
, pTrigger
, 0, 0, TRIGGER_BEFORE
|TRIGGER_AFTER
, pTab
, onconf
781 mask
|= sqlite3FkOldmask(pParse
, pTab
);
782 iOld
= pParse
->nMem
+1;
783 pParse
->nMem
+= (1 + pTab
->nCol
);
785 /* Populate the OLD.* pseudo-table register array. These values will be
786 ** used by any BEFORE and AFTER triggers that exist. */
787 sqlite3VdbeAddOp2(v
, OP_Copy
, iPk
, iOld
);
788 for(iCol
=0; iCol
<pTab
->nCol
; iCol
++){
789 testcase( mask
!=0xffffffff && iCol
==31 );
790 testcase( mask
!=0xffffffff && iCol
==32 );
791 if( mask
==0xffffffff || (iCol
<=31 && (mask
& MASKBIT32(iCol
))!=0) ){
792 int kk
= sqlite3TableColumnToStorage(pTab
, iCol
);
793 sqlite3ExprCodeGetColumnOfTable(v
, pTab
, iDataCur
, iCol
, iOld
+kk
+1);
797 /* Invoke BEFORE DELETE trigger programs. */
798 addrStart
= sqlite3VdbeCurrentAddr(v
);
799 sqlite3CodeRowTrigger(pParse
, pTrigger
,
800 TK_DELETE
, 0, TRIGGER_BEFORE
, pTab
, iOld
, onconf
, iLabel
803 /* If any BEFORE triggers were coded, then seek the cursor to the
804 ** row to be deleted again. It may be that the BEFORE triggers moved
805 ** the cursor or already deleted the row that the cursor was
808 ** Also disable the iIdxNoSeek optimization since the BEFORE trigger
809 ** may have moved that cursor.
811 if( addrStart
<sqlite3VdbeCurrentAddr(v
) ){
812 sqlite3VdbeAddOp4Int(v
, opSeek
, iDataCur
, iLabel
, iPk
, nPk
);
813 VdbeCoverageIf(v
, opSeek
==OP_NotExists
);
814 VdbeCoverageIf(v
, opSeek
==OP_NotFound
);
815 testcase( iIdxNoSeek
>=0 );
819 /* Do FK processing. This call checks that any FK constraints that
820 ** refer to this table (i.e. constraints attached to other tables)
821 ** are not violated by deleting this row. */
822 sqlite3FkCheck(pParse
, pTab
, iOld
, 0, 0, 0);
825 /* Delete the index and table entries. Skip this step if pTab is really
826 ** a view (in which case the only effect of the DELETE statement is to
827 ** fire the INSTEAD OF triggers).
829 ** If variable 'count' is non-zero, then this OP_Delete instruction should
830 ** invoke the update-hook. The pre-update-hook, on the other hand should
831 ** be invoked unless table pTab is a system table. The difference is that
832 ** the update-hook is not invoked for rows removed by REPLACE, but the
833 ** pre-update-hook is.
837 sqlite3GenerateRowIndexDelete(pParse
, pTab
, iDataCur
, iIdxCur
,0,iIdxNoSeek
);
838 sqlite3VdbeAddOp2(v
, OP_Delete
, iDataCur
, (count
?OPFLAG_NCHANGE
:0));
839 if( pParse
->nested
==0 || 0==sqlite3_stricmp(pTab
->zName
, "sqlite_stat1") ){
840 sqlite3VdbeAppendP4(v
, (char*)pTab
, P4_TABLE
);
842 if( eMode
!=ONEPASS_OFF
){
843 sqlite3VdbeChangeP5(v
, OPFLAG_AUXDELETE
);
845 if( iIdxNoSeek
>=0 && iIdxNoSeek
!=iDataCur
){
846 sqlite3VdbeAddOp1(v
, OP_Delete
, iIdxNoSeek
);
848 if( eMode
==ONEPASS_MULTI
) p5
|= OPFLAG_SAVEPOSITION
;
849 sqlite3VdbeChangeP5(v
, p5
);
852 /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
853 ** handle rows (possibly in other tables) that refer via a foreign key
854 ** to the row just deleted. */
855 sqlite3FkActions(pParse
, pTab
, 0, iOld
, 0, 0);
857 /* Invoke AFTER DELETE trigger programs. */
858 sqlite3CodeRowTrigger(pParse
, pTrigger
,
859 TK_DELETE
, 0, TRIGGER_AFTER
, pTab
, iOld
, onconf
, iLabel
862 /* Jump here if the row had already been deleted before any BEFORE
863 ** trigger programs were invoked. Or if a trigger program throws a
864 ** RAISE(IGNORE) exception. */
865 sqlite3VdbeResolveLabel(v
, iLabel
);
866 VdbeModuleComment((v
, "END: GenRowDel()"));
870 ** This routine generates VDBE code that causes the deletion of all
871 ** index entries associated with a single row of a single table, pTab
875 ** 1. A read/write cursor "iDataCur" must be open on the canonical storage
876 ** btree for the table pTab. (This will be either the table itself
877 ** for rowid tables or to the primary key index for WITHOUT ROWID
880 ** 2. Read/write cursors for all indices of pTab must be open as
881 ** cursor number iIdxCur+i for the i-th index. (The pTab->pIndex
882 ** index is the 0-th index.)
884 ** 3. The "iDataCur" cursor must be already be positioned on the row
885 ** that is to be deleted.
887 void sqlite3GenerateRowIndexDelete(
888 Parse
*pParse
, /* Parsing and code generating context */
889 Table
*pTab
, /* Table containing the row to be deleted */
890 int iDataCur
, /* Cursor of table holding data. */
891 int iIdxCur
, /* First index cursor */
892 int *aRegIdx
, /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
893 int iIdxNoSeek
/* Do not delete from this cursor */
895 int i
; /* Index loop counter */
896 int r1
= -1; /* Register holding an index key */
897 int iPartIdxLabel
; /* Jump destination for skipping partial index entries */
898 Index
*pIdx
; /* Current index */
899 Index
*pPrior
= 0; /* Prior index */
900 Vdbe
*v
; /* The prepared statement under construction */
901 Index
*pPk
; /* PRIMARY KEY index, or NULL for rowid tables */
904 pPk
= HasRowid(pTab
) ? 0 : sqlite3PrimaryKeyIndex(pTab
);
905 for(i
=0, pIdx
=pTab
->pIndex
; pIdx
; i
++, pIdx
=pIdx
->pNext
){
906 assert( iIdxCur
+i
!=iDataCur
|| pPk
==pIdx
);
907 if( aRegIdx
!=0 && aRegIdx
[i
]==0 ) continue;
908 if( pIdx
==pPk
) continue;
909 if( iIdxCur
+i
==iIdxNoSeek
) continue;
910 VdbeModuleComment((v
, "GenRowIdxDel for %s", pIdx
->zName
));
911 r1
= sqlite3GenerateIndexKey(pParse
, pIdx
, iDataCur
, 0, 1,
912 &iPartIdxLabel
, pPrior
, r1
);
913 sqlite3VdbeAddOp3(v
, OP_IdxDelete
, iIdxCur
+i
, r1
,
914 pIdx
->uniqNotNull
? pIdx
->nKeyCol
: pIdx
->nColumn
);
915 sqlite3VdbeChangeP5(v
, 1); /* Cause IdxDelete to error if no entry found */
916 sqlite3ResolvePartIdxLabel(pParse
, iPartIdxLabel
);
922 ** Generate code that will assemble an index key and stores it in register
923 ** regOut. The key with be for index pIdx which is an index on pTab.
924 ** iCur is the index of a cursor open on the pTab table and pointing to
925 ** the entry that needs indexing. If pTab is a WITHOUT ROWID table, then
926 ** iCur must be the cursor of the PRIMARY KEY index.
928 ** Return a register number which is the first in a block of
929 ** registers that holds the elements of the index key. The
930 ** block of registers has already been deallocated by the time
931 ** this routine returns.
933 ** If *piPartIdxLabel is not NULL, fill it in with a label and jump
934 ** to that label if pIdx is a partial index that should be skipped.
935 ** The label should be resolved using sqlite3ResolvePartIdxLabel().
936 ** A partial index should be skipped if its WHERE clause evaluates
937 ** to false or null. If pIdx is not a partial index, *piPartIdxLabel
938 ** will be set to zero which is an empty label that is ignored by
939 ** sqlite3ResolvePartIdxLabel().
941 ** The pPrior and regPrior parameters are used to implement a cache to
942 ** avoid unnecessary register loads. If pPrior is not NULL, then it is
943 ** a pointer to a different index for which an index key has just been
944 ** computed into register regPrior. If the current pIdx index is generating
945 ** its key into the same sequence of registers and if pPrior and pIdx share
946 ** a column in common, then the register corresponding to that column already
947 ** holds the correct value and the loading of that register is skipped.
948 ** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK
949 ** on a table with multiple indices, and especially with the ROWID or
950 ** PRIMARY KEY columns of the index.
952 int sqlite3GenerateIndexKey(
953 Parse
*pParse
, /* Parsing context */
954 Index
*pIdx
, /* The index for which to generate a key */
955 int iDataCur
, /* Cursor number from which to take column data */
956 int regOut
, /* Put the new key into this register if not 0 */
957 int prefixOnly
, /* Compute only a unique prefix of the key */
958 int *piPartIdxLabel
, /* OUT: Jump to this label to skip partial index */
959 Index
*pPrior
, /* Previously generated index key */
960 int regPrior
/* Register holding previous generated key */
962 Vdbe
*v
= pParse
->pVdbe
;
967 if( piPartIdxLabel
){
968 if( pIdx
->pPartIdxWhere
){
969 *piPartIdxLabel
= sqlite3VdbeMakeLabel(pParse
);
970 pParse
->iSelfTab
= iDataCur
+ 1;
971 sqlite3ExprIfFalseDup(pParse
, pIdx
->pPartIdxWhere
, *piPartIdxLabel
,
973 pParse
->iSelfTab
= 0;
974 pPrior
= 0; /* Ticket a9efb42811fa41ee 2019-11-02;
975 ** pPartIdxWhere may have corrupted regPrior registers */
980 nCol
= (prefixOnly
&& pIdx
->uniqNotNull
) ? pIdx
->nKeyCol
: pIdx
->nColumn
;
981 regBase
= sqlite3GetTempRange(pParse
, nCol
);
982 if( pPrior
&& (regBase
!=regPrior
|| pPrior
->pPartIdxWhere
) ) pPrior
= 0;
983 for(j
=0; j
<nCol
; j
++){
985 && pPrior
->aiColumn
[j
]==pIdx
->aiColumn
[j
]
986 && pPrior
->aiColumn
[j
]!=XN_EXPR
988 /* This column was already computed by the previous index */
991 sqlite3ExprCodeLoadIndexColumn(pParse
, pIdx
, iDataCur
, j
, regBase
+j
);
992 if( pIdx
->aiColumn
[j
]>=0 ){
993 /* If the column affinity is REAL but the number is an integer, then it
994 ** might be stored in the table as an integer (using a compact
995 ** representation) then converted to REAL by an OP_RealAffinity opcode.
996 ** But we are getting ready to store this value back into an index, where
997 ** it should be converted by to INTEGER again. So omit the
998 ** OP_RealAffinity opcode if it is present */
999 sqlite3VdbeDeletePriorOpcode(v
, OP_RealAffinity
);
1003 sqlite3VdbeAddOp3(v
, OP_MakeRecord
, regBase
, nCol
, regOut
);
1005 sqlite3ReleaseTempRange(pParse
, regBase
, nCol
);
1010 ** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
1011 ** because it was a partial index, then this routine should be called to
1012 ** resolve that label.
1014 void sqlite3ResolvePartIdxLabel(Parse
*pParse
, int iLabel
){
1016 sqlite3VdbeResolveLabel(pParse
->pVdbe
, iLabel
);