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