/ Check-in [38a9327b]
Login

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:More fixes and comment updates.
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1: 38a9327bad1a01e3d7a47fad44ece2f6c7e88643
User & Date: dan 2009-09-01 12:16:01
Context
2009-09-01
16:19
Add new test script triggerC.test. check-in: a2a062a4 user: dan tags: trunk
12:16
More fixes and comment updates. check-in: 38a9327b user: dan tags: trunk
2009-08-31
15:27
More fixes for test cases. check-in: 85d9f23b user: dan tags: trunk
Changes
Hide Diffs Side-by-Side Diffs Ignore Whitespace Patch

Changes to src/build.c.

    60     60   void sqlite3TableLock(
    61     61     Parse *pParse,     /* Parsing context */
    62     62     int iDb,           /* Index of the database containing the table to lock */
    63     63     int iTab,          /* Root page number of the table to be locked */
    64     64     u8 isWriteLock,    /* True for a write lock */
    65     65     const char *zName  /* Name of the table to be locked */
    66     66   ){
           67  +  Parse *pToplevel = sqlite3ParseToplevel(pParse);
    67     68     int i;
    68     69     int nBytes;
    69     70     TableLock *p;
    70         -
    71     71     assert( iDb>=0 );
    72     72   
    73         -  if( pParse->pRoot ){
    74         -    pParse = pParse->pRoot;
    75         -  }
    76         -  for(i=0; i<pParse->nTableLock; i++){
    77         -    p = &pParse->aTableLock[i];
           73  +  for(i=0; i<pToplevel->nTableLock; i++){
           74  +    p = &pToplevel->aTableLock[i];
    78     75       if( p->iDb==iDb && p->iTab==iTab ){
    79     76         p->isWriteLock = (p->isWriteLock || isWriteLock);
    80     77         return;
    81     78       }
    82     79     }
    83     80   
    84         -  nBytes = sizeof(TableLock) * (pParse->nTableLock+1);
    85         -  pParse->aTableLock =
    86         -      sqlite3DbReallocOrFree(pParse->db, pParse->aTableLock, nBytes);
    87         -  if( pParse->aTableLock ){
    88         -    p = &pParse->aTableLock[pParse->nTableLock++];
           81  +  nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
           82  +  pToplevel->aTableLock =
           83  +      sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
           84  +  if( pToplevel->aTableLock ){
           85  +    p = &pToplevel->aTableLock[pToplevel->nTableLock++];
    89     86       p->iDb = iDb;
    90     87       p->iTab = iTab;
    91     88       p->isWriteLock = isWriteLock;
    92     89       p->zName = zName;
    93     90     }else{
    94         -    pParse->nTableLock = 0;
    95         -    pParse->db->mallocFailed = 1;
           91  +    pToplevel->nTableLock = 0;
           92  +    pToplevel->db->mallocFailed = 1;
    96     93     }
    97     94   }
    98     95   
    99     96   /*
   100     97   ** Code an OP_TableLock instruction for each table locked by the
   101     98   ** statement (configured by calls to sqlite3TableLock()).
   102     99   */
................................................................................
   194    191     if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
   195    192   #ifdef SQLITE_DEBUG
   196    193       FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
   197    194       sqlite3VdbeTrace(v, trace);
   198    195   #endif
   199    196       assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
   200    197       sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem,
   201         -                         pParse->nTab, pParse->nArg, pParse->explain);
          198  +                         pParse->nTab, pParse->nMaxArg, pParse->explain);
   202    199       pParse->rc = SQLITE_DONE;
   203    200       pParse->colNamesSet = 0;
   204    201     }else if( pParse->rc==SQLITE_OK ){
   205    202       pParse->rc = SQLITE_ERROR;
   206    203     }
   207    204     pParse->nTab = 0;
   208    205     pParse->nMem = 0;
................................................................................
  3422   3419   ** cookie verification subroutine code happens in sqlite3FinishCoding().
  3423   3420   **
  3424   3421   ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
  3425   3422   ** schema on any databases.  This can be used to position the OP_Goto
  3426   3423   ** early in the code, before we know if any database tables will be used.
  3427   3424   */
  3428   3425   void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
  3429         -  sqlite3 *db;
  3430         -  Vdbe *v;
  3431         -  int mask;
  3432         -  Parse *pRoot = pParse->pRoot;        /* Root parse structure */
         3426  +  Parse *pToplevel = sqlite3ParseToplevel(pParse);
  3433   3427   
  3434         -  v = sqlite3GetVdbe(pParse);
  3435         -  if( v==0 ) return;  /* This only happens if there was a prior error */
  3436         -  db = pParse->db;
  3437         -  if( pParse->cookieGoto==0 && pRoot==0 ){
  3438         -    pParse->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
         3428  +  if( pToplevel->cookieGoto==0 ){
         3429  +    Vdbe *v = sqlite3GetVdbe(pToplevel);
         3430  +    if( v==0 ) return;  /* This only happens if there was a prior error */
         3431  +    pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
  3439   3432     }
  3440   3433     if( iDb>=0 ){
  3441         -    if( pRoot==0 ){
  3442         -      pRoot = pParse;
  3443         -    }
         3434  +    sqlite3 *db = pToplevel->db;
         3435  +    int mask;
         3436  +
  3444   3437       assert( iDb<db->nDb );
  3445   3438       assert( db->aDb[iDb].pBt!=0 || iDb==1 );
  3446   3439       assert( iDb<SQLITE_MAX_ATTACHED+2 );
  3447   3440       mask = 1<<iDb;
  3448         -    if( (pRoot->cookieMask & mask)==0 ){
  3449         -      pRoot->cookieMask |= mask;
  3450         -      pRoot->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
         3441  +    if( (pToplevel->cookieMask & mask)==0 ){
         3442  +      pToplevel->cookieMask |= mask;
         3443  +      pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
  3451   3444         if( !OMIT_TEMPDB && iDb==1 ){
  3452         -        sqlite3OpenTempDatabase(pRoot);
         3445  +        sqlite3OpenTempDatabase(pToplevel);
  3453   3446         }
  3454   3447       }
  3455   3448     }
  3456   3449   }
  3457   3450   
  3458   3451   /*
  3459   3452   ** Generate VDBE code that prepares for doing an operation that
................................................................................
  3465   3458   ** be set for operations that might fail (due to a constraint) part of
  3466   3459   ** the way through and which will need to undo some writes without having to
  3467   3460   ** rollback the whole transaction.  For operations where all constraints
  3468   3461   ** can be checked before any changes are made to the database, it is never
  3469   3462   ** necessary to undo a write and the checkpoint should not be set.
  3470   3463   */
  3471   3464   void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
  3472         -  Parse *pRoot = pParse->pRoot;
         3465  +  Parse *pToplevel = sqlite3ParseToplevel(pParse);
  3473   3466     sqlite3CodeVerifySchema(pParse, iDb);
  3474         -  if( pRoot==0 ){
  3475         -    pRoot = pParse;
  3476         -  }
  3477         -  pRoot->writeMask |= 1<<iDb;
  3478         -  if( setStatement && pParse->nested==0 && pParse->pRoot==0 ){
         3467  +  pToplevel->writeMask |= 1<<iDb;
         3468  +  if( setStatement && pParse->nested==0 && pParse==pToplevel ){
  3479   3469       /* Every place where this routine is called with setStatement!=0 has
  3480   3470       ** already successfully created a VDBE. */
  3481   3471       assert( pParse->pVdbe );
  3482   3472       sqlite3VdbeAddOp1(pParse->pVdbe, OP_Statement, iDb);
  3483   3473     }
  3484   3474   }
  3485   3475   

Changes to src/expr.c.

  1394   1394       ** has already been allocated. So assume sqlite3GetVdbe() is always
  1395   1395       ** successful here.
  1396   1396       */
  1397   1397       assert(v);
  1398   1398       if( iCol<0 ){
  1399   1399         int iMem = ++pParse->nMem;
  1400   1400         int iAddr;
  1401         -      sqlite3VdbeUsesBtree(v, iDb);
  1402   1401   
  1403   1402         iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
  1404   1403         sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
  1405   1404   
  1406   1405         sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  1407   1406         eType = IN_INDEX_ROWID;
  1408   1407   
................................................................................
  1428   1427            && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
  1429   1428           ){
  1430   1429             int iMem = ++pParse->nMem;
  1431   1430             int iAddr;
  1432   1431             char *pKey;
  1433   1432     
  1434   1433             pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
  1435         -          iDb = sqlite3SchemaToIndex(db, pIdx->pSchema);
  1436         -          sqlite3VdbeUsesBtree(v, iDb);
  1437         -
  1438   1434             iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
  1439   1435             sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
  1440   1436     
  1441   1437             sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
  1442   1438                                  pKey,P4_KEYINFO_HANDOFF);
  1443   1439             VdbeComment((v, "%s", pIdx->zName));
  1444   1440             eType = IN_INDEX_INDEX;
................................................................................
  2555   2551       }
  2556   2552       case TK_UPLUS: {
  2557   2553         inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  2558   2554         break;
  2559   2555       }
  2560   2556   
  2561   2557       case TK_TRIGGER: {
         2558  +      /* If the opcode is TK_TRIGGER, then the expression is a reference
         2559  +      ** to a column in the new.* or old.* pseudo-tables available to
         2560  +      ** trigger programs. In this case Expr.iTable is set to 1 for the
         2561  +      ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
         2562  +      ** is set to the column of the pseudo-table to read, or to -1 to
         2563  +      ** read the rowid field.
         2564  +      **
         2565  +      ** The expression is implemented using an OP_Param opcode. The p1
         2566  +      ** parameter is set to 0 for an old.rowid reference, or to (i+1)
         2567  +      ** to reference another column of the old.* pseudo-table, where 
         2568  +      ** i is the index of the column. For a new.rowid reference, p1 is
         2569  +      ** set to (n+1), where n is the number of columns in each pseudo-table.
         2570  +      ** For a reference to any other column in the new.* pseudo-table, p1
         2571  +      ** is set to (n+2+i), where n and i are as defined previously. For
         2572  +      ** example, if the table on which triggers are being fired is
         2573  +      ** declared as:
         2574  +      **
         2575  +      **   CREATE TABLE t1(a, b);
         2576  +      **
         2577  +      ** Then p1 is interpreted as follows:
         2578  +      **
         2579  +      **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
         2580  +      **   p1==1   ->    old.a         p1==4   ->    new.a
         2581  +      **   p1==2   ->    old.b         p1==5   ->    new.b       
         2582  +      */
  2562   2583         Table *pTab = pExpr->pTab;
  2563         -      int iVal = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
  2564         -      sqlite3VdbeAddOp2(v, OP_Param, iVal, target);
         2584  +      int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
         2585  +
         2586  +      assert( pExpr->iTable==0 || pExpr->iTable==1 );
         2587  +      assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
         2588  +      assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
         2589  +      assert( p1>=0 && p1<(pTab->nCol*2+2) );
         2590  +
         2591  +      sqlite3VdbeAddOp2(v, OP_Param, p1, target);
  2565   2592         VdbeComment((v, "%s.%s -> $%d",
  2566   2593           (pExpr->iTable ? "new" : "old"),
  2567   2594           (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
  2568   2595           target
  2569   2596         ));
         2597  +
         2598  +      /* If the column has REAL affinity, it may currently be stored as an
         2599  +      ** integer. Use OP_RealAffinity to make sure it is really real.  */
  2570   2600         if( pExpr->iColumn>=0 
  2571   2601          && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
  2572   2602         ){
  2573   2603           sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
  2574   2604         }
  2575   2605         break;
  2576   2606       }

Changes to src/insert.c.

   193    193   static int autoIncBegin(
   194    194     Parse *pParse,      /* Parsing context */
   195    195     int iDb,            /* Index of the database holding pTab */
   196    196     Table *pTab         /* The table we are writing to */
   197    197   ){
   198    198     int memId = 0;      /* Register holding maximum rowid */
   199    199     if( pTab->tabFlags & TF_Autoincrement ){
   200         -    Parse *pRoot = (pParse->pRoot ? pParse->pRoot : pParse);
          200  +    Parse *pToplevel = sqlite3ParseToplevel(pParse);
   201    201       AutoincInfo *pInfo;
   202    202   
   203         -    pInfo = pRoot->pAinc;
          203  +    pInfo = pToplevel->pAinc;
   204    204       while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
   205    205       if( pInfo==0 ){
   206    206         pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
   207    207         if( pInfo==0 ) return 0;
   208         -      pInfo->pNext = pRoot->pAinc;
   209         -      pRoot->pAinc = pInfo;
          208  +      pInfo->pNext = pToplevel->pAinc;
          209  +      pToplevel->pAinc = pInfo;
   210    210         pInfo->pTab = pTab;
   211    211         pInfo->iDb = iDb;
   212         -      pRoot->nMem++;                  /* Register to hold name of table */
   213         -      pInfo->regCtr = ++pRoot->nMem;  /* Max rowid register */
   214         -      pRoot->nMem++;                  /* Rowid in sqlite_sequence */
          212  +      pToplevel->nMem++;                  /* Register to hold name of table */
          213  +      pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
          214  +      pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
   215    215       }
   216    216       memId = pInfo->regCtr;
   217    217     }
   218    218     return memId;
   219    219   }
   220    220   
   221    221   /*
................................................................................
   450    450     int endOfLoop;        /* Label for the end of the insertion loop */
   451    451     int useTempTable = 0; /* Store SELECT results in intermediate table */
   452    452     int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
   453    453     int addrInsTop = 0;   /* Jump to label "D" */
   454    454     int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
   455    455     int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
   456    456     SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
   457         -  int newIdx = -1;      /* Cursor for the NEW pseudo-table */
   458    457     int iDb;              /* Index of database holding TABLE */
   459    458     Db *pDb;              /* The database containing table being inserted into */
   460    459     int appendFlag = 0;   /* True if the insert is likely to be an append */
   461    460   
   462    461     /* Register allocations */
   463    462     int regFromSelect = 0;/* Base register for data coming from SELECT */
   464    463     int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
................................................................................
   465    464     int regRowCount = 0;  /* Memory cell used for the row counter */
   466    465     int regIns;           /* Block of regs holding rowid+data being inserted */
   467    466     int regRowid;         /* registers holding insert rowid */
   468    467     int regData;          /* register holding first column to insert */
   469    468     int regRecord;        /* Holds the assemblied row record */
   470    469     int regEof = 0;       /* Register recording end of SELECT data */
   471    470     int *aRegIdx = 0;     /* One register allocated to each index */
   472         -
   473    471   
   474    472   #ifndef SQLITE_OMIT_TRIGGER
   475    473     int isView;                 /* True if attempting to insert into a view */
   476    474     Trigger *pTrigger;          /* List of triggers on pTab, if required */
   477    475     int tmask;                  /* Mask of trigger times */
   478    476   #endif
   479    477   
................................................................................
  1046   1044   }
  1047   1045   
  1048   1046   /*
  1049   1047   ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
  1050   1048   **
  1051   1049   ** The input is a range of consecutive registers as follows:
  1052   1050   **
  1053         -**    1.  The rowid of the row to be updated before the update.  This
  1054         -**        value is omitted unless we are doing an UPDATE that involves a
  1055         -**        change to the record number or writing to a virtual table.
         1051  +**    1.  The rowid of the row after the update.
  1056   1052   **
  1057         -**    2.  The rowid of the row after the update.
  1058         -**
  1059         -**    3.  The data in the first column of the entry after the update.
         1053  +**    2.  The data in the first column of the entry after the update.
  1060   1054   **
  1061   1055   **    i.  Data from middle columns...
  1062   1056   **
  1063   1057   **    N.  The data in the last column of the entry after the update.
  1064   1058   **
  1065         -** The regRowid parameter is the index of the register containing (2).
         1059  +** The regRowid parameter is the index of the register containing (1).
  1066   1060   **
  1067         -** The old rowid shown as entry (1) above is omitted unless both isUpdate
  1068         -** and rowidChng are 1.  isUpdate is true for UPDATEs and false for
  1069         -** INSERTs.  RowidChng means that the new rowid is explicitly specified by
  1070         -** the update or insert statement.  If rowidChng is false, it means that
  1071         -** the rowid is computed automatically in an insert or that the rowid value
  1072         -** is not modified by the update.
         1061  +** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
         1062  +** the address of a register containing the rowid before the update takes
         1063  +** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
         1064  +** is false, indicating an INSERT statement, then a non-zero rowidChng 
         1065  +** indicates that the rowid was explicitly specified as part of the
         1066  +** INSERT statement. If rowidChng is false, it means that  the rowid is
         1067  +** computed automatically in an insert or that the rowid value is not 
         1068  +** modified by an update.
  1073   1069   **
  1074   1070   ** The code generated by this routine store new index entries into
  1075   1071   ** registers identified by aRegIdx[].  No index entry is created for
  1076   1072   ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
  1077   1073   ** the same as the order of indices on the linked list of indices
  1078   1074   ** attached to the table.
  1079   1075   **
................................................................................
  1140   1136     int onError;        /* Conflict resolution strategy */
  1141   1137     int j1;             /* Addresss of jump instruction */
  1142   1138     int j2 = 0, j3;     /* Addresses of jump instructions */
  1143   1139     int regData;        /* Register containing first data column */
  1144   1140     int iCur;           /* Table cursor number */
  1145   1141     Index *pIdx;         /* Pointer to one of the indices */
  1146   1142     int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
  1147         -  int hasTwoRowids = (isUpdate && rowidChng);
         1143  +  int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
  1148   1144   
  1149   1145     v = sqlite3GetVdbe(pParse);
  1150   1146     assert( v!=0 );
  1151   1147     assert( pTab->pSelect==0 );  /* This table is not a VIEW */
  1152   1148     nCol = pTab->nCol;
  1153   1149     regData = regRowid + 1;
  1154   1150   
................................................................................
  1300   1296         if( onError==OE_Ignore ) onError = OE_Replace;
  1301   1297         else if( onError==OE_Fail ) onError = OE_Abort;
  1302   1298       }
  1303   1299       
  1304   1300   
  1305   1301       /* Check to see if the new index entry will be unique */
  1306   1302       regR = sqlite3GetTempReg(pParse);
  1307         -    sqlite3VdbeAddOp2(v, OP_SCopy, regRowid-hasTwoRowids, regR);
         1303  +    sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
  1308   1304       j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
  1309   1305                              regR, SQLITE_INT_TO_PTR(regIdx),
  1310   1306                              P4_INT32);
  1311   1307       sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
  1312   1308   
  1313   1309       /* Generate code that executes if the new index entry is not unique */
  1314   1310       assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail

Changes to src/main.c.

  1587   1587     db->flags |= SQLITE_ShortColNames
  1588   1588   #if SQLITE_DEFAULT_FILE_FORMAT<4
  1589   1589                    | SQLITE_LegacyFileFmt
  1590   1590   #endif
  1591   1591   #ifdef SQLITE_ENABLE_LOAD_EXTENSION
  1592   1592                    | SQLITE_LoadExtension
  1593   1593   #endif
  1594         -#ifdef SQLITE_DISABLE_RECURSIVE_TRIGGERS
         1594  +#if 1 || defined(SQLITE_DISABLE_RECURSIVE_TRIGGERS)
  1595   1595                    | SQLITE_NoRecTriggers
  1596   1596   #endif
  1597   1597         ;
  1598   1598     sqlite3HashInit(&db->aCollSeq);
  1599   1599   #ifndef SQLITE_OMIT_VIRTUALTABLE
  1600   1600     sqlite3HashInit(&db->aModule);
  1601   1601   #endif

Changes to src/prepare.c.

   672    672     if( zErrMsg ){
   673    673       sqlite3Error(db, rc, "%s", zErrMsg);
   674    674       sqlite3DbFree(db, zErrMsg);
   675    675     }else{
   676    676       sqlite3Error(db, rc, 0);
   677    677     }
   678    678   
          679  +  /* Delete any TriggerPrg structures allocated while parsing this statement. */
   679    680     while( pParse->pTriggerPrg ){
   680    681       TriggerPrg *pT = pParse->pTriggerPrg;
   681    682       pParse->pTriggerPrg = pT->pNext;
   682    683       sqlite3VdbeProgramDelete(db, pT->pProgram, 0);
   683    684       sqlite3DbFree(db, pT);
   684    685     }
   685    686   

Changes to src/resolve.c.

   220    220       }
   221    221   
   222    222   #ifndef SQLITE_OMIT_TRIGGER
   223    223       /* If we have not already resolved the name, then maybe 
   224    224       ** it is a new.* or old.* trigger argument reference
   225    225       */
   226    226       if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
          227  +      int op = pParse->eTriggerOp;
   227    228         Table *pTab = 0;
   228         -      if( pParse->triggerOp!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
          229  +      assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
          230  +      if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
   229    231           pExpr->iTable = 1;
   230    232           pTab = pParse->pTriggerTab;
   231         -      }else if( pParse->triggerOp!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
          233  +      }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
   232    234           pExpr->iTable = 0;
   233    235           pTab = pParse->pTriggerTab;
   234    236         }
   235    237   
   236    238         if( pTab ){ 
   237    239           int iCol;
   238    240           pSchema = pTab->pSchema;

Changes to src/select.c.

  2729   2729     ** complete, since there may still exist Expr.pTab entries that
  2730   2730     ** refer to the subquery even after flattening.  Ticket #3346.
  2731   2731     **
  2732   2732     ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
  2733   2733     */
  2734   2734     if( ALWAYS(pSubitem->pTab!=0) ){
  2735   2735       Table *pTabToDel = pSubitem->pTab;
  2736         -    Parse *pRoot = (pParse->pRoot ? pParse->pRoot : pParse);
  2737   2736       if( pTabToDel->nRef==1 ){
  2738         -      pTabToDel->pNextZombie = pRoot->pZombieTab;
  2739         -      pRoot->pZombieTab = pTabToDel;
         2737  +      Parse *pToplevel = sqlite3ParseToplevel(pParse);
         2738  +      pTabToDel->pNextZombie = pToplevel->pZombieTab;
         2739  +      pToplevel->pZombieTab = pTabToDel;
  2740   2740       }else{
  2741   2741         pTabToDel->nRef--;
  2742   2742       }
  2743   2743       pSubitem->pTab = 0;
  2744   2744     }
  2745   2745   
  2746   2746     /* The following loop runs once for each term in a compound-subquery

Changes to src/sqliteInt.h.

  2025   2025   ** completed.
  2026   2026   **
  2027   2027   ** A Vdbe sub-program that implements the body and WHEN clause of trigger
  2028   2028   ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
  2029   2029   ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
  2030   2030   ** The Parse.pTriggerPrg list never contains two entries with the same
  2031   2031   ** values for both pTrigger and orconf.
         2032  +**
         2033  +** The TriggerPrg.oldmask variable is set to a mask of old.* columns
         2034  +** accessed (or set to 0 for triggers fired as a result of INSERT 
         2035  +** statements).
  2032   2036   */
  2033   2037   struct TriggerPrg {
  2034   2038     Trigger *pTrigger;      /* Trigger this program was coded from */
  2035   2039     int orconf;             /* Default ON CONFLICT policy */
  2036   2040     SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
  2037   2041     u32 oldmask;            /* Mask of old.* columns accessed */
  2038   2042     TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
................................................................................
  2094   2098   #ifndef SQLITE_OMIT_SHARED_CACHE
  2095   2099     int nTableLock;        /* Number of locks in aTableLock */
  2096   2100     TableLock *aTableLock; /* Required table locks for shared-cache mode */
  2097   2101   #endif
  2098   2102     int regRowid;        /* Register holding rowid of CREATE TABLE entry */
  2099   2103     int regRoot;         /* Register holding root page number for new objects */
  2100   2104     AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
         2105  +  int nMaxArg;         /* Max args passed to user function by sub-program */
  2101   2106   
  2102   2107     /* Information used while coding trigger programs. */
  2103         -  Parse *pRoot;        /* Root Parse structure */
         2108  +  Parse *pToplevel;    /* Parse structure for main program (or NULL) */
  2104   2109     Table *pTriggerTab;  /* Table triggers are being coded for */
  2105         -  u32 oldmask; 
  2106         -  u32 newmask; 
  2107         -  int triggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
  2108         -  int nArg;
  2109         -  int orconf;          /* Default ON CONFLICT policy for trigger steps */
         2110  +  u32 oldmask;         /* Mask of old.* columns referenced */
         2111  +  u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
         2112  +  u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
  2110   2113   
  2111   2114     /* Above is constant between recursions.  Below is reset before and after
  2112   2115     ** each recursion */
  2113   2116   
  2114   2117     int nVar;            /* Number of '?' variables seen in the SQL so far */
  2115   2118     int nVarExpr;        /* Number of used slots in apVarExpr[] */
  2116   2119     int nVarExprAlloc;   /* Number of allocated slots in apVarExpr[] */
................................................................................
  2688   2691     TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
  2689   2692                                           ExprList*,Select*,u8);
  2690   2693     TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
  2691   2694     TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
  2692   2695     void sqlite3DeleteTrigger(sqlite3*, Trigger*);
  2693   2696     void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
  2694   2697     u32 sqlite3TriggerOldmask(Parse*,Trigger*,int,ExprList*,Table*,int);
         2698  +# define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
  2695   2699   #else
  2696   2700   # define sqlite3TriggersExist(B,C,D,E,F) 0
  2697   2701   # define sqlite3DeleteTrigger(A,B)
  2698   2702   # define sqlite3DropTriggerPtr(A,B)
  2699   2703   # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
  2700   2704   # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I,J)
  2701   2705   # define sqlite3TriggerList(X, Y) 0
         2706  +# define sqlite3ParseToplevel(p) p
  2702   2707   #endif
  2703   2708   
  2704   2709   int sqlite3JoinType(Parse*, Token*, Token*, Token*);
  2705   2710   void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
  2706   2711   void sqlite3DeferForeignKey(Parse*, int);
  2707   2712   #ifndef SQLITE_OMIT_AUTHORIZATION
  2708   2713     void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);

Changes to src/trigger.c.

   662    662         pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
   663    663       }
   664    664     }
   665    665     return pSrc;
   666    666   }
   667    667   
   668    668   /*
   669         -** Generate VDBE code for zero or more statements inside the body of a
   670         -** trigger.  
          669  +** Generate VDBE code for the statements inside the body of a single 
          670  +** trigger.
   671    671   */
   672    672   static int codeTriggerProgram(
   673    673     Parse *pParse,            /* The parser context */
   674    674     TriggerStep *pStepList,   /* List of statements inside the trigger body */
   675         -  int orconfin              /* Conflict algorithm. (OE_Abort, etc) */  
          675  +  int orconf                /* Conflict algorithm. (OE_Abort, etc) */  
   676    676   ){
   677         -  TriggerStep * pStep = pStepList;
          677  +  TriggerStep *pStep;
   678    678     Vdbe *v = pParse->pVdbe;
   679    679     sqlite3 *db = pParse->db;
   680    680   
   681         -  assert( pParse->pRoot );
   682         -  assert( pStep!=0 );
          681  +  assert( pParse->pTriggerTab && pParse->pToplevel );
          682  +  assert( pStepList );
   683    683     assert( v!=0 );
   684         -  while( pStep ){
          684  +  for(pStep=pStepList; pStep; pStep=pStep->pNext){
   685    685       /* Figure out the ON CONFLICT policy that will be used for this step
   686    686       ** of the trigger program. If the statement that caused this trigger
   687    687       ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
   688    688       ** the ON CONFLICT policy that was specified as part of the trigger
   689    689       ** step statement. Example:
   690    690       **
   691    691       **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
   692    692       **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
   693    693       **   END;
   694    694       **
   695    695       **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
   696    696       **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
   697    697       */
   698         -    pParse->orconf = (orconfin==OE_Default)?pStep->orconf:orconfin;
          698  +    pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:orconf;
   699    699   
   700    700       switch( pStep->op ){
   701    701         case TK_UPDATE: {
   702    702           sqlite3Update(pParse, 
   703    703             targetSrcList(pParse, pStep),
   704    704             sqlite3ExprListDup(db, pStep->pExprList, 0), 
   705    705             sqlite3ExprDup(db, pStep->pWhere, 0), 
   706         -          pParse->orconf
          706  +          pParse->eOrconf
   707    707           );
   708    708           break;
   709    709         }
   710    710         case TK_INSERT: {
   711    711           sqlite3Insert(pParse, 
   712    712             targetSrcList(pParse, pStep),
   713    713             sqlite3ExprListDup(db, pStep->pExprList, 0), 
   714    714             sqlite3SelectDup(db, pStep->pSelect, 0), 
   715    715             sqlite3IdListDup(db, pStep->pIdList), 
   716         -          pParse->orconf
          716  +          pParse->eOrconf
   717    717           );
   718    718           break;
   719    719         }
   720    720         case TK_DELETE: {
   721    721           sqlite3DeleteFrom(pParse, 
   722    722             targetSrcList(pParse, pStep),
   723    723             sqlite3ExprDup(db, pStep->pWhere, 0)
................................................................................
   732    732           sqlite3SelectDelete(db, pSelect);
   733    733           break;
   734    734         }
   735    735       } 
   736    736       if( pStep->op!=TK_SELECT ){
   737    737         sqlite3VdbeAddOp1(v, OP_ResetCount, 1);
   738    738       }
   739         -    pStep = pStep->pNext;
   740    739     }
   741    740   
   742    741     return 0;
   743    742   }
   744    743   
   745    744   #ifdef SQLITE_DEBUG
   746    745   /*
................................................................................
   772    771       pTo->zErrMsg = pFrom->zErrMsg;
   773    772       pTo->nErr = pFrom->nErr;
   774    773     }else{
   775    774       sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
   776    775     }
   777    776   }
   778    777   
          778  +/*
          779  +** Create and populate a new TriggerPrg object with a sub-program 
          780  +** implementing trigger pTrigger with ON CONFLICT policy orconf.
          781  +*/
   779    782   static TriggerPrg *codeRowTrigger(
   780         -  Parse *pRoot,        /* Root parse context */
   781    783     Parse *pParse,       /* Current parse context */
   782    784     Trigger *pTrigger,   /* Trigger to code */
   783         -  int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
   784         -  Table *pTab,         /* The table to code triggers from */
   785         -  int orconf
          785  +  Table *pTab,         /* The table pTrigger is attached to */
          786  +  int orconf           /* ON CONFLICT policy to code trigger program with */
   786    787   ){
   787         -  sqlite3 *db = pParse->db;
   788         -  TriggerPrg *pPrg;
          788  +  Parse *pTop = sqlite3ParseToplevel(pParse);
          789  +  sqlite3 *db = pParse->db;   /* Database handle */
          790  +  TriggerPrg *pPrg;           /* Value to return */
   789    791     Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
   790    792     Vdbe *v;                    /* Temporary VM */
   791    793     NameContext sNC;            /* Name context for sub-vdbe */
   792    794     SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
   793    795     Parse *pSubParse;           /* Parse context for sub-vdbe */
   794    796     int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
   795    797   
          798  +  assert( pTab==tableOfTrigger(pTrigger) );
          799  +
          800  +  /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
          801  +  ** are freed if an error occurs, link them into the Parse.pTriggerPrg 
          802  +  ** list of the top-level Parse object sooner rather than later.  */
   796    803     pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
   797    804     if( !pPrg ) return 0;
   798         -  pPrg->pNext = pRoot->pTriggerPrg;
   799         -  pRoot->pTriggerPrg = pPrg;
          805  +  pPrg->pNext = pTop->pTriggerPrg;
          806  +  pTop->pTriggerPrg = pPrg;
   800    807     pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
   801    808     if( !pProgram ) return 0;
   802    809     pProgram->nRef = 1;
   803         -  pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
   804         -  if( !pSubParse ) return 0;
   805         -
   806         -  pPrg->pProgram = pProgram;
   807    810     pPrg->pTrigger = pTrigger;
   808    811     pPrg->orconf = orconf;
   809    812   
          813  +  /* Allocate and populate a new Parse context to use for coding the 
          814  +  ** trigger sub-program.  */
          815  +  pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
          816  +  if( !pSubParse ) return 0;
   810    817     memset(&sNC, 0, sizeof(sNC));
   811    818     sNC.pParse = pSubParse;
   812    819     pSubParse->db = db;
   813    820     pSubParse->pTriggerTab = pTab;
   814         -  pSubParse->pRoot = pRoot;
          821  +  pSubParse->pToplevel = pTop;
   815    822     pSubParse->zAuthContext = pTrigger->zName;
          823  +  pSubParse->eTriggerOp = pTrigger->op;
   816    824   
   817    825     v = sqlite3GetVdbe(pSubParse);
   818    826     if( v ){
   819    827       VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)", 
   820    828         pTrigger->zName, onErrorText(orconf),
   821    829         (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
   822         -        (op==TK_UPDATE ? "UPDATE" : ""),
   823         -        (op==TK_INSERT ? "INSERT" : ""),
   824         -        (op==TK_DELETE ? "DELETE" : ""),
          830  +        (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
          831  +        (pTrigger->op==TK_INSERT ? "INSERT" : ""),
          832  +        (pTrigger->op==TK_DELETE ? "DELETE" : ""),
   825    833         pTab->zName
   826    834       ));
   827    835   #ifndef SQLITE_OMIT_TRACE
   828    836       sqlite3VdbeChangeP4(v, -1, 
   829    837         sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
   830    838       );
   831    839   #endif
   832    840   
          841  +    /* If one was specified, code the WHEN clause. If it evaluates to false
          842  +    ** (or NULL) the sub-vdbe is immediately halted by jumping to the 
          843  +    ** OP_Halt inserted at the end of the program.  */
   833    844       if( pTrigger->pWhen ){
   834         -      /* Code the WHEN clause. If it evaluates to false (or NULL) the 
   835         -      ** sub-vdbe is immediately halted.  */
   836    845         pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
   837    846         if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen) 
   838    847          && db->mallocFailed==0 
   839    848         ){
   840    849           iEndTrigger = sqlite3VdbeMakeLabel(v);
   841    850           sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
   842    851         }
   843    852         sqlite3ExprDelete(db, pWhen);
   844    853       }
   845    854   
   846    855       /* Code the trigger program into the sub-vdbe. */
   847    856       codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
          857  +
          858  +    /* Insert an OP_Halt at the end of the sub-program. */
   848    859       if( iEndTrigger ){
   849    860         sqlite3VdbeResolveLabel(v, iEndTrigger);
   850    861       }
   851    862       sqlite3VdbeAddOp0(v, OP_Halt);
   852    863       VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
   853    864   
   854    865       transferParseError(pParse, pSubParse);
   855    866       if( db->mallocFailed==0 ){
   856         -      pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pParse->nArg);
          867  +      pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
   857    868       }
   858    869       pProgram->nMem = pSubParse->nMem;
   859    870       pProgram->nCsr = pSubParse->nTab;
   860    871       pProgram->token = (void *)pTrigger;
   861    872       pPrg->oldmask = pSubParse->oldmask;
   862    873       sqlite3VdbeDelete(v);
   863         -
   864         -    while( pSubParse->pAinc ){
   865         -      AutoincInfo *p = pSubParse->pAinc;
   866         -      pSubParse->pAinc = p->pNext;
   867         -      sqlite3DbFree(db, p);
   868         -    }
   869    874     }
          875  +
          876  +  assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
          877  +  assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
   870    878     sqlite3StackFree(db, pSubParse);
   871    879   
   872    880     return pPrg;
   873    881   }
   874    882       
          883  +/*
          884  +** Return a pointer to a TriggerPrg object containing the sub-program for
          885  +** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
          886  +** TriggerPrg object exists, a new object is allocated and populated before
          887  +** being returned.
          888  +*/
   875    889   static TriggerPrg *getRowTrigger(
   876         -  Parse *pParse,
          890  +  Parse *pParse,       /* Current parse context */
   877    891     Trigger *pTrigger,   /* Trigger to code */
   878         -  int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
   879         -  Table *pTab,         /* The table to code triggers from */
   880         -  int orconf
          892  +  Table *pTab,         /* The table trigger pTrigger is attached to */
          893  +  int orconf           /* ON CONFLICT algorithm. */
   881    894   ){
          895  +  Parse *pRoot = sqlite3ParseToplevel(pParse);
   882    896     TriggerPrg *pPrg;
   883         -  Parse *pRoot = pParse;
          897  +
          898  +  assert( pTab==tableOfTrigger(pTrigger) );
   884    899   
   885    900     /* It may be that this trigger has already been coded (or is in the
   886    901     ** process of being coded). If this is the case, then an entry with
   887    902     ** a matching TriggerPrg.pTrigger field will be present somewhere
   888    903     ** in the Parse.pTriggerPrg list. Search for such an entry.  */
   889         -  if( pParse->pRoot ){
   890         -    pRoot = pParse->pRoot;
   891         -  }
   892    904     for(pPrg=pRoot->pTriggerPrg; 
   893    905         pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf); 
   894    906         pPrg=pPrg->pNext
   895    907     );
   896    908   
          909  +  /* If an existing TriggerPrg could not be located, create a new one. */
   897    910     if( !pPrg ){
   898         -    pPrg = codeRowTrigger(pRoot, pParse, pTrigger, op, pTab, orconf);
          911  +    pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
   899    912     }
   900    913   
   901    914     return pPrg;
   902    915   }
   903    916   
   904    917   /*
   905    918   ** This is called to code FOR EACH ROW triggers.
................................................................................
   958    971       /* Determine whether we should code this trigger */
   959    972       if( p->op==op 
   960    973        && p->tr_tm==tr_tm 
   961    974        && checkColumnOverlap(p->pColumns,pChanges)
   962    975       ){
   963    976         Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
   964    977         TriggerPrg *pPrg;
   965         -      pPrg = getRowTrigger(pParse, p, op, pTab, orconf);
          978  +      pPrg = getRowTrigger(pParse, p, pTab, orconf);
   966    979         assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
   967    980   
   968    981         /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program 
   969    982         ** is a pointer to the sub-vdbe containing the trigger program.  */
   970    983         if( pPrg ){
   971    984           sqlite3VdbeAddOp3(v, OP_Program, oldIdx, ignoreJump, ++pParse->nMem);
   972    985           pPrg->pProgram->nRef++;
................................................................................
  1007   1020     u32 mask = 0;
  1008   1021     Trigger *p;
  1009   1022   
  1010   1023     assert(op==TK_UPDATE || op==TK_DELETE);
  1011   1024     for(p=pTrigger; p; p=p->pNext){
  1012   1025       if( p->op==op && checkColumnOverlap(p->pColumns,pChanges) ){
  1013   1026         TriggerPrg *pPrg;
  1014         -      pPrg = getRowTrigger(pParse, p, op, pTab, orconf);
         1027  +      pPrg = getRowTrigger(pParse, p, pTab, orconf);
  1015   1028         if( pPrg ){
  1016   1029           mask |= pPrg->oldmask;
  1017   1030         }
  1018   1031       }
  1019   1032     }
  1020   1033   
  1021   1034     return mask;
  1022   1035   }
  1023   1036   
  1024   1037   #endif /* !defined(SQLITE_OMIT_TRIGGER) */

Changes to src/vdbe.c.

  4768   4768   ** exception using the RAISE() function. Register P3 contains the address 
  4769   4769   ** of a memory cell in this (the parent) VM that is used to allocate the 
  4770   4770   ** memory required by the sub-vdbe at runtime.
  4771   4771   **
  4772   4772   ** P4 is a pointer to the VM containing the trigger program.
  4773   4773   */
  4774   4774   case OP_Program: {        /* jump */
  4775         -  VdbeFrame *pFrame;
  4776         -  SubProgram *pProgram = pOp->p4.pProgram;
  4777         -  Mem *pRt = &p->aMem[pOp->p3];        /* Register to allocate runtime space */
         4775  +  int nMem;               /* Number of memory registers for sub-program */
         4776  +  int nByte;              /* Bytes of runtime space required for sub-program */
         4777  +  Mem *pRt;               /* Register to allocate runtime space */
         4778  +  Mem *pMem;              /* Used to iterate through memory cells */
         4779  +  Mem *pEnd;              /* Last memory cell in new array */
         4780  +  VdbeFrame *pFrame;      /* New vdbe frame to execute in */
         4781  +  SubProgram *pProgram;   /* Sub-program to execute */
         4782  +  void *t;                /* Token identifying trigger */
         4783  +
         4784  +  pProgram = pOp->p4.pProgram;
         4785  +  pRt = &p->aMem[pOp->p3];
  4778   4786     assert( pProgram->nOp>0 );
  4779   4787     
  4780   4788     /* If the SQLITE_NoRecTriggers flag it set, then recursive invocation of
  4781   4789     ** triggers is disabled for backwards compatibility (flag set/cleared by
  4782   4790     ** the "PRAGMA disable_recursive_triggers" command). 
  4783   4791     ** 
  4784   4792     ** It is recursive invocation of triggers, at the SQL level, that is 
................................................................................
  4785   4793     ** disabled. In some cases a single trigger may generate more than one 
  4786   4794     ** SubProgram (if the trigger may be executed with more than one different 
  4787   4795     ** ON CONFLICT algorithm). SubProgram structures associated with a
  4788   4796     ** single trigger all have the same value for the SubProgram.token 
  4789   4797     ** variable.
  4790   4798     */
  4791   4799     if( db->flags&SQLITE_NoRecTriggers ){
  4792         -    void *t = pProgram->token;
         4800  +    t = pProgram->token;
  4793   4801       for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
  4794   4802       if( pFrame ) break;
  4795   4803     }
  4796   4804   
  4797   4805     /* TODO: This constant should be configurable. */
  4798   4806     if( p->nFrame>1000 ){
  4799   4807       rc = SQLITE_ERROR;
................................................................................
  4802   4810     }
  4803   4811   
  4804   4812     /* Register pRt is used to store the memory required to save the state
  4805   4813     ** of the current program, and the memory required at runtime to execute
  4806   4814     ** the trigger program. If this trigger has been fired before, then pRt 
  4807   4815     ** is already allocated. Otherwise, it must be initialized.  */
  4808   4816     if( (pRt->flags&MEM_Frame)==0 ){
  4809         -    Mem *pMem;
  4810         -    Mem *pEnd;
  4811         -
  4812   4817       /* SubProgram.nMem is set to the number of memory cells used by the 
  4813   4818       ** program stored in SubProgram.aOp. As well as these, one memory
  4814   4819       ** cell is required for each cursor used by the program. Set local
  4815   4820       ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
  4816   4821       */
  4817         -    int nMem = pProgram->nMem + pProgram->nCsr;
  4818         -    int nByte = ROUND8(sizeof(VdbeFrame))
         4822  +    nMem = pProgram->nMem + pProgram->nCsr;
         4823  +    nByte = ROUND8(sizeof(VdbeFrame))
  4819   4824                 + nMem * sizeof(Mem)
  4820   4825                 + pProgram->nCsr * sizeof(VdbeCursor *);
  4821   4826       pFrame = sqlite3DbMallocZero(db, nByte);
  4822   4827       if( !pFrame ){
  4823   4828         goto no_mem;
  4824   4829       }
  4825   4830       sqlite3VdbeMemRelease(pRt);
................................................................................
  4876   4881   ** and old.* values.
  4877   4882   **
  4878   4883   ** The address of the cell in the parent frame is determined by adding
  4879   4884   ** the value of the P1 argument to the value of the P1 argument to the
  4880   4885   ** calling OP_Program instruction.
  4881   4886   */
  4882   4887   case OP_Param: {           /* out2-prerelease */
  4883         -  VdbeFrame *pFrame = p->pFrame;
  4884         -  Mem *pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];   
         4888  +  VdbeFrame *pFrame;
         4889  +  Mem *pIn;
         4890  +  pFrame = p->pFrame;
         4891  +  pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];   
  4885   4892     sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
  4886   4893     break;
  4887   4894   }
  4888   4895   
  4889   4896   #endif /* #ifndef SQLITE_OMIT_TRIGGER */
  4890   4897   
  4891   4898   #ifndef SQLITE_OMIT_AUTOINCREMENT

Changes to src/vdbeInt.h.

    85     85     int payloadSize;      /* Total number of bytes in the record */
    86     86     u32 *aType;           /* Type values for all entries in the record */
    87     87     u32 *aOffset;         /* Cached offsets to the start of each columns data */
    88     88     u8 *aRow;             /* Data for the current row, if all on one page */
    89     89   };
    90     90   typedef struct VdbeCursor VdbeCursor;
    91     91   
           92  +/*
           93  +** When a sub-program is executed (OP_Program), a structure of this type
           94  +** is allocated to store the current value of the program counter, as
           95  +** well as the current memory cell array and various other frame specific
           96  +** values stored in the Vdbe struct. When the sub-program is finished, 
           97  +** these values are copied back to the Vdbe from the VdbeFrame structure,
           98  +** restoring the state of the VM to as it was before the sub-program
           99  +** began executing.
          100  +**
          101  +** Frames are stored in a linked list headed at Vdbe.pParent. Vdbe.pParent
          102  +** is the parent of the current frame, or zero if the current frame
          103  +** is the main Vdbe program.
          104  +*/
    92    105   typedef struct VdbeFrame VdbeFrame;
    93    106   struct VdbeFrame {
    94    107     Vdbe *v;                /* VM this frame belongs to */
    95    108     int pc;                 /* Program Counter */
    96    109     Op *aOp;                /* Program instructions */
    97    110     int nOp;                /* Size of aOp array */
    98    111     Mem *aMem;              /* Array of memory cells */
    99    112     int nMem;               /* Number of entries in aMem */
   100    113     VdbeCursor **apCsr;     /* Element of Vdbe cursors */
   101    114     u16 nCursor;            /* Number of entries in apCsr */
   102         -  VdbeFrame *pParent;     /* Parent of this frame */
   103    115     void *token;            /* Copy of SubProgram.token */
   104    116     int nChildMem;          /* Number of memory cells for child frame */
   105    117     int nChildCsr;          /* Number of cursors for child frame */
   106         -  i64 lastRowid;    /* Last insert rowid (sqlite3.lastRowid) */
   107         -  int nChange;      /* Statement changes (Vdbe.nChanges)     */
          118  +  i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
          119  +  int nChange;            /* Statement changes (Vdbe.nChanges)     */
          120  +  VdbeFrame *pParent;     /* Parent of this frame */
   108    121   };
   109    122   
   110    123   #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
   111    124   
   112    125   /*
   113    126   ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
   114    127   */
................................................................................
   304    317     void *pFree;            /* Free this when deleting the vdbe */
   305    318     int iStatement;         /* Statement number (or 0 if has not opened stmt) */
   306    319   #ifdef SQLITE_DEBUG
   307    320     FILE *trace;            /* Write an execution trace here, if not NULL */
   308    321   #endif
   309    322     VdbeFrame *pFrame;      /* Parent frame */
   310    323     int nFrame;             /* Number of frames in pFrame list */
   311         -  u8 noRecTrigger;        /* True to disable recursive triggers */
   312    324   };
   313    325   
   314    326   /*
   315    327   ** The following are allowed values for Vdbe.magic
   316    328   */
   317    329   #define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
   318    330   #define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */

Changes to src/vdbeaux.c.

   335    335   ** Return the address of the next instruction to be inserted.
   336    336   */
   337    337   int sqlite3VdbeCurrentAddr(Vdbe *p){
   338    338     assert( p->magic==VDBE_MAGIC_INIT );
   339    339     return p->nOp;
   340    340   }
   341    341   
          342  +/*
          343  +** This function returns a pointer to the array of opcodes associated with
          344  +** the Vdbe passed as the first argument. It is the callers responsibility
          345  +** to arrange for the returned array to be eventually freed using the 
          346  +** vdbeFreeOpArray() function.
          347  +**
          348  +** Before returning, *pnOp is set to the number of entries in the returned
          349  +** array. Also, *pnMaxArg is set to the larger of its current value and 
          350  +** the number of entries in the Vdbe.apArg[] array required to execute the 
          351  +** returned program.
          352  +*/
   342    353   VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
   343    354     VdbeOp *aOp = p->aOp;
   344    355     assert( aOp && !p->db->mallocFailed );
          356  +
          357  +  /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
          358  +  assert( p->aMutex.nMutex==0 );
          359  +
   345    360     resolveP2Values(p, pnMaxArg);
   346    361     *pnOp = p->nOp;
   347    362     p->aOp = 0;
   348    363     return aOp;
   349    364   }
   350    365   
   351    366   /*
................................................................................
   495    510           sqlite3VdbeProgramDelete(db, (SubProgram *)p4, 1);
   496    511           break;
   497    512         }
   498    513       }
   499    514     }
   500    515   }
   501    516   
          517  +/*
          518  +** Free the space allocated for aOp and any p4 values allocated for the
          519  +** opcodes contained within. If aOp is not NULL it is assumed to contain 
          520  +** nOp entries. 
          521  +*/
   502    522   static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
   503    523     if( aOp ){
   504    524       Op *pOp;
   505    525       for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
   506    526         freeP4(db, pOp->p4type, pOp->p4.p);
   507    527   #ifdef SQLITE_DEBUG
   508    528         sqlite3DbFree(db, pOp->zComment);
   509    529   #endif     
   510    530       }
   511    531     }
   512    532     sqlite3DbFree(db, aOp);
   513    533   }
   514    534   
          535  +/*
          536  +** Decrement the ref-count on the SubProgram structure passed as the
          537  +** second argument. If the ref-count reaches zero, free the structure.
          538  +**
          539  +** The array of VDBE opcodes stored as SubProgram.aOp is freed if
          540  +** either the ref-count reaches zero or parameter freeop is non-zero.
          541  +**
          542  +** Since the array of opcodes pointed to by SubProgram.aOp may directly
          543  +** or indirectly contain a reference to the SubProgram structure itself.
          544  +** By passing a non-zero freeop parameter, the caller may ensure that all
          545  +** SubProgram structures and their aOp arrays are freed, even when there
          546  +** are such circular references.
          547  +*/
   515    548   void sqlite3VdbeProgramDelete(sqlite3 *db, SubProgram *p, int freeop){
   516    549     if( p ){
   517    550       assert( p->nRef>0 );
   518    551       if( freeop || p->nRef==1 ){
   519    552         Op *aOp = p->aOp;
   520    553         p->aOp = 0;
   521    554         vdbeFreeOpArray(db, aOp, p->nOp);
................................................................................
   811    844     assert( zP4!=0 );
   812    845     return zP4;
   813    846   }
   814    847   #endif
   815    848   
   816    849   /*
   817    850   ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
   818         -**
   819    851   */
   820    852   void sqlite3VdbeUsesBtree(Vdbe *p, int i){
   821    853     int mask;
   822    854     assert( i>=0 && i<p->db->nDb && i<sizeof(u32)*8 );
   823    855     assert( i<(int)sizeof(p->btreeMask)*8 );
   824    856     mask = ((u32)1)<<i;
   825    857     if( (p->btreeMask & mask)==0 ){
................................................................................
   883    915   
   884    916         p->flags = MEM_Null;
   885    917       }
   886    918       db->mallocFailed = malloc_failed;
   887    919     }
   888    920   }
   889    921   
          922  +/*
          923  +** Delete a VdbeFrame object and its contents. VdbeFrame objects are
          924  +** allocated by the OP_Program opcode in sqlite3VdbeExec().
          925  +*/
   890    926   void sqlite3VdbeFrameDelete(VdbeFrame *p){
   891    927     int i;
   892    928     Mem *aMem = VdbeFrameMem(p);
   893    929     VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
   894    930     for(i=0; i<p->nChildCsr; i++){
   895    931       sqlite3VdbeFreeCursor(p->v, apCsr[i]);
   896    932     }
................................................................................
  1330   1366     }
  1331   1367   #endif
  1332   1368     if( !pCx->ephemPseudoTable ){
  1333   1369       sqlite3DbFree(p->db, pCx->pData);
  1334   1370     }
  1335   1371   }
  1336   1372   
         1373  +/*
         1374  +** Copy the values stored in the VdbeFrame structure to its Vdbe. This
         1375  +** is used, for example, when a trigger sub-program is halted to restore
         1376  +** control to the main program.
         1377  +*/
  1337   1378   int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
  1338   1379     Vdbe *v = pFrame->v;
  1339   1380     v->aOp = pFrame->aOp;
  1340   1381     v->nOp = pFrame->nOp;
  1341   1382     v->aMem = pFrame->aMem;
  1342   1383     v->nMem = pFrame->nMem;
  1343   1384     v->apCsr = pFrame->apCsr;

Changes to src/vtab.c.

   937    937   /*
   938    938   ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
   939    939   ** array so that an OP_VBegin will get generated for it.  Add pTab to the
   940    940   ** array if it is missing.  If pTab is already in the array, this routine
   941    941   ** is a no-op.
   942    942   */
   943    943   void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
          944  +  Parse *pToplevel = sqlite3ParseToplevel(pParse);
   944    945     int i, n;
   945    946     Table **apVtabLock;
   946         -  Parse *pRoot = (pParse->pRoot ? pParse->pRoot : pParse);
   947    947   
   948    948     assert( IsVirtual(pTab) );
   949         -  for(i=0; i<pRoot->nVtabLock; i++){
   950         -    if( pTab==pRoot->apVtabLock[i] ) return;
          949  +  for(i=0; i<pToplevel->nVtabLock; i++){
          950  +    if( pTab==pToplevel->apVtabLock[i] ) return;
   951    951     }
   952         -  n = (pRoot->nVtabLock+1)*sizeof(pRoot->apVtabLock[0]);
   953         -  apVtabLock = sqlite3_realloc(pRoot->apVtabLock, n);
          952  +  n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
          953  +  apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
   954    954     if( apVtabLock ){
   955         -    pRoot->apVtabLock = apVtabLock;
   956         -    pRoot->apVtabLock[pRoot->nVtabLock++] = pTab;
          955  +    pToplevel->apVtabLock = apVtabLock;
          956  +    pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
   957    957     }else{
   958         -    pRoot->db->mallocFailed = 1;
          958  +    pToplevel->db->mallocFailed = 1;
   959    959     }
   960    960   }
   961    961   
   962    962   #endif /* SQLITE_OMIT_VIRTUALTABLE */

Changes to tool/vdbe-compress.tcl.

    91     91     }
    92     92     if {[regexp "^\175" $line]} {
    93     93       append afterUnion $line\n
    94     94       set vlist {}
    95     95     } elseif {[llength $vlist]>0} {
    96     96       append line " "
    97     97       foreach v $vlist {
           98  +      regsub -all "(\[^a-zA-Z0-9>.\])${v}(\\W)" $line "\\1u.$sname.$v\\2" line
    98     99         regsub -all "(\[^a-zA-Z0-9>.\])${v}(\\W)" $line "\\1u.$sname.$v\\2" line
    99    100       }
   100    101       append afterUnion [string trimright $line]\n
   101    102     } elseif {$line=="" && [eof stdin]} {
   102    103       # no-op
   103    104     } else {
   104    105       append afterUnion $line\n