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