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