000001 /*
000002 ** 2001 September 15
000003 **
000004 ** The author disclaims copyright to this source code. In place of
000005 ** a legal notice, here is a blessing:
000006 **
000007 ** May you do good and not evil.
000008 ** May you find forgiveness for yourself and forgive others.
000009 ** May you share freely, never taking more than you give.
000010 **
000011 *************************************************************************
000012 ** This file contains C code routines that are called by the parser
000013 ** in order to generate code for DELETE FROM statements.
000014 */
000015 #include "sqliteInt.h"
000016
000017 /*
000018 ** While a SrcList can in general represent multiple tables and subqueries
000019 ** (as in the FROM clause of a SELECT statement) in this case it contains
000020 ** the name of a single table, as one might find in an INSERT, DELETE,
000021 ** or UPDATE statement. Look up that table in the symbol table and
000022 ** return a pointer. Set an error message and return NULL if the table
000023 ** name is not found or if any other error occurs.
000024 **
000025 ** The following fields are initialized appropriate in pSrc:
000026 **
000027 ** pSrc->a[0].spTab Pointer to the Table object
000028 ** pSrc->a[0].u2.pIBIndex Pointer to the INDEXED BY index, if there is one
000029 **
000030 */
000031 Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
000032 SrcItem *pItem = pSrc->a;
000033 Table *pTab;
000034 assert( pItem && pSrc->nSrc>=1 );
000035 pTab = sqlite3LocateTableItem(pParse, 0, pItem);
000036 if( pItem->pSTab ) sqlite3DeleteTable(pParse->db, pItem->pSTab);
000037 pItem->pSTab = pTab;
000038 pItem->fg.notCte = 1;
000039 if( pTab ){
000040 pTab->nTabRef++;
000041 if( pItem->fg.isIndexedBy && sqlite3IndexedByLookup(pParse, pItem) ){
000042 pTab = 0;
000043 }
000044 }
000045 return pTab;
000046 }
000047
000048 /* Generate byte-code that will report the number of rows modified
000049 ** by a DELETE, INSERT, or UPDATE statement.
000050 */
000051 void sqlite3CodeChangeCount(Vdbe *v, int regCounter, const char *zColName){
000052 sqlite3VdbeAddOp0(v, OP_FkCheck);
000053 sqlite3VdbeAddOp2(v, OP_ResultRow, regCounter, 1);
000054 sqlite3VdbeSetNumCols(v, 1);
000055 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zColName, SQLITE_STATIC);
000056 }
000057
000058 /* Return true if table pTab is read-only.
000059 **
000060 ** A table is read-only if any of the following are true:
000061 **
000062 ** 1) It is a virtual table and no implementation of the xUpdate method
000063 ** has been provided
000064 **
000065 ** 2) A trigger is currently being coded and the table is a virtual table
000066 ** that is SQLITE_VTAB_DIRECTONLY or if PRAGMA trusted_schema=OFF and
000067 ** the table is not SQLITE_VTAB_INNOCUOUS.
000068 **
000069 ** 3) It is a system table (i.e. sqlite_schema), this call is not
000070 ** part of a nested parse and writable_schema pragma has not
000071 ** been specified
000072 **
000073 ** 4) The table is a shadow table, the database connection is in
000074 ** defensive mode, and the current sqlite3_prepare()
000075 ** is for a top-level SQL statement.
000076 */
000077 static int vtabIsReadOnly(Parse *pParse, Table *pTab){
000078 assert( IsVirtual(pTab) );
000079 if( sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 ){
000080 return 1;
000081 }
000082
000083 /* Within triggers:
000084 ** * Do not allow DELETE, INSERT, or UPDATE of SQLITE_VTAB_DIRECTONLY
000085 ** virtual tables
000086 ** * Only allow DELETE, INSERT, or UPDATE of non-SQLITE_VTAB_INNOCUOUS
000087 ** virtual tables if PRAGMA trusted_schema=ON.
000088 */
000089 if( pParse->pToplevel!=0
000090 && pTab->u.vtab.p->eVtabRisk >
000091 ((pParse->db->flags & SQLITE_TrustedSchema)!=0)
000092 ){
000093 sqlite3ErrorMsg(pParse, "unsafe use of virtual table \"%s\"",
000094 pTab->zName);
000095 }
000096 return 0;
000097 }
000098 static int tabIsReadOnly(Parse *pParse, Table *pTab){
000099 sqlite3 *db;
000100 if( IsVirtual(pTab) ){
000101 return vtabIsReadOnly(pParse, pTab);
000102 }
000103 if( (pTab->tabFlags & (TF_Readonly|TF_Shadow))==0 ) return 0;
000104 db = pParse->db;
000105 if( (pTab->tabFlags & TF_Readonly)!=0 ){
000106 return sqlite3WritableSchema(db)==0 && pParse->nested==0;
000107 }
000108 assert( pTab->tabFlags & TF_Shadow );
000109 return sqlite3ReadOnlyShadowTables(db);
000110 }
000111
000112 /*
000113 ** Check to make sure the given table is writable.
000114 **
000115 ** If pTab is not writable -> generate an error message and return 1.
000116 ** If pTab is writable but other errors have occurred -> return 1.
000117 ** If pTab is writable and no prior errors -> return 0;
000118 */
000119 int sqlite3IsReadOnly(Parse *pParse, Table *pTab, Trigger *pTrigger){
000120 if( tabIsReadOnly(pParse, pTab) ){
000121 sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
000122 return 1;
000123 }
000124 #ifndef SQLITE_OMIT_VIEW
000125 if( IsView(pTab)
000126 && (pTrigger==0 || (pTrigger->bReturning && pTrigger->pNext==0))
000127 ){
000128 sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
000129 return 1;
000130 }
000131 #endif
000132 return 0;
000133 }
000134
000135
000136 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
000137 /*
000138 ** Evaluate a view and store its result in an ephemeral table. The
000139 ** pWhere argument is an optional WHERE clause that restricts the
000140 ** set of rows in the view that are to be added to the ephemeral table.
000141 */
000142 void sqlite3MaterializeView(
000143 Parse *pParse, /* Parsing context */
000144 Table *pView, /* View definition */
000145 Expr *pWhere, /* Optional WHERE clause to be added */
000146 ExprList *pOrderBy, /* Optional ORDER BY clause */
000147 Expr *pLimit, /* Optional LIMIT clause */
000148 int iCur /* Cursor number for ephemeral table */
000149 ){
000150 SelectDest dest;
000151 Select *pSel;
000152 SrcList *pFrom;
000153 sqlite3 *db = pParse->db;
000154 int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
000155 pWhere = sqlite3ExprDup(db, pWhere, 0);
000156 pFrom = sqlite3SrcListAppend(pParse, 0, 0, 0);
000157 if( pFrom ){
000158 assert( pFrom->nSrc==1 );
000159 pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
000160 assert( pFrom->a[0].fg.fixedSchema==0 && pFrom->a[0].fg.isSubquery==0 );
000161 pFrom->a[0].u4.zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zDbSName);
000162 assert( pFrom->a[0].fg.isUsing==0 );
000163 assert( pFrom->a[0].u3.pOn==0 );
000164 }
000165 pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, pOrderBy,
000166 SF_IncludeHidden, pLimit);
000167 sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
000168 sqlite3Select(pParse, pSel, &dest);
000169 sqlite3SelectDelete(db, pSel);
000170 }
000171 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
000172
000173 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
000174 /*
000175 ** Generate an expression tree to implement the WHERE, ORDER BY,
000176 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
000177 **
000178 ** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
000179 ** \__________________________/
000180 ** pLimitWhere (pInClause)
000181 */
000182 Expr *sqlite3LimitWhere(
000183 Parse *pParse, /* The parser context */
000184 SrcList *pSrc, /* the FROM clause -- which tables to scan */
000185 Expr *pWhere, /* The WHERE clause. May be null */
000186 ExprList *pOrderBy, /* The ORDER BY clause. May be null */
000187 Expr *pLimit, /* The LIMIT clause. May be null */
000188 char *zStmtType /* Either DELETE or UPDATE. For err msgs. */
000189 ){
000190 sqlite3 *db = pParse->db;
000191 Expr *pLhs = NULL; /* LHS of IN(SELECT...) operator */
000192 Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */
000193 ExprList *pEList = NULL; /* Expression list containing only pSelectRowid*/
000194 SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */
000195 Select *pSelect = NULL; /* Complete SELECT tree */
000196 Table *pTab;
000197
000198 /* Check that there isn't an ORDER BY without a LIMIT clause.
000199 */
000200 if( pOrderBy && pLimit==0 ) {
000201 sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
000202 sqlite3ExprDelete(pParse->db, pWhere);
000203 sqlite3ExprListDelete(pParse->db, pOrderBy);
000204 return 0;
000205 }
000206
000207 /* We only need to generate a select expression if there
000208 ** is a limit/offset term to enforce.
000209 */
000210 if( pLimit == 0 ) {
000211 return pWhere;
000212 }
000213
000214 /* Generate a select expression tree to enforce the limit/offset
000215 ** term for the DELETE or UPDATE statement. For example:
000216 ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
000217 ** becomes:
000218 ** DELETE FROM table_a WHERE rowid IN (
000219 ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
000220 ** );
000221 */
000222
000223 pTab = pSrc->a[0].pSTab;
000224 if( HasRowid(pTab) ){
000225 pLhs = sqlite3PExpr(pParse, TK_ROW, 0, 0);
000226 pEList = sqlite3ExprListAppend(
000227 pParse, 0, sqlite3PExpr(pParse, TK_ROW, 0, 0)
000228 );
000229 }else{
000230 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
000231 assert( pPk!=0 );
000232 assert( pPk->nKeyCol>=1 );
000233 if( pPk->nKeyCol==1 ){
000234 const char *zName;
000235 assert( pPk->aiColumn[0]>=0 && pPk->aiColumn[0]<pTab->nCol );
000236 zName = pTab->aCol[pPk->aiColumn[0]].zCnName;
000237 pLhs = sqlite3Expr(db, TK_ID, zName);
000238 pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, zName));
000239 }else{
000240 int i;
000241 for(i=0; i<pPk->nKeyCol; i++){
000242 Expr *p;
000243 assert( pPk->aiColumn[i]>=0 && pPk->aiColumn[i]<pTab->nCol );
000244 p = sqlite3Expr(db, TK_ID, pTab->aCol[pPk->aiColumn[i]].zCnName);
000245 pEList = sqlite3ExprListAppend(pParse, pEList, p);
000246 }
000247 pLhs = sqlite3PExpr(pParse, TK_VECTOR, 0, 0);
000248 if( pLhs ){
000249 pLhs->x.pList = sqlite3ExprListDup(db, pEList, 0);
000250 }
000251 }
000252 }
000253
000254 /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
000255 ** and the SELECT subtree. */
000256 pSrc->a[0].pSTab = 0;
000257 pSelectSrc = sqlite3SrcListDup(db, pSrc, 0);
000258 pSrc->a[0].pSTab = pTab;
000259 if( pSrc->a[0].fg.isIndexedBy ){
000260 assert( pSrc->a[0].fg.isCte==0 );
000261 pSrc->a[0].u2.pIBIndex = 0;
000262 pSrc->a[0].fg.isIndexedBy = 0;
000263 sqlite3DbFree(db, pSrc->a[0].u1.zIndexedBy);
000264 }else if( pSrc->a[0].fg.isCte ){
000265 pSrc->a[0].u2.pCteUse->nUse++;
000266 }
000267
000268 /* generate the SELECT expression tree. */
000269 pSelect = sqlite3SelectNew(pParse, pEList, pSelectSrc, pWhere, 0 ,0,
000270 pOrderBy,0,pLimit
000271 );
000272
000273 /* now generate the new WHERE rowid IN clause for the DELETE/UPDATE */
000274 pInClause = sqlite3PExpr(pParse, TK_IN, pLhs, 0);
000275 sqlite3PExprAddSelect(pParse, pInClause, pSelect);
000276 return pInClause;
000277 }
000278 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */
000279 /* && !defined(SQLITE_OMIT_SUBQUERY) */
000280
000281 /*
000282 ** Generate code for a DELETE FROM statement.
000283 **
000284 ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
000285 ** \________/ \________________/
000286 ** pTabList pWhere
000287 */
000288 void sqlite3DeleteFrom(
000289 Parse *pParse, /* The parser context */
000290 SrcList *pTabList, /* The table from which we should delete things */
000291 Expr *pWhere, /* The WHERE clause. May be null */
000292 ExprList *pOrderBy, /* ORDER BY clause. May be null */
000293 Expr *pLimit /* LIMIT clause. May be null */
000294 ){
000295 Vdbe *v; /* The virtual database engine */
000296 Table *pTab; /* The table from which records will be deleted */
000297 int i; /* Loop counter */
000298 WhereInfo *pWInfo; /* Information about the WHERE clause */
000299 Index *pIdx; /* For looping over indices of the table */
000300 int iTabCur; /* Cursor number for the table */
000301 int iDataCur = 0; /* VDBE cursor for the canonical data source */
000302 int iIdxCur = 0; /* Cursor number of the first index */
000303 int nIdx; /* Number of indices */
000304 sqlite3 *db; /* Main database structure */
000305 AuthContext sContext; /* Authorization context */
000306 NameContext sNC; /* Name context to resolve expressions in */
000307 int iDb; /* Database number */
000308 int memCnt = 0; /* Memory cell used for change counting */
000309 int rcauth; /* Value returned by authorization callback */
000310 int eOnePass; /* ONEPASS_OFF or _SINGLE or _MULTI */
000311 int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
000312 u8 *aToOpen = 0; /* Open cursor iTabCur+j if aToOpen[j] is true */
000313 Index *pPk; /* The PRIMARY KEY index on the table */
000314 int iPk = 0; /* First of nPk registers holding PRIMARY KEY value */
000315 i16 nPk = 1; /* Number of columns in the PRIMARY KEY */
000316 int iKey; /* Memory cell holding key of row to be deleted */
000317 i16 nKey; /* Number of memory cells in the row key */
000318 int iEphCur = 0; /* Ephemeral table holding all primary key values */
000319 int iRowSet = 0; /* Register for rowset of rows to delete */
000320 int addrBypass = 0; /* Address of jump over the delete logic */
000321 int addrLoop = 0; /* Top of the delete loop */
000322 int addrEphOpen = 0; /* Instruction to open the Ephemeral table */
000323 int bComplex; /* True if there are triggers or FKs or
000324 ** subqueries in the WHERE clause */
000325
000326 #ifndef SQLITE_OMIT_TRIGGER
000327 int isView; /* True if attempting to delete from a view */
000328 Trigger *pTrigger; /* List of table triggers, if required */
000329 #endif
000330
000331 memset(&sContext, 0, sizeof(sContext));
000332 db = pParse->db;
000333 assert( db->pParse==pParse );
000334 if( pParse->nErr ){
000335 goto delete_from_cleanup;
000336 }
000337 assert( db->mallocFailed==0 );
000338 assert( pTabList->nSrc==1 );
000339
000340 /* Locate the table which we want to delete. This table has to be
000341 ** put in an SrcList structure because some of the subroutines we
000342 ** will be calling are designed to work with multiple tables and expect
000343 ** an SrcList* parameter instead of just a Table* parameter.
000344 */
000345 pTab = sqlite3SrcListLookup(pParse, pTabList);
000346 if( pTab==0 ) goto delete_from_cleanup;
000347
000348 /* Figure out if we have any triggers and if the table being
000349 ** deleted from is a view
000350 */
000351 #ifndef SQLITE_OMIT_TRIGGER
000352 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
000353 isView = IsView(pTab);
000354 #else
000355 # define pTrigger 0
000356 # define isView 0
000357 #endif
000358 bComplex = pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0);
000359 #ifdef SQLITE_OMIT_VIEW
000360 # undef isView
000361 # define isView 0
000362 #endif
000363
000364 #if TREETRACE_ENABLED
000365 if( sqlite3TreeTrace & 0x10000 ){
000366 sqlite3TreeViewLine(0, "In sqlite3Delete() at %s:%d", __FILE__, __LINE__);
000367 sqlite3TreeViewDelete(pParse->pWith, pTabList, pWhere,
000368 pOrderBy, pLimit, pTrigger);
000369 }
000370 #endif
000371
000372 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
000373 if( !isView ){
000374 pWhere = sqlite3LimitWhere(
000375 pParse, pTabList, pWhere, pOrderBy, pLimit, "DELETE"
000376 );
000377 pOrderBy = 0;
000378 pLimit = 0;
000379 }
000380 #endif
000381
000382 /* If pTab is really a view, make sure it has been initialized.
000383 */
000384 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
000385 goto delete_from_cleanup;
000386 }
000387
000388 if( sqlite3IsReadOnly(pParse, pTab, pTrigger) ){
000389 goto delete_from_cleanup;
000390 }
000391 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
000392 assert( iDb<db->nDb );
000393 rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0,
000394 db->aDb[iDb].zDbSName);
000395 assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
000396 if( rcauth==SQLITE_DENY ){
000397 goto delete_from_cleanup;
000398 }
000399 assert(!isView || pTrigger);
000400
000401 /* Assign cursor numbers to the table and all its indices.
000402 */
000403 assert( pTabList->nSrc==1 );
000404 iTabCur = pTabList->a[0].iCursor = pParse->nTab++;
000405 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
000406 pParse->nTab++;
000407 }
000408
000409 /* Start the view context
000410 */
000411 if( isView ){
000412 sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
000413 }
000414
000415 /* Begin generating code.
000416 */
000417 v = sqlite3GetVdbe(pParse);
000418 if( v==0 ){
000419 goto delete_from_cleanup;
000420 }
000421 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
000422 sqlite3BeginWriteOperation(pParse, bComplex, iDb);
000423
000424 /* If we are trying to delete from a view, realize that view into
000425 ** an ephemeral table.
000426 */
000427 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
000428 if( isView ){
000429 sqlite3MaterializeView(pParse, pTab,
000430 pWhere, pOrderBy, pLimit, iTabCur
000431 );
000432 iDataCur = iIdxCur = iTabCur;
000433 pOrderBy = 0;
000434 pLimit = 0;
000435 }
000436 #endif
000437
000438 /* Resolve the column names in the WHERE clause.
000439 */
000440 memset(&sNC, 0, sizeof(sNC));
000441 sNC.pParse = pParse;
000442 sNC.pSrcList = pTabList;
000443 if( sqlite3ResolveExprNames(&sNC, pWhere) ){
000444 goto delete_from_cleanup;
000445 }
000446
000447 /* Initialize the counter of the number of rows deleted, if
000448 ** we are counting rows.
000449 */
000450 if( (db->flags & SQLITE_CountRows)!=0
000451 && !pParse->nested
000452 && !pParse->pTriggerTab
000453 && !pParse->bReturning
000454 ){
000455 memCnt = ++pParse->nMem;
000456 sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
000457 }
000458
000459 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
000460 /* Special case: A DELETE without a WHERE clause deletes everything.
000461 ** It is easier just to erase the whole table. Prior to version 3.6.5,
000462 ** this optimization caused the row change count (the value returned by
000463 ** API function sqlite3_count_changes) to be set incorrectly.
000464 **
000465 ** The "rcauth==SQLITE_OK" terms is the
000466 ** IMPLEMENTATION-OF: R-17228-37124 If the action code is SQLITE_DELETE and
000467 ** the callback returns SQLITE_IGNORE then the DELETE operation proceeds but
000468 ** the truncate optimization is disabled and all rows are deleted
000469 ** individually.
000470 */
000471 if( rcauth==SQLITE_OK
000472 && pWhere==0
000473 && !bComplex
000474 && !IsVirtual(pTab)
000475 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
000476 && db->xPreUpdateCallback==0
000477 #endif
000478 ){
000479 assert( !isView );
000480 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
000481 if( HasRowid(pTab) ){
000482 sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt ? memCnt : -1,
000483 pTab->zName, P4_STATIC);
000484 }
000485 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
000486 assert( pIdx->pSchema==pTab->pSchema );
000487 if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
000488 sqlite3VdbeAddOp3(v, OP_Clear, pIdx->tnum, iDb, memCnt ? memCnt : -1);
000489 }else{
000490 sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
000491 }
000492 }
000493 }else
000494 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
000495 {
000496 u16 wcf = WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK;
000497 if( sNC.ncFlags & NC_Subquery ) bComplex = 1;
000498 wcf |= (bComplex ? 0 : WHERE_ONEPASS_MULTIROW);
000499 if( HasRowid(pTab) ){
000500 /* For a rowid table, initialize the RowSet to an empty set */
000501 pPk = 0;
000502 assert( nPk==1 );
000503 iRowSet = ++pParse->nMem;
000504 sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
000505 }else{
000506 /* For a WITHOUT ROWID table, create an ephemeral table used to
000507 ** hold all primary keys for rows to be deleted. */
000508 pPk = sqlite3PrimaryKeyIndex(pTab);
000509 assert( pPk!=0 );
000510 nPk = pPk->nKeyCol;
000511 iPk = pParse->nMem+1;
000512 pParse->nMem += nPk;
000513 iEphCur = pParse->nTab++;
000514 addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk);
000515 sqlite3VdbeSetP4KeyInfo(pParse, pPk);
000516 }
000517
000518 /* Construct a query to find the rowid or primary key for every row
000519 ** to be deleted, based on the WHERE clause. Set variable eOnePass
000520 ** to indicate the strategy used to implement this delete:
000521 **
000522 ** ONEPASS_OFF: Two-pass approach - use a FIFO for rowids/PK values.
000523 ** ONEPASS_SINGLE: One-pass approach - at most one row deleted.
000524 ** ONEPASS_MULTI: One-pass approach - any number of rows may be deleted.
000525 */
000526 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0,0,wcf,iTabCur+1);
000527 if( pWInfo==0 ) goto delete_from_cleanup;
000528 eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
000529 assert( IsVirtual(pTab)==0 || eOnePass!=ONEPASS_MULTI );
000530 assert( IsVirtual(pTab) || bComplex || eOnePass!=ONEPASS_OFF
000531 || OptimizationDisabled(db, SQLITE_OnePass) );
000532 if( eOnePass!=ONEPASS_SINGLE ) sqlite3MultiWrite(pParse);
000533 if( sqlite3WhereUsesDeferredSeek(pWInfo) ){
000534 sqlite3VdbeAddOp1(v, OP_FinishSeek, iTabCur);
000535 }
000536
000537 /* Keep track of the number of rows to be deleted */
000538 if( memCnt ){
000539 sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
000540 }
000541
000542 /* Extract the rowid or primary key for the current row */
000543 if( pPk ){
000544 for(i=0; i<nPk; i++){
000545 assert( pPk->aiColumn[i]>=0 );
000546 sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
000547 pPk->aiColumn[i], iPk+i);
000548 }
000549 iKey = iPk;
000550 }else{
000551 iKey = ++pParse->nMem;
000552 sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, -1, iKey);
000553 }
000554
000555 if( eOnePass!=ONEPASS_OFF ){
000556 /* For ONEPASS, no need to store the rowid/primary-key. There is only
000557 ** one, so just keep it in its register(s) and fall through to the
000558 ** delete code. */
000559 nKey = nPk; /* OP_Found will use an unpacked key */
000560 aToOpen = sqlite3DbMallocRawNN(db, nIdx+2);
000561 if( aToOpen==0 ){
000562 sqlite3WhereEnd(pWInfo);
000563 goto delete_from_cleanup;
000564 }
000565 memset(aToOpen, 1, nIdx+1);
000566 aToOpen[nIdx+1] = 0;
000567 if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
000568 if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
000569 if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);
000570 addrBypass = sqlite3VdbeMakeLabel(pParse);
000571 }else{
000572 if( pPk ){
000573 /* Add the PK key for this row to the temporary table */
000574 iKey = ++pParse->nMem;
000575 nKey = 0; /* Zero tells OP_Found to use a composite key */
000576 sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey,
000577 sqlite3IndexAffinityStr(pParse->db, pPk), nPk);
000578 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEphCur, iKey, iPk, nPk);
000579 }else{
000580 /* Add the rowid of the row to be deleted to the RowSet */
000581 nKey = 1; /* OP_DeferredSeek always uses a single rowid */
000582 sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);
000583 }
000584 sqlite3WhereEnd(pWInfo);
000585 }
000586
000587 /* Unless this is a view, open cursors for the table we are
000588 ** deleting from and all its indices. If this is a view, then the
000589 ** only effect this statement has is to fire the INSTEAD OF
000590 ** triggers.
000591 */
000592 if( !isView ){
000593 int iAddrOnce = 0;
000594 if( eOnePass==ONEPASS_MULTI ){
000595 iAddrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
000596 }
000597 testcase( IsVirtual(pTab) );
000598 sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, OPFLAG_FORDELETE,
000599 iTabCur, aToOpen, &iDataCur, &iIdxCur);
000600 assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur );
000601 assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 );
000602 if( eOnePass==ONEPASS_MULTI ){
000603 sqlite3VdbeJumpHereOrPopInst(v, iAddrOnce);
000604 }
000605 }
000606
000607 /* Set up a loop over the rowids/primary-keys that were found in the
000608 ** where-clause loop above.
000609 */
000610 if( eOnePass!=ONEPASS_OFF ){
000611 assert( nKey==nPk ); /* OP_Found will use an unpacked key */
000612 if( !IsVirtual(pTab) && aToOpen[iDataCur-iTabCur] ){
000613 assert( pPk!=0 || IsView(pTab) );
000614 sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);
000615 VdbeCoverage(v);
000616 }
000617 }else if( pPk ){
000618 addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v);
000619 if( IsVirtual(pTab) ){
000620 sqlite3VdbeAddOp3(v, OP_Column, iEphCur, 0, iKey);
000621 }else{
000622 sqlite3VdbeAddOp2(v, OP_RowData, iEphCur, iKey);
000623 }
000624 assert( nKey==0 ); /* OP_Found will use a composite key */
000625 }else{
000626 addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);
000627 VdbeCoverage(v);
000628 assert( nKey==1 );
000629 }
000630
000631 /* Delete the row */
000632 #ifndef SQLITE_OMIT_VIRTUALTABLE
000633 if( IsVirtual(pTab) ){
000634 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
000635 sqlite3VtabMakeWritable(pParse, pTab);
000636 assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );
000637 sqlite3MayAbort(pParse);
000638 if( eOnePass==ONEPASS_SINGLE ){
000639 sqlite3VdbeAddOp1(v, OP_Close, iTabCur);
000640 if( sqlite3IsToplevel(pParse) ){
000641 pParse->isMultiWrite = 0;
000642 }
000643 }
000644 sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
000645 sqlite3VdbeChangeP5(v, OE_Abort);
000646 }else
000647 #endif
000648 {
000649 int count = (pParse->nested==0); /* True to count changes */
000650 sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
000651 iKey, nKey, count, OE_Default, eOnePass, aiCurOnePass[1]);
000652 }
000653
000654 /* End of the loop over all rowids/primary-keys. */
000655 if( eOnePass!=ONEPASS_OFF ){
000656 sqlite3VdbeResolveLabel(v, addrBypass);
000657 sqlite3WhereEnd(pWInfo);
000658 }else if( pPk ){
000659 sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v);
000660 sqlite3VdbeJumpHere(v, addrLoop);
000661 }else{
000662 sqlite3VdbeGoto(v, addrLoop);
000663 sqlite3VdbeJumpHere(v, addrLoop);
000664 }
000665 } /* End non-truncate path */
000666
000667 /* Update the sqlite_sequence table by storing the content of the
000668 ** maximum rowid counter values recorded while inserting into
000669 ** autoincrement tables.
000670 */
000671 if( pParse->nested==0 && pParse->pTriggerTab==0 ){
000672 sqlite3AutoincrementEnd(pParse);
000673 }
000674
000675 /* Return the number of rows that were deleted. If this routine is
000676 ** generating code because of a call to sqlite3NestedParse(), do not
000677 ** invoke the callback function.
000678 */
000679 if( memCnt ){
000680 sqlite3CodeChangeCount(v, memCnt, "rows deleted");
000681 }
000682
000683 delete_from_cleanup:
000684 sqlite3AuthContextPop(&sContext);
000685 sqlite3SrcListDelete(db, pTabList);
000686 sqlite3ExprDelete(db, pWhere);
000687 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
000688 sqlite3ExprListDelete(db, pOrderBy);
000689 sqlite3ExprDelete(db, pLimit);
000690 #endif
000691 if( aToOpen ) sqlite3DbNNFreeNN(db, aToOpen);
000692 return;
000693 }
000694 /* Make sure "isView" and other macros defined above are undefined. Otherwise
000695 ** they may interfere with compilation of other functions in this file
000696 ** (or in another file, if this file becomes part of the amalgamation). */
000697 #ifdef isView
000698 #undef isView
000699 #endif
000700 #ifdef pTrigger
000701 #undef pTrigger
000702 #endif
000703
000704 /*
000705 ** This routine generates VDBE code that causes a single row of a
000706 ** single table to be deleted. Both the original table entry and
000707 ** all indices are removed.
000708 **
000709 ** Preconditions:
000710 **
000711 ** 1. iDataCur is an open cursor on the btree that is the canonical data
000712 ** store for the table. (This will be either the table itself,
000713 ** in the case of a rowid table, or the PRIMARY KEY index in the case
000714 ** of a WITHOUT ROWID table.)
000715 **
000716 ** 2. Read/write cursors for all indices of pTab must be open as
000717 ** cursor number iIdxCur+i for the i-th index.
000718 **
000719 ** 3. The primary key for the row to be deleted must be stored in a
000720 ** sequence of nPk memory cells starting at iPk. If nPk==0 that means
000721 ** that a search record formed from OP_MakeRecord is contained in the
000722 ** single memory location iPk.
000723 **
000724 ** eMode:
000725 ** Parameter eMode may be passed either ONEPASS_OFF (0), ONEPASS_SINGLE, or
000726 ** ONEPASS_MULTI. If eMode is not ONEPASS_OFF, then the cursor
000727 ** iDataCur already points to the row to delete. If eMode is ONEPASS_OFF
000728 ** then this function must seek iDataCur to the entry identified by iPk
000729 ** and nPk before reading from it.
000730 **
000731 ** If eMode is ONEPASS_MULTI, then this call is being made as part
000732 ** of a ONEPASS delete that affects multiple rows. In this case, if
000733 ** iIdxNoSeek is a valid cursor number (>=0) and is not the same as
000734 ** iDataCur, then its position should be preserved following the delete
000735 ** operation. Or, if iIdxNoSeek is not a valid cursor number, the
000736 ** position of iDataCur should be preserved instead.
000737 **
000738 ** iIdxNoSeek:
000739 ** If iIdxNoSeek is a valid cursor number (>=0) not equal to iDataCur,
000740 ** then it identifies an index cursor (from within array of cursors
000741 ** starting at iIdxCur) that already points to the index entry to be deleted.
000742 ** Except, this optimization is disabled if there are BEFORE triggers since
000743 ** the trigger body might have moved the cursor.
000744 */
000745 void sqlite3GenerateRowDelete(
000746 Parse *pParse, /* Parsing context */
000747 Table *pTab, /* Table containing the row to be deleted */
000748 Trigger *pTrigger, /* List of triggers to (potentially) fire */
000749 int iDataCur, /* Cursor from which column data is extracted */
000750 int iIdxCur, /* First index cursor */
000751 int iPk, /* First memory cell containing the PRIMARY KEY */
000752 i16 nPk, /* Number of PRIMARY KEY memory cells */
000753 u8 count, /* If non-zero, increment the row change counter */
000754 u8 onconf, /* Default ON CONFLICT policy for triggers */
000755 u8 eMode, /* ONEPASS_OFF, _SINGLE, or _MULTI. See above */
000756 int iIdxNoSeek /* Cursor number of cursor that does not need seeking */
000757 ){
000758 Vdbe *v = pParse->pVdbe; /* Vdbe */
000759 int iOld = 0; /* First register in OLD.* array */
000760 int iLabel; /* Label resolved to end of generated code */
000761 u8 opSeek; /* Seek opcode */
000762
000763 /* Vdbe is guaranteed to have been allocated by this stage. */
000764 assert( v );
000765 VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)",
000766 iDataCur, iIdxCur, iPk, (int)nPk));
000767
000768 /* Seek cursor iCur to the row to delete. If this row no longer exists
000769 ** (this can happen if a trigger program has already deleted it), do
000770 ** not attempt to delete it or fire any DELETE triggers. */
000771 iLabel = sqlite3VdbeMakeLabel(pParse);
000772 opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
000773 if( eMode==ONEPASS_OFF ){
000774 sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
000775 VdbeCoverageIf(v, opSeek==OP_NotExists);
000776 VdbeCoverageIf(v, opSeek==OP_NotFound);
000777 }
000778
000779 /* If there are any triggers to fire, allocate a range of registers to
000780 ** use for the old.* references in the triggers. */
000781 if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
000782 u32 mask; /* Mask of OLD.* columns in use */
000783 int iCol; /* Iterator used while populating OLD.* */
000784 int addrStart; /* Start of BEFORE trigger programs */
000785
000786 /* TODO: Could use temporary registers here. Also could attempt to
000787 ** avoid copying the contents of the rowid register. */
000788 mask = sqlite3TriggerColmask(
000789 pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
000790 );
000791 mask |= sqlite3FkOldmask(pParse, pTab);
000792 iOld = pParse->nMem+1;
000793 pParse->nMem += (1 + pTab->nCol);
000794
000795 /* Populate the OLD.* pseudo-table register array. These values will be
000796 ** used by any BEFORE and AFTER triggers that exist. */
000797 sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);
000798 for(iCol=0; iCol<pTab->nCol; iCol++){
000799 testcase( mask!=0xffffffff && iCol==31 );
000800 testcase( mask!=0xffffffff && iCol==32 );
000801 if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){
000802 int kk = sqlite3TableColumnToStorage(pTab, iCol);
000803 sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+kk+1);
000804 }
000805 }
000806
000807 /* Invoke BEFORE DELETE trigger programs. */
000808 addrStart = sqlite3VdbeCurrentAddr(v);
000809 sqlite3CodeRowTrigger(pParse, pTrigger,
000810 TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
000811 );
000812
000813 /* If any BEFORE triggers were coded, then seek the cursor to the
000814 ** row to be deleted again. It may be that the BEFORE triggers moved
000815 ** the cursor or already deleted the row that the cursor was
000816 ** pointing to.
000817 **
000818 ** Also disable the iIdxNoSeek optimization since the BEFORE trigger
000819 ** may have moved that cursor.
000820 */
000821 if( addrStart<sqlite3VdbeCurrentAddr(v) ){
000822 sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
000823 VdbeCoverageIf(v, opSeek==OP_NotExists);
000824 VdbeCoverageIf(v, opSeek==OP_NotFound);
000825 testcase( iIdxNoSeek>=0 );
000826 iIdxNoSeek = -1;
000827 }
000828
000829 /* Do FK processing. This call checks that any FK constraints that
000830 ** refer to this table (i.e. constraints attached to other tables)
000831 ** are not violated by deleting this row. */
000832 sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
000833 }
000834
000835 /* Delete the index and table entries. Skip this step if pTab is really
000836 ** a view (in which case the only effect of the DELETE statement is to
000837 ** fire the INSTEAD OF triggers).
000838 **
000839 ** If variable 'count' is non-zero, then this OP_Delete instruction should
000840 ** invoke the update-hook. The pre-update-hook, on the other hand should
000841 ** be invoked unless table pTab is a system table. The difference is that
000842 ** the update-hook is not invoked for rows removed by REPLACE, but the
000843 ** pre-update-hook is.
000844 */
000845 if( !IsView(pTab) ){
000846 u8 p5 = 0;
000847 sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,iIdxNoSeek);
000848 sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
000849 if( pParse->nested==0 || 0==sqlite3_stricmp(pTab->zName, "sqlite_stat1") ){
000850 sqlite3VdbeAppendP4(v, (char*)pTab, P4_TABLE);
000851 }
000852 if( eMode!=ONEPASS_OFF ){
000853 sqlite3VdbeChangeP5(v, OPFLAG_AUXDELETE);
000854 }
000855 if( iIdxNoSeek>=0 && iIdxNoSeek!=iDataCur ){
000856 sqlite3VdbeAddOp1(v, OP_Delete, iIdxNoSeek);
000857 }
000858 if( eMode==ONEPASS_MULTI ) p5 |= OPFLAG_SAVEPOSITION;
000859 sqlite3VdbeChangeP5(v, p5);
000860 }
000861
000862 /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
000863 ** handle rows (possibly in other tables) that refer via a foreign key
000864 ** to the row just deleted. */
000865 sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
000866
000867 /* Invoke AFTER DELETE trigger programs. */
000868 if( pTrigger ){
000869 sqlite3CodeRowTrigger(pParse, pTrigger,
000870 TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
000871 );
000872 }
000873
000874 /* Jump here if the row had already been deleted before any BEFORE
000875 ** trigger programs were invoked. Or if a trigger program throws a
000876 ** RAISE(IGNORE) exception. */
000877 sqlite3VdbeResolveLabel(v, iLabel);
000878 VdbeModuleComment((v, "END: GenRowDel()"));
000879 }
000880
000881 /*
000882 ** This routine generates VDBE code that causes the deletion of all
000883 ** index entries associated with a single row of a single table, pTab
000884 **
000885 ** Preconditions:
000886 **
000887 ** 1. A read/write cursor "iDataCur" must be open on the canonical storage
000888 ** btree for the table pTab. (This will be either the table itself
000889 ** for rowid tables or to the primary key index for WITHOUT ROWID
000890 ** tables.)
000891 **
000892 ** 2. Read/write cursors for all indices of pTab must be open as
000893 ** cursor number iIdxCur+i for the i-th index. (The pTab->pIndex
000894 ** index is the 0-th index.)
000895 **
000896 ** 3. The "iDataCur" cursor must be already be positioned on the row
000897 ** that is to be deleted.
000898 */
000899 void sqlite3GenerateRowIndexDelete(
000900 Parse *pParse, /* Parsing and code generating context */
000901 Table *pTab, /* Table containing the row to be deleted */
000902 int iDataCur, /* Cursor of table holding data. */
000903 int iIdxCur, /* First index cursor */
000904 int *aRegIdx, /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
000905 int iIdxNoSeek /* Do not delete from this cursor */
000906 ){
000907 int i; /* Index loop counter */
000908 int r1 = -1; /* Register holding an index key */
000909 int iPartIdxLabel; /* Jump destination for skipping partial index entries */
000910 Index *pIdx; /* Current index */
000911 Index *pPrior = 0; /* Prior index */
000912 Vdbe *v; /* The prepared statement under construction */
000913 Index *pPk; /* PRIMARY KEY index, or NULL for rowid tables */
000914
000915 v = pParse->pVdbe;
000916 pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
000917 for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
000918 assert( iIdxCur+i!=iDataCur || pPk==pIdx );
000919 if( aRegIdx!=0 && aRegIdx[i]==0 ) continue;
000920 if( pIdx==pPk ) continue;
000921 if( iIdxCur+i==iIdxNoSeek ) continue;
000922 VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
000923 r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,
000924 &iPartIdxLabel, pPrior, r1);
000925 sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
000926 pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
000927 sqlite3VdbeChangeP5(v, 1); /* Cause IdxDelete to error if no entry found */
000928 sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
000929 pPrior = pIdx;
000930 }
000931 }
000932
000933 /*
000934 ** Generate code that will assemble an index key and stores it in register
000935 ** regOut. The key with be for index pIdx which is an index on pTab.
000936 ** iCur is the index of a cursor open on the pTab table and pointing to
000937 ** the entry that needs indexing. If pTab is a WITHOUT ROWID table, then
000938 ** iCur must be the cursor of the PRIMARY KEY index.
000939 **
000940 ** Return a register number which is the first in a block of
000941 ** registers that holds the elements of the index key. The
000942 ** block of registers has already been deallocated by the time
000943 ** this routine returns.
000944 **
000945 ** If *piPartIdxLabel is not NULL, fill it in with a label and jump
000946 ** to that label if pIdx is a partial index that should be skipped.
000947 ** The label should be resolved using sqlite3ResolvePartIdxLabel().
000948 ** A partial index should be skipped if its WHERE clause evaluates
000949 ** to false or null. If pIdx is not a partial index, *piPartIdxLabel
000950 ** will be set to zero which is an empty label that is ignored by
000951 ** sqlite3ResolvePartIdxLabel().
000952 **
000953 ** The pPrior and regPrior parameters are used to implement a cache to
000954 ** avoid unnecessary register loads. If pPrior is not NULL, then it is
000955 ** a pointer to a different index for which an index key has just been
000956 ** computed into register regPrior. If the current pIdx index is generating
000957 ** its key into the same sequence of registers and if pPrior and pIdx share
000958 ** a column in common, then the register corresponding to that column already
000959 ** holds the correct value and the loading of that register is skipped.
000960 ** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK
000961 ** on a table with multiple indices, and especially with the ROWID or
000962 ** PRIMARY KEY columns of the index.
000963 */
000964 int sqlite3GenerateIndexKey(
000965 Parse *pParse, /* Parsing context */
000966 Index *pIdx, /* The index for which to generate a key */
000967 int iDataCur, /* Cursor number from which to take column data */
000968 int regOut, /* Put the new key into this register if not 0 */
000969 int prefixOnly, /* Compute only a unique prefix of the key */
000970 int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */
000971 Index *pPrior, /* Previously generated index key */
000972 int regPrior /* Register holding previous generated key */
000973 ){
000974 Vdbe *v = pParse->pVdbe;
000975 int j;
000976 int regBase;
000977 int nCol;
000978
000979 if( piPartIdxLabel ){
000980 if( pIdx->pPartIdxWhere ){
000981 *piPartIdxLabel = sqlite3VdbeMakeLabel(pParse);
000982 pParse->iSelfTab = iDataCur + 1;
000983 sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
000984 SQLITE_JUMPIFNULL);
000985 pParse->iSelfTab = 0;
000986 pPrior = 0; /* Ticket a9efb42811fa41ee 2019-11-02;
000987 ** pPartIdxWhere may have corrupted regPrior registers */
000988 }else{
000989 *piPartIdxLabel = 0;
000990 }
000991 }
000992 nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
000993 regBase = sqlite3GetTempRange(pParse, nCol);
000994 if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
000995 for(j=0; j<nCol; j++){
000996 if( pPrior
000997 && pPrior->aiColumn[j]==pIdx->aiColumn[j]
000998 && pPrior->aiColumn[j]!=XN_EXPR
000999 ){
001000 /* This column was already computed by the previous index */
001001 continue;
001002 }
001003 sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iDataCur, j, regBase+j);
001004 if( pIdx->aiColumn[j]>=0 ){
001005 /* If the column affinity is REAL but the number is an integer, then it
001006 ** might be stored in the table as an integer (using a compact
001007 ** representation) then converted to REAL by an OP_RealAffinity opcode.
001008 ** But we are getting ready to store this value back into an index, where
001009 ** it should be converted by to INTEGER again. So omit the
001010 ** OP_RealAffinity opcode if it is present */
001011 sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
001012 }
001013 }
001014 if( regOut ){
001015 sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
001016 }
001017 sqlite3ReleaseTempRange(pParse, regBase, nCol);
001018 return regBase;
001019 }
001020
001021 /*
001022 ** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
001023 ** because it was a partial index, then this routine should be called to
001024 ** resolve that label.
001025 */
001026 void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){
001027 if( iLabel ){
001028 sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel);
001029 }
001030 }