/ Check-in [c1b388c3]
Login

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

Overview
Comment:Merge in changes to support recursive invocation of triggers (disabled by default).
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1: c1b388c30de1b660c56afbcac9c69700500808a9
User & Date: dan 2009-09-01 16:39:06
Context
2009-09-01
17:11
Change "PRAGMA disable_recursive_triggers" to "PRAGMA recursive_triggers". Also a fix for compiling with OMIT_TRIGGER defined. check-in: e016cca3 user: dan tags: trunk
16:39
Merge in changes to support recursive invocation of triggers (disabled by default). check-in: c1b388c3 user: dan tags: trunk
16:19
Add new test script triggerC.test. check-in: a2a062a4 user: dan tags: trunk
2009-08-31
16:09
More thorough initialization of a buffer when writing the rollback journal header, in order to prevent a harmless valgrind warning. CVSTrac ticket #4039 check-in: 5e2f5496 user: drh tags: trunk
Changes
Hide Diffs Side-by-Side Diffs Ignore Whitespace Patch

Changes to src/alter.c.

   192    192     ** expression being built up in zWhere.
   193    193     */
   194    194     if( pTab->pSchema!=pTempSchema ){
   195    195       sqlite3 *db = pParse->db;
   196    196       for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
   197    197         if( pTrig->pSchema==pTempSchema ){
   198    198           if( !zWhere ){
   199         -          zWhere = sqlite3MPrintf(db, "name=%Q", pTrig->name);
          199  +          zWhere = sqlite3MPrintf(db, "name=%Q", pTrig->zName);
   200    200           }else{
   201    201             tmp = zWhere;
   202         -          zWhere = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, pTrig->name);
          202  +          zWhere = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, pTrig->zName);
   203    203             sqlite3DbFree(db, tmp);
   204    204           }
   205    205         }
   206    206       }
   207    207     }
   208    208     return zWhere;
   209    209   }
................................................................................
   231    231     assert( iDb>=0 );
   232    232   
   233    233   #ifndef SQLITE_OMIT_TRIGGER
   234    234     /* Drop any table triggers from the internal schema. */
   235    235     for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
   236    236       int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
   237    237       assert( iTrigDb==iDb || iTrigDb==1 );
   238         -    sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->name, 0);
          238  +    sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
   239    239     }
   240    240   #endif
   241    241   
   242    242     /* Drop the table and index from the internal schema */
   243    243     sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
   244    244   
   245    245     /* Reload the table, index and permanent trigger schemas. */

Changes to src/auth.c.

   109    109     sqlite3 *db = pParse->db;
   110    110     int rc;
   111    111     Table *pTab = 0;      /* The table being read */
   112    112     const char *zCol;     /* Name of the column of the table */
   113    113     int iSrc;             /* Index in pTabList->a[] of table being read */
   114    114     const char *zDBase;   /* Name of database being accessed */
   115    115     int iDb;              /* The index of the database the expression refers to */
          116  +  int iCol;             /* Index of column in table */
   116    117   
   117    118     if( db->xAuth==0 ) return;
   118         -  assert( pExpr->op==TK_COLUMN );
   119    119     iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
   120    120     if( iDb<0 ){
   121    121       /* An attempt to read a column out of a subquery or other
   122    122       ** temporary table. */
   123    123       return;
   124    124     }
   125         -  if( pTabList ){
          125  +
          126  +  assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
          127  +  if( pExpr->op==TK_TRIGGER ){
          128  +    pTab = pParse->pTriggerTab;
          129  +  }else{
          130  +    assert( pTabList );
   126    131       for(iSrc=0; iSrc<pTabList->nSrc; iSrc++){
   127    132         if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
   128    133           pTab = pTabList->a[iSrc].pTab;
   129         -	break;
          134  +        break;
   130    135         }
   131    136       }
   132    137     }
   133         -  if( !pTab ){
   134         -    TriggerStack *pStack = pParse->trigStack;
   135         -    if( ALWAYS(pStack) ){
   136         -      /* This must be an attempt to read the NEW or OLD pseudo-tables
   137         -      ** of a trigger.  */
   138         -      assert( pExpr->iTable==pStack->newIdx || pExpr->iTable==pStack->oldIdx );
   139         -      pTab = pStack->pTab;
   140         -    }
   141         -  }
          138  +  iCol = pExpr->iColumn;
   142    139     if( NEVER(pTab==0) ) return;
   143         -  if( pExpr->iColumn>=0 ){
   144         -    assert( pExpr->iColumn<pTab->nCol );
   145         -    zCol = pTab->aCol[pExpr->iColumn].zName;
          140  +
          141  +  if( iCol>=0 ){
          142  +    assert( iCol<pTab->nCol );
          143  +    zCol = pTab->aCol[iCol].zName;
   146    144     }else if( pTab->iPKey>=0 ){
   147    145       assert( pTab->iPKey<pTab->nCol );
   148    146       zCol = pTab->aCol[pTab->iPKey].zName;
   149    147     }else{
   150    148       zCol = "ROWID";
   151    149     }
   152    150     assert( iDb>=0 && iDb<db->nDb );

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

Changes to src/delete.c.

   224    224     int end, addr = 0;     /* A couple addresses of generated code */
   225    225     int i;                 /* Loop counter */
   226    226     WhereInfo *pWInfo;     /* Information about the WHERE clause */
   227    227     Index *pIdx;           /* For looping over indices of the table */
   228    228     int iCur;              /* VDBE Cursor number for pTab */
   229    229     sqlite3 *db;           /* Main database structure */
   230    230     AuthContext sContext;  /* Authorization context */
   231         -  int oldIdx = -1;       /* Cursor for the OLD table of AFTER triggers */
   232    231     NameContext sNC;       /* Name context to resolve expressions in */
   233    232     int iDb;               /* Database number */
   234    233     int memCnt = -1;       /* Memory cell used for change counting */
   235    234     int rcauth;            /* Value returned by authorization callback */
   236    235   
   237    236   #ifndef SQLITE_OMIT_TRIGGER
   238    237     int isView;                  /* True if attempting to delete from a view */
   239    238     Trigger *pTrigger;           /* List of table triggers, if required */
   240    239   #endif
   241         -  int iBeginAfterTrigger = 0;  /* Address of after trigger program */
   242         -  int iEndAfterTrigger = 0;    /* Exit of after trigger program */
   243         -  int iBeginBeforeTrigger = 0; /* Address of before trigger program */
   244         -  int iEndBeforeTrigger = 0;   /* Exit of before trigger program */
   245         -  u32 old_col_mask = 0;        /* Mask of OLD.* columns in use */
   246    240   
   247    241     memset(&sContext, 0, sizeof(sContext));
   248    242     db = pParse->db;
   249    243     if( pParse->nErr || db->mallocFailed ){
   250    244       goto delete_from_cleanup;
   251    245     }
   252    246     assert( pTabList->nSrc==1 );
................................................................................
   289    283     rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
   290    284     assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
   291    285     if( rcauth==SQLITE_DENY ){
   292    286       goto delete_from_cleanup;
   293    287     }
   294    288     assert(!isView || pTrigger);
   295    289   
   296         -  /* Allocate a cursor used to store the old.* data for a trigger.
   297         -  */
   298         -  if( pTrigger ){ 
   299         -    oldIdx = pParse->nTab++;
   300         -  }
   301         -
   302    290     /* Assign  cursor number to the table and all its indices.
   303    291     */
   304    292     assert( pTabList->nSrc==1 );
   305    293     iCur = pTabList->a[0].iCursor = pParse->nTab++;
   306    294     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   307    295       pParse->nTab++;
   308    296     }
................................................................................
   318    306     v = sqlite3GetVdbe(pParse);
   319    307     if( v==0 ){
   320    308       goto delete_from_cleanup;
   321    309     }
   322    310     if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
   323    311     sqlite3BeginWriteOperation(pParse, (pTrigger?1:0), iDb);
   324    312   
   325         -  if( pTrigger ){
   326         -    int orconf = ((pParse->trigStack)?pParse->trigStack->orconf:OE_Default);
   327         -    int iGoto = sqlite3VdbeAddOp0(v, OP_Goto);
   328         -    addr = sqlite3VdbeMakeLabel(v);
   329         -
   330         -    iBeginBeforeTrigger = sqlite3VdbeCurrentAddr(v);
   331         -    (void)sqlite3CodeRowTrigger(pParse, pTrigger, TK_DELETE, 0, 
   332         -        TRIGGER_BEFORE, pTab, -1, oldIdx, orconf, addr, &old_col_mask, 0);
   333         -    iEndBeforeTrigger = sqlite3VdbeAddOp0(v, OP_Goto);
   334         -
   335         -    iBeginAfterTrigger = sqlite3VdbeCurrentAddr(v);
   336         -    (void)sqlite3CodeRowTrigger(pParse, pTrigger, TK_DELETE, 0, 
   337         -        TRIGGER_AFTER, pTab, -1, oldIdx, orconf, addr, &old_col_mask, 0);
   338         -    iEndAfterTrigger = sqlite3VdbeAddOp0(v, OP_Goto);
   339         -
   340         -    sqlite3VdbeJumpHere(v, iGoto);
   341         -  }
   342         -
   343    313     /* If we are trying to delete from a view, realize that view into
   344    314     ** a ephemeral table.
   345    315     */
   346    316   #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
   347    317     if( isView ){
   348    318       sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
   349    319     }
................................................................................
   381    351       }
   382    352     }else
   383    353   #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
   384    354     /* The usual case: There is a WHERE clause so we have to scan through
   385    355     ** the table and pick which records to delete.
   386    356     */
   387    357     {
   388         -    int iRowid = ++pParse->nMem;    /* Used for storing rowid values. */
   389    358       int iRowSet = ++pParse->nMem;   /* Register for rowset of rows to delete */
          359  +    int iRowid = ++pParse->nMem;    /* Used for storing rowid values. */
          360  +    int regOld = pParse->nMem + 1;  /* Start of array for old.* (if triggers) */
   390    361       int regRowid;                   /* Actual register containing rowids */
   391    362   
   392    363       /* Collect rowids of every row to be deleted.
   393    364       */
   394    365       sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
   395    366       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0,WHERE_DUPLICATES_OK);
   396    367       if( pWInfo==0 ) goto delete_from_cleanup;
................................................................................
   397    368       regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid, 0);
   398    369       sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
   399    370       if( db->flags & SQLITE_CountRows ){
   400    371         sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
   401    372       }
   402    373       sqlite3WhereEnd(pWInfo);
   403    374   
   404         -    /* Open the pseudo-table used to store OLD if there are triggers.
   405         -    */
   406         -    if( pTrigger ){
   407         -      sqlite3VdbeAddOp3(v, OP_OpenPseudo, oldIdx, 0, pTab->nCol);
   408         -    }
   409         -
   410    375       /* Delete every item whose key was written to the list during the
   411    376       ** database scan.  We have to delete items after the scan is complete
   412         -    ** because deleting an item can change the scan order.
   413         -    */
          377  +    ** because deleting an item can change the scan order.  */
   414    378       end = sqlite3VdbeMakeLabel(v);
   415    379   
          380  +    /* Unless this is a view, open cursors for the table we are 
          381  +    ** deleting from and all its indices. If this is a view, then the
          382  +    ** only effect this statement has is to fire the INSTEAD OF 
          383  +    ** triggers.  */
   416    384       if( !isView ){
   417         -      /* Open cursors for the table we are deleting from and 
   418         -      ** all its indices.
   419         -      */
   420    385         sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
   421    386       }
   422    387   
   423         -    /* This is the beginning of the delete loop. If a trigger encounters
   424         -    ** an IGNORE constraint, it jumps back to here.
   425         -    */
   426         -    if( pTrigger ){
   427         -      sqlite3VdbeResolveLabel(v, addr);
   428         -    }
   429    388       addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
   430    389   
          390  +    /* If there are triggers, populate an array of registers with the
          391  +    ** data required by the old.* references in the trigger bodies.  */
   431    392       if( pTrigger ){
   432         -      int iData = ++pParse->nMem;   /* For storing row data of OLD table */
          393  +      u32 mask = 0;         /* Mask of OLD.* columns in use */
          394  +      pParse->nMem += pTab->nCol;
          395  +
          396  +      /* Open the pseudo-table used to store OLD if there are triggers. */
          397  +      mask = sqlite3TriggerOldmask(
          398  +          pParse, pTrigger, TK_DELETE, 0, pTab, OE_Default);
   433    399   
   434    400         /* If the record is no longer present in the table, jump to the
   435    401         ** next iteration of the loop through the contents of the fifo.
   436    402         */
   437    403         sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, iRowid);
   438    404   
   439    405         /* Populate the OLD.* pseudo-table */
   440         -      if( old_col_mask ){
   441         -        sqlite3VdbeAddOp2(v, OP_RowData, iCur, iData);
   442         -      }else{
   443         -        sqlite3VdbeAddOp2(v, OP_Null, 0, iData);
          406  +      assert( regOld==iRowid+1 );
          407  +      for(i=0; i<pTab->nCol; i++){
          408  +        if( mask==0xffffffff || mask&(1<<i) ){
          409  +          sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regOld+i);
          410  +          sqlite3ColumnDefault(v, pTab, i, regOld+i);
          411  +        }
   444    412         }
   445         -      sqlite3VdbeAddOp3(v, OP_Insert, oldIdx, iData, iRowid);
          413  +      sqlite3VdbeAddOp2(v, OP_Affinity, regOld, pTab->nCol);
          414  +      sqlite3TableAffinityStr(v, pTab);
   446    415   
   447         -      /* Jump back and run the BEFORE triggers */
   448         -      sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginBeforeTrigger);
   449         -      sqlite3VdbeJumpHere(v, iEndBeforeTrigger);
          416  +      sqlite3CodeRowTrigger(pParse, pTrigger, 
          417  +          TK_DELETE, 0, TRIGGER_BEFORE, pTab, -1, iRowid, OE_Default, addr
          418  +      );
   450    419       }
   451    420   
   452    421       if( !isView ){
   453    422         /* Delete the row */
   454    423   #ifndef SQLITE_OMIT_VIRTUALTABLE
   455    424         if( IsVirtual(pTab) ){
   456    425           const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
................................................................................
   459    428         }else
   460    429   #endif
   461    430         {
   462    431           sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, pParse->nested==0);
   463    432         }
   464    433       }
   465    434   
   466         -    /* If there are row triggers, close all cursors then invoke
   467         -    ** the AFTER triggers
   468         -    */
   469         -    if( pTrigger ){
   470         -      /* Jump back and run the AFTER triggers */
   471         -      sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginAfterTrigger);
   472         -      sqlite3VdbeJumpHere(v, iEndAfterTrigger);
   473         -    }
          435  +    /* Code the AFTER triggers. This is a no-op if there are no triggers. */
          436  +    sqlite3CodeRowTrigger(pParse, 
          437  +      pTrigger, TK_DELETE, 0, TRIGGER_AFTER, pTab, -1, iRowid, OE_Default, addr
          438  +    );
   474    439   
   475    440       /* End of the delete loop */
   476    441       sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
   477    442       sqlite3VdbeResolveLabel(v, end);
   478    443   
   479         -    /* Close the cursors after the loop if there are no row triggers */
   480         -    if( !isView  && !IsVirtual(pTab) ){
          444  +    /* Close the cursors open on the table and its indexes. */
          445  +    if( !isView && !IsVirtual(pTab) ){
   481    446         for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
   482    447           sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
   483    448         }
   484    449         sqlite3VdbeAddOp1(v, OP_Close, iCur);
   485    450       }
   486    451     }
   487    452   
   488    453     /* Update the sqlite_sequence table by storing the content of the
   489    454     ** maximum rowid counter values recorded while inserting into
   490    455     ** autoincrement tables.
   491    456     */
   492         -  if( pParse->nested==0 && pParse->trigStack==0 ){
          457  +  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
   493    458       sqlite3AutoincrementEnd(pParse);
   494    459     }
   495    460   
   496    461     /*
   497    462     ** Return the number of rows that were deleted. If this routine is 
   498    463     ** generating code because of a call to sqlite3NestedParse(), do not
   499    464     ** invoke the callback function.
   500    465     */
   501         -  if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
          466  +  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
   502    467       sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
   503    468       sqlite3VdbeSetNumCols(v, 1);
   504    469       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
   505    470     }
   506    471   
   507    472   delete_from_cleanup:
   508    473     sqlite3AuthContextPop(&sContext);

Changes to src/expr.c.

    86     86     CollSeq *pColl = 0;
    87     87     Expr *p = pExpr;
    88     88     while( ALWAYS(p) ){
    89     89       int op;
    90     90       pColl = p->pColl;
    91     91       if( pColl ) break;
    92     92       op = p->op;
    93         -    if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER) && p->pTab!=0 ){
           93  +    if( p->pTab!=0 && (
           94  +        op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER || op==TK_TRIGGER
           95  +    )){
    94     96         /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
    95     97         ** a TK_COLUMN but was previously evaluated and cached in a register */
    96     98         const char *zColl;
    97     99         int j = p->iColumn;
    98    100         if( j>=0 ){
    99    101           sqlite3 *db = pParse->db;
   100    102           zColl = p->pTab->aCol[j].zColl;
................................................................................
  1392   1394       ** has already been allocated. So assume sqlite3GetVdbe() is always
  1393   1395       ** successful here.
  1394   1396       */
  1395   1397       assert(v);
  1396   1398       if( iCol<0 ){
  1397   1399         int iMem = ++pParse->nMem;
  1398   1400         int iAddr;
  1399         -      sqlite3VdbeUsesBtree(v, iDb);
  1400   1401   
  1401   1402         iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
  1402   1403         sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
  1403   1404   
  1404   1405         sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  1405   1406         eType = IN_INDEX_ROWID;
  1406   1407   
................................................................................
  1426   1427            && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
  1427   1428           ){
  1428   1429             int iMem = ++pParse->nMem;
  1429   1430             int iAddr;
  1430   1431             char *pKey;
  1431   1432     
  1432   1433             pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
  1433         -          iDb = sqlite3SchemaToIndex(db, pIdx->pSchema);
  1434         -          sqlite3VdbeUsesBtree(v, iDb);
  1435         -
  1436   1434             iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
  1437   1435             sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
  1438   1436     
  1439   1437             sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
  1440   1438                                  pKey,P4_KEYINFO_HANDOFF);
  1441   1439             VdbeComment((v, "%s", pIdx->zName));
  1442   1440             eType = IN_INDEX_INDEX;
................................................................................
  1517   1515     **    *  The right-hand side is a correlated subquery
  1518   1516     **    *  The right-hand side is an expression list containing variables
  1519   1517     **    *  We are inside a trigger
  1520   1518     **
  1521   1519     ** If all of the above are false, then we can run this code just once
  1522   1520     ** save the results, and reuse the same result on subsequent invocations.
  1523   1521     */
  1524         -  if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->trigStack ){
         1522  +  if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->pTriggerTab ){
  1525   1523       int mem = ++pParse->nMem;
  1526   1524       sqlite3VdbeAddOp1(v, OP_If, mem);
  1527   1525       testAddr = sqlite3VdbeAddOp2(v, OP_Integer, 1, mem);
  1528   1526       assert( testAddr>0 || pParse->db->mallocFailed );
  1529   1527     }
  1530   1528   
  1531   1529     switch( pExpr->op ){
................................................................................
  2551   2549         sqlite3ReleaseTempReg(pParse, r4);
  2552   2550         break;
  2553   2551       }
  2554   2552       case TK_UPLUS: {
  2555   2553         inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  2556   2554         break;
  2557   2555       }
         2556  +
         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  +      */
         2583  +      Table *pTab = pExpr->pTab;
         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);
         2592  +      VdbeComment((v, "%s.%s -> $%d",
         2593  +        (pExpr->iTable ? "new" : "old"),
         2594  +        (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
         2595  +        target
         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.  */
         2600  +      if( pExpr->iColumn>=0 
         2601  +       && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
         2602  +      ){
         2603  +        sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
         2604  +      }
         2605  +      break;
         2606  +    }
         2607  +
  2558   2608   
  2559   2609       /*
  2560   2610       ** Form A:
  2561   2611       **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  2562   2612       **
  2563   2613       ** Form B:
  2564   2614       **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
................................................................................
  2636   2686         assert( db->mallocFailed || pParse->nErr>0 
  2637   2687              || pParse->iCacheLevel==iCacheLevel );
  2638   2688         sqlite3VdbeResolveLabel(v, endLabel);
  2639   2689         break;
  2640   2690       }
  2641   2691   #ifndef SQLITE_OMIT_TRIGGER
  2642   2692       case TK_RAISE: {
  2643         -      if( !pParse->trigStack ){
         2693  +      int vrc;
         2694  +      if( !pParse->pTriggerTab ){
  2644   2695           sqlite3ErrorMsg(pParse,
  2645   2696                          "RAISE() may only be used within a trigger-program");
  2646   2697           return 0;
  2647   2698         }
  2648         -      if( pExpr->affinity!=OE_Ignore ){
  2649         -         assert( pExpr->affinity==OE_Rollback ||
  2650         -                 pExpr->affinity == OE_Abort ||
  2651         -                 pExpr->affinity == OE_Fail );
  2652         -         assert( !ExprHasProperty(pExpr, EP_IntValue) );
  2653         -         sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, pExpr->affinity, 0,
  2654         -                           pExpr->u.zToken, 0);
  2655         -      } else {
  2656         -         assert( pExpr->affinity == OE_Ignore );
  2657         -         sqlite3VdbeAddOp2(v, OP_ContextPop, 0, 0);
  2658         -         sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->trigStack->ignoreJump);
  2659         -         VdbeComment((v, "raise(IGNORE)"));
  2660         -      }
         2699  +      assert( pExpr->affinity==OE_Rollback 
         2700  +           || pExpr->affinity==OE_Abort
         2701  +           || pExpr->affinity==OE_Fail
         2702  +           || pExpr->affinity==OE_Ignore
         2703  +      );
         2704  +      assert( !ExprHasProperty(pExpr, EP_IntValue) );
         2705  +      vrc = (pExpr->affinity==OE_Ignore ? SQLITE_OK : SQLITE_CONSTRAINT);
         2706  +      sqlite3VdbeAddOp4(v, OP_Halt, vrc, pExpr->affinity, 0, pExpr->u.zToken,0);
  2661   2707         break;
  2662   2708       }
  2663   2709   #endif
  2664   2710     }
  2665   2711     sqlite3ReleaseTempReg(pParse, regFree1);
  2666   2712     sqlite3ReleaseTempReg(pParse, regFree2);
  2667   2713     return inReg;

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 *pToplevel = sqlite3ParseToplevel(pParse);
   200    201       AutoincInfo *pInfo;
   201    202   
   202         -    pInfo = pParse->pAinc;
          203  +    pInfo = pToplevel->pAinc;
   203    204       while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
   204    205       if( pInfo==0 ){
   205    206         pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
   206    207         if( pInfo==0 ) return 0;
   207         -      pInfo->pNext = pParse->pAinc;
   208         -      pParse->pAinc = pInfo;
          208  +      pInfo->pNext = pToplevel->pAinc;
          209  +      pToplevel->pAinc = pInfo;
   209    210         pInfo->pTab = pTab;
   210    211         pInfo->iDb = iDb;
   211         -      pParse->nMem++;                  /* Register to hold name of table */
   212         -      pInfo->regCtr = ++pParse->nMem;  /* Max rowid register */
   213         -      pParse->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 */
   214    215       }
   215    216       memId = pInfo->regCtr;
   216    217     }
   217    218     return memId;
   218    219   }
   219    220   
   220    221   /*
................................................................................
   224    225   void sqlite3AutoincrementBegin(Parse *pParse){
   225    226     AutoincInfo *p;            /* Information about an AUTOINCREMENT */
   226    227     sqlite3 *db = pParse->db;  /* The database connection */
   227    228     Db *pDb;                   /* Database only autoinc table */
   228    229     int memId;                 /* Register holding max rowid */
   229    230     int addr;                  /* A VDBE address */
   230    231     Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
          232  +
          233  +  /* If currently generating a trigger program, this call is a no-op */
          234  +  if( pParse->pTriggerTab ) return;
   231    235   
   232    236     assert( v );   /* We failed long ago if this is not so */
   233    237     for(p = pParse->pAinc; p; p = p->pNext){
   234    238       pDb = &db->aDb[p->iDb];
   235    239       memId = p->regCtr;
   236    240       sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
   237    241       addr = sqlite3VdbeCurrentAddr(v);
................................................................................
   446    450     int endOfLoop;        /* Label for the end of the insertion loop */
   447    451     int useTempTable = 0; /* Store SELECT results in intermediate table */
   448    452     int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
   449    453     int addrInsTop = 0;   /* Jump to label "D" */
   450    454     int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
   451    455     int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
   452    456     SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
   453         -  int newIdx = -1;      /* Cursor for the NEW pseudo-table */
   454    457     int iDb;              /* Index of database holding TABLE */
   455    458     Db *pDb;              /* The database containing table being inserted into */
   456    459     int appendFlag = 0;   /* True if the insert is likely to be an append */
   457    460   
   458    461     /* Register allocations */
   459    462     int regFromSelect = 0;/* Base register for data coming from SELECT */
   460    463     int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
................................................................................
   461    464     int regRowCount = 0;  /* Memory cell used for the row counter */
   462    465     int regIns;           /* Block of regs holding rowid+data being inserted */
   463    466     int regRowid;         /* registers holding insert rowid */
   464    467     int regData;          /* register holding first column to insert */
   465    468     int regRecord;        /* Holds the assemblied row record */
   466    469     int regEof = 0;       /* Register recording end of SELECT data */
   467    470     int *aRegIdx = 0;     /* One register allocated to each index */
   468         -
   469    471   
   470    472   #ifndef SQLITE_OMIT_TRIGGER
   471    473     int isView;                 /* True if attempting to insert into a view */
   472    474     Trigger *pTrigger;          /* List of triggers on pTab, if required */
   473    475     int tmask;                  /* Mask of trigger times */
   474    476   #endif
   475    477   
................................................................................
   532    534     /* Allocate a VDBE
   533    535     */
   534    536     v = sqlite3GetVdbe(pParse);
   535    537     if( v==0 ) goto insert_cleanup;
   536    538     if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
   537    539     sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
   538    540   
   539         -  /* if there are row triggers, allocate a temp table for new.* references. */
   540         -  if( pTrigger ){
   541         -    newIdx = pParse->nTab++;
   542         -  }
   543         -
   544    541   #ifndef SQLITE_OMIT_XFER_OPT
   545    542     /* If the statement is of the form
   546    543     **
   547    544     **       INSERT INTO <table1> SELECT * FROM <table2>;
   548    545     **
   549    546     ** Then special optimizations can be applied that make the transfer
   550    547     ** very fast and which reduce fragmentation of indices.
................................................................................
   740    737     /* If there is no IDLIST term but the table has an integer primary
   741    738     ** key, the set the keyColumn variable to the primary key column index
   742    739     ** in the original table definition.
   743    740     */
   744    741     if( pColumn==0 && nColumn>0 ){
   745    742       keyColumn = pTab->iPKey;
   746    743     }
   747         -
   748         -  /* Open the temp table for FOR EACH ROW triggers
   749         -  */
   750         -  if( pTrigger ){
   751         -    sqlite3VdbeAddOp3(v, OP_OpenPseudo, newIdx, 0, pTab->nCol);
   752         -  }
   753    744       
   754    745     /* Initialize the count of rows to be inserted
   755    746     */
   756    747     if( db->flags & SQLITE_CountRows ){
   757    748       regRowCount = ++pParse->nMem;
   758    749       sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
   759    750     }
................................................................................
   812    803     }
   813    804     regData = regRowid+1;
   814    805   
   815    806     /* Run the BEFORE and INSTEAD OF triggers, if there are any
   816    807     */
   817    808     endOfLoop = sqlite3VdbeMakeLabel(v);
   818    809     if( tmask & TRIGGER_BEFORE ){
   819         -    int regTrigRowid;
   820         -    int regCols;
   821         -    int regRec;
          810  +    int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
   822    811   
   823    812       /* build the NEW.* reference row.  Note that if there is an INTEGER
   824    813       ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
   825    814       ** translated into a unique ID for the row.  But on a BEFORE trigger,
   826    815       ** we do not know what the unique ID will be (because the insert has
   827    816       ** not happened yet) so we substitute a rowid of -1
   828    817       */
   829         -    regTrigRowid = sqlite3GetTempReg(pParse);
   830    818       if( keyColumn<0 ){
   831         -      sqlite3VdbeAddOp2(v, OP_Integer, -1, regTrigRowid);
          819  +      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
   832    820       }else{
   833    821         int j1;
   834    822         if( useTempTable ){
   835         -        sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regTrigRowid);
          823  +        sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
   836    824         }else{
   837    825           assert( pSelect==0 );  /* Otherwise useTempTable is true */
   838         -        sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regTrigRowid);
          826  +        sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
   839    827         }
   840         -      j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regTrigRowid);
   841         -      sqlite3VdbeAddOp2(v, OP_Integer, -1, regTrigRowid);
          828  +      j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
          829  +      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
   842    830         sqlite3VdbeJumpHere(v, j1);
   843         -      sqlite3VdbeAddOp1(v, OP_MustBeInt, regTrigRowid);
          831  +      sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
   844    832       }
   845    833   
   846    834       /* Cannot have triggers on a virtual table. If it were possible,
   847    835       ** this block would have to account for hidden column.
   848    836       */
   849         -    assert(!IsVirtual(pTab));
          837  +    assert( !IsVirtual(pTab) );
   850    838   
   851    839       /* Create the new column data
   852    840       */
   853         -    regCols = sqlite3GetTempRange(pParse, pTab->nCol);
   854    841       for(i=0; i<pTab->nCol; i++){
   855    842         if( pColumn==0 ){
   856    843           j = i;
   857    844         }else{
   858    845           for(j=0; j<pColumn->nId; j++){
   859    846             if( pColumn->a[j].idx==i ) break;
   860    847           }
   861    848         }
   862    849         if( pColumn && j>=pColumn->nId ){
   863         -        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i);
          850  +        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
   864    851         }else if( useTempTable ){
   865         -        sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i); 
          852  +        sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1); 
   866    853         }else{
   867    854           assert( pSelect==0 ); /* Otherwise useTempTable is true */
   868         -        sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i);
          855  +        sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
   869    856         }
   870    857       }
   871         -    regRec = sqlite3GetTempReg(pParse);
   872         -    sqlite3VdbeAddOp3(v, OP_MakeRecord, regCols, pTab->nCol, regRec);
   873    858   
   874    859       /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
   875    860       ** do not attempt any conversions before assembling the record.
   876    861       ** If this is a real table, attempt conversions as required by the
   877    862       ** table column affinities.
   878    863       */
   879    864       if( !isView ){
          865  +      sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
   880    866         sqlite3TableAffinityStr(v, pTab);
   881    867       }
   882         -    sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regTrigRowid);
   883         -    sqlite3ReleaseTempReg(pParse, regRec);
   884         -    sqlite3ReleaseTempReg(pParse, regTrigRowid);
   885         -    sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol);
   886    868   
   887    869       /* Fire BEFORE or INSTEAD OF triggers */
   888         -    if( sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, 
   889         -        pTab, newIdx, -1, onError, endOfLoop, 0, 0) ){
   890         -      goto insert_cleanup;
   891         -    }
          870  +    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, 
          871  +        pTab, -1, regCols-pTab->nCol-1, onError, endOfLoop);
          872  +
          873  +    sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
   892    874     }
   893    875   
   894    876     /* Push the record number for the new entry onto the stack.  The
   895    877     ** record number is a randomly generate integer created by NewRowid
   896    878     ** except when the table has an INTEGER PRIMARY KEY column, in which
   897    879     ** case the record number is the same as that column. 
   898    880     */
................................................................................
   991    973   #endif
   992    974       {
   993    975         int isReplace;    /* Set to true if constraints may cause a replace */
   994    976         sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
   995    977             keyColumn>=0, 0, onError, endOfLoop, &isReplace
   996    978         );
   997    979         sqlite3CompleteInsertion(
   998         -          pParse, pTab, baseCur, regIns, aRegIdx, 0,
   999         -          (tmask&TRIGGER_AFTER) ? newIdx : -1, appendFlag, isReplace==0
          980  +          pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
  1000    981         );
  1001    982       }
  1002    983     }
  1003    984   
  1004    985     /* Update the count of rows that are inserted
  1005    986     */
  1006    987     if( (db->flags & SQLITE_CountRows)!=0 ){
  1007    988       sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  1008    989     }
  1009    990   
  1010    991     if( pTrigger ){
  1011    992       /* Code AFTER triggers */
  1012         -    if( sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, 
  1013         -          pTab, newIdx, -1, onError, endOfLoop, 0, 0) ){
  1014         -      goto insert_cleanup;
  1015         -    }
          993  +    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, 
          994  +        pTab, -1, regData-2-pTab->nCol, onError, endOfLoop);
  1016    995     }
  1017    996   
  1018    997     /* The bottom of the main insertion loop, if the data source
  1019    998     ** is a SELECT statement.
  1020    999     */
  1021   1000     sqlite3VdbeResolveLabel(v, endOfLoop);
  1022   1001     if( useTempTable ){
................................................................................
  1037   1016     }
  1038   1017   
  1039   1018   insert_end:
  1040   1019     /* Update the sqlite_sequence table by storing the content of the
  1041   1020     ** maximum rowid counter values recorded while inserting into
  1042   1021     ** autoincrement tables.
  1043   1022     */
  1044         -  if( pParse->nested==0 && pParse->trigStack==0 ){
         1023  +  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  1045   1024       sqlite3AutoincrementEnd(pParse);
  1046   1025     }
  1047   1026   
  1048   1027     /*
  1049   1028     ** Return the number of rows inserted. If this routine is 
  1050   1029     ** generating code because of a call to sqlite3NestedParse(), do not
  1051   1030     ** invoke the callback function.
  1052   1031     */
  1053         -  if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
         1032  +  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
  1054   1033       sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  1055   1034       sqlite3VdbeSetNumCols(v, 1);
  1056   1035       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
  1057   1036     }
  1058   1037   
  1059   1038   insert_cleanup:
  1060   1039     sqlite3SrcListDelete(db, pTabList);
................................................................................
  1065   1044   }
  1066   1045   
  1067   1046   /*
  1068   1047   ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
  1069   1048   **
  1070   1049   ** The input is a range of consecutive registers as follows:
  1071   1050   **
  1072         -**    1.  The rowid of the row to be updated before the update.  This
  1073         -**        value is omitted unless we are doing an UPDATE that involves a
  1074         -**        change to the record number or writing to a virtual table.
         1051  +**    1.  The rowid of the row after the update.
  1075   1052   **
  1076         -**    2.  The rowid of the row after the update.
  1077         -**
  1078         -**    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.
  1079   1054   **
  1080   1055   **    i.  Data from middle columns...
  1081   1056   **
  1082   1057   **    N.  The data in the last column of the entry after the update.
  1083   1058   **
  1084         -** The regRowid parameter is the index of the register containing (2).
         1059  +** The regRowid parameter is the index of the register containing (1).
  1085   1060   **
  1086         -** The old rowid shown as entry (1) above is omitted unless both isUpdate
  1087         -** and rowidChng are 1.  isUpdate is true for UPDATEs and false for
  1088         -** INSERTs.  RowidChng means that the new rowid is explicitly specified by
  1089         -** the update or insert statement.  If rowidChng is false, it means that
  1090         -** the rowid is computed automatically in an insert or that the rowid value
  1091         -** 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.
  1092   1069   **
  1093   1070   ** The code generated by this routine store new index entries into
  1094   1071   ** registers identified by aRegIdx[].  No index entry is created for
  1095   1072   ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
  1096   1073   ** the same as the order of indices on the linked list of indices
  1097   1074   ** attached to the table.
  1098   1075   **
................................................................................
  1159   1136     int onError;        /* Conflict resolution strategy */
  1160   1137     int j1;             /* Addresss of jump instruction */
  1161   1138     int j2 = 0, j3;     /* Addresses of jump instructions */
  1162   1139     int regData;        /* Register containing first data column */
  1163   1140     int iCur;           /* Table cursor number */
  1164   1141     Index *pIdx;         /* Pointer to one of the indices */
  1165   1142     int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
  1166         -  int hasTwoRowids = (isUpdate && rowidChng);
         1143  +  int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
  1167   1144   
  1168   1145     v = sqlite3GetVdbe(pParse);
  1169   1146     assert( v!=0 );
  1170   1147     assert( pTab->pSelect==0 );  /* This table is not a VIEW */
  1171   1148     nCol = pTab->nCol;
  1172   1149     regData = regRowid + 1;
  1173         -
  1174   1150   
  1175   1151     /* Test all NOT NULL constraints.
  1176   1152     */
  1177   1153     for(i=0; i<nCol; i++){
  1178   1154       if( i==pTab->iPKey ){
  1179   1155         continue;
  1180   1156       }
................................................................................
  1243   1219         onError = overrideError;
  1244   1220       }else if( onError==OE_Default ){
  1245   1221         onError = OE_Abort;
  1246   1222       }
  1247   1223       
  1248   1224       if( onError!=OE_Replace || pTab->pIndex ){
  1249   1225         if( isUpdate ){
  1250         -        j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, regRowid-1);
         1226  +        j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
  1251   1227         }
  1252   1228         j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
  1253   1229         switch( onError ){
  1254   1230           default: {
  1255   1231             onError = OE_Abort;
  1256   1232             /* Fall thru into the next case */
  1257   1233           }
................................................................................
  1320   1296         if( onError==OE_Ignore ) onError = OE_Replace;
  1321   1297         else if( onError==OE_Fail ) onError = OE_Abort;
  1322   1298       }
  1323   1299       
  1324   1300   
  1325   1301       /* Check to see if the new index entry will be unique */
  1326   1302       regR = sqlite3GetTempReg(pParse);
  1327         -    sqlite3VdbeAddOp2(v, OP_SCopy, regRowid-hasTwoRowids, regR);
         1303  +    sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
  1328   1304       j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
  1329   1305                              regR, SQLITE_INT_TO_PTR(regIdx),
  1330   1306                              P4_INT32);
  1331   1307       sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
  1332   1308   
  1333   1309       /* Generate code that executes if the new index entry is not unique */
  1334   1310       assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
................................................................................
  1391   1367   void sqlite3CompleteInsertion(
  1392   1368     Parse *pParse,      /* The parser context */
  1393   1369     Table *pTab,        /* the table into which we are inserting */
  1394   1370     int baseCur,        /* Index of a read/write cursor pointing at pTab */
  1395   1371     int regRowid,       /* Range of content */
  1396   1372     int *aRegIdx,       /* Register used by each index.  0 for unused indices */
  1397   1373     int isUpdate,       /* True for UPDATE, False for INSERT */
  1398         -  int newIdx,         /* Index of NEW table for triggers.  -1 if none */
  1399   1374     int appendBias,     /* True if this is likely to be an append */
  1400   1375     int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
  1401   1376   ){
  1402   1377     int i;
  1403   1378     Vdbe *v;
  1404   1379     int nIdx;
  1405   1380     Index *pIdx;
................................................................................
  1419   1394       }
  1420   1395     }
  1421   1396     regData = regRowid + 1;
  1422   1397     regRec = sqlite3GetTempReg(pParse);
  1423   1398     sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
  1424   1399     sqlite3TableAffinityStr(v, pTab);
  1425   1400     sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
  1426         -#ifndef SQLITE_OMIT_TRIGGER
  1427         -  if( newIdx>=0 ){
  1428         -    sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regRowid);
  1429         -  }
  1430         -#endif
  1431   1401     if( pParse->nested ){
  1432   1402       pik_flags = 0;
  1433   1403     }else{
  1434   1404       pik_flags = OPFLAG_NCHANGE;
  1435   1405       pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
  1436   1406     }
  1437   1407     if( appendBias ){

Changes to src/main.c.

  1586   1586     db->nextPagesize = 0;
  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  +#endif
         1594  +#if 1 || defined(SQLITE_DISABLE_RECURSIVE_TRIGGERS)
         1595  +                 | SQLITE_NoRecTriggers
  1593   1596   #endif
  1594   1597         ;
  1595   1598     sqlite3HashInit(&db->aCollSeq);
  1596   1599   #ifndef SQLITE_OMIT_VIRTUALTABLE
  1597   1600     sqlite3HashInit(&db->aModule);
  1598   1601   #endif
  1599   1602   

Changes to src/pragma.c.

   186    186       /* The following is VERY experimental */
   187    187       { "writable_schema",          SQLITE_WriteSchema|SQLITE_RecoveryMode },
   188    188       { "omit_readlock",            SQLITE_NoReadlock    },
   189    189   
   190    190       /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
   191    191       ** flag if there are any active statements. */
   192    192       { "read_uncommitted",         SQLITE_ReadUncommitted },
          193  +    { "disable_recursive_triggers", SQLITE_NoRecTriggers },
   193    194     };
   194    195     int i;
   195    196     const struct sPragmaType *p;
   196    197     for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
   197    198       if( sqlite3StrICmp(zLeft, p->zName)==0 ){
   198    199         sqlite3 *db = pParse->db;
   199    200         Vdbe *v;

Changes to src/prepare.c.

   671    671   
   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  +
          679  +  /* Delete any TriggerPrg structures allocated while parsing this statement. */
          680  +  while( pParse->pTriggerPrg ){
          681  +    TriggerPrg *pT = pParse->pTriggerPrg;
          682  +    pParse->pTriggerPrg = pT->pNext;
          683  +    sqlite3VdbeProgramDelete(db, pT->pProgram, 0);
          684  +    sqlite3DbFree(db, pT);
          685  +  }
   678    686   
   679    687   end_prepare:
   680    688   
   681    689     sqlite3StackFree(db, pParse);
   682    690     rc = sqlite3ApiExit(db, rc);
   683    691     assert( (rc&db->errMask)==rc );
   684    692     return rc;

Changes to src/resolve.c.

   133    133     int cnt = 0;                      /* Number of matching column names */
   134    134     int cntTab = 0;                   /* Number of matching table names */
   135    135     sqlite3 *db = pParse->db;         /* The database connection */
   136    136     struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
   137    137     struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
   138    138     NameContext *pTopNC = pNC;        /* First namecontext in the list */
   139    139     Schema *pSchema = 0;              /* Schema of the expression */
          140  +  int isTrigger = 0;
   140    141   
   141    142     assert( pNC );     /* the name context cannot be NULL. */
   142    143     assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
   143    144     assert( ~ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
   144    145   
   145    146     /* Initialize the node to no-match */
   146    147     pExpr->iTable = -1;
................................................................................
   218    219         }
   219    220       }
   220    221   
   221    222   #ifndef SQLITE_OMIT_TRIGGER
   222    223       /* If we have not already resolved the name, then maybe 
   223    224       ** it is a new.* or old.* trigger argument reference
   224    225       */
   225         -    if( zDb==0 && zTab!=0 && cnt==0 && pParse->trigStack!=0 ){
   226         -      TriggerStack *pTriggerStack = pParse->trigStack;
          226  +    if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
          227  +      int op = pParse->eTriggerOp;
   227    228         Table *pTab = 0;
   228         -      u32 *piColMask = 0;
   229         -      if( pTriggerStack->newIdx != -1 && sqlite3StrICmp("new", zTab) == 0 ){
   230         -        pExpr->iTable = pTriggerStack->newIdx;
   231         -        assert( pTriggerStack->pTab );
   232         -        pTab = pTriggerStack->pTab;
   233         -        piColMask = &(pTriggerStack->newColMask);
   234         -      }else if( pTriggerStack->oldIdx != -1 && sqlite3StrICmp("old", zTab)==0 ){
   235         -        pExpr->iTable = pTriggerStack->oldIdx;
   236         -        assert( pTriggerStack->pTab );
   237         -        pTab = pTriggerStack->pTab;
   238         -        piColMask = &(pTriggerStack->oldColMask);
          229  +      assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
          230  +      if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
          231  +        pExpr->iTable = 1;
          232  +        pTab = pParse->pTriggerTab;
          233  +      }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
          234  +        pExpr->iTable = 0;
          235  +        pTab = pParse->pTriggerTab;
   239    236         }
   240    237   
   241    238         if( pTab ){ 
   242    239           int iCol;
   243         -        Column *pCol = pTab->aCol;
   244         -
   245    240           pSchema = pTab->pSchema;
   246    241           cntTab++;
   247         -        for(iCol=0; iCol < pTab->nCol; iCol++, pCol++) {
   248         -          if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
   249         -            cnt++;
   250         -            pExpr->iColumn = iCol==pTab->iPKey ? -1 : (i16)iCol;
   251         -            pExpr->pTab = pTab;
          242  +        if( sqlite3IsRowid(zCol) ){
          243  +          iCol = -1;
          244  +        }else{
          245  +          for(iCol=0; iCol<pTab->nCol; iCol++){
          246  +            Column *pCol = &pTab->aCol[iCol];
          247  +            if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
          248  +              if( iCol==pTab->iPKey ){
          249  +                iCol = -1;
          250  +              }
          251  +              break;
          252  +            }
          253  +          }
          254  +        }
          255  +        if( iCol<pTab->nCol ){
          256  +          cnt++;
          257  +          if( iCol<0 ){
          258  +            pExpr->affinity = SQLITE_AFF_INTEGER;
          259  +          }else if( pExpr->iTable==0 ){
   252    260               testcase( iCol==31 );
   253    261               testcase( iCol==32 );
   254         -            if( iCol>=32 ){
   255         -              *piColMask = 0xffffffff;
   256         -            }else{
   257         -              *piColMask |= ((u32)1)<<iCol;
   258         -            }
   259         -            break;
          262  +            pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
   260    263             }
          264  +          pExpr->iColumn = iCol;
          265  +          pExpr->pTab = pTab;
          266  +          isTrigger = 1;
   261    267           }
   262    268         }
   263    269       }
   264    270   #endif /* !defined(SQLITE_OMIT_TRIGGER) */
   265    271   
   266    272       /*
   267    273       ** Perhaps the name is a reference to the ROWID
................................................................................
   365    371   
   366    372     /* Clean up and return
   367    373     */
   368    374     sqlite3ExprDelete(db, pExpr->pLeft);
   369    375     pExpr->pLeft = 0;
   370    376     sqlite3ExprDelete(db, pExpr->pRight);
   371    377     pExpr->pRight = 0;
   372         -  pExpr->op = TK_COLUMN;
          378  +  pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
   373    379   lookupname_end:
   374    380     if( cnt==1 ){
   375    381       assert( pNC!=0 );
   376    382       sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
   377    383       /* Increment the nRef value on all name contexts from TopNC up to
   378    384       ** the point where the name matched. */
   379    385       for(;;){

Changes to src/select.c.

  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   2736       if( pTabToDel->nRef==1 ){
  2737         -      pTabToDel->pNextZombie = pParse->pZombieTab;
  2738         -      pParse->pZombieTab = pTabToDel;
         2737  +      Parse *pToplevel = sqlite3ParseToplevel(pParse);
         2738  +      pTabToDel->pNextZombie = pToplevel->pZombieTab;
         2739  +      pToplevel->pZombieTab = pTabToDel;
  2739   2740       }else{
  2740   2741         pTabToDel->nRef--;
  2741   2742       }
  2742   2743       pSubitem->pTab = 0;
  2743   2744     }
  2744   2745   
  2745   2746     /* The following loop runs once for each term in a compound-subquery

Changes to src/sqliteInt.h.

   607    607   typedef struct Savepoint Savepoint;
   608    608   typedef struct Select Select;
   609    609   typedef struct SrcList SrcList;
   610    610   typedef struct StrAccum StrAccum;
   611    611   typedef struct Table Table;
   612    612   typedef struct TableLock TableLock;
   613    613   typedef struct Token Token;
   614         -typedef struct TriggerStack TriggerStack;
          614  +typedef struct TriggerPrg TriggerPrg;
   615    615   typedef struct TriggerStep TriggerStep;
   616    616   typedef struct Trigger Trigger;
   617    617   typedef struct UnpackedRecord UnpackedRecord;
   618    618   typedef struct VTable VTable;
   619    619   typedef struct Walker Walker;
   620    620   typedef struct WherePlan WherePlan;
   621    621   typedef struct WhereInfo WhereInfo;
................................................................................
   907    907   #define SQLITE_ReadUncommitted 0x00004000 /* For shared-cache mode */
   908    908   #define SQLITE_LegacyFileFmt  0x00008000  /* Create new databases in format 1 */
   909    909   #define SQLITE_FullFSync      0x00010000  /* Use full fsync on the backend */
   910    910   #define SQLITE_LoadExtension  0x00020000  /* Enable load_extension */
   911    911   
   912    912   #define SQLITE_RecoveryMode   0x00040000  /* Ignore schema errors */
   913    913   #define SQLITE_ReverseOrder   0x00100000  /* Reverse unordered SELECTs */
          914  +#define SQLITE_NoRecTriggers  0x00200000  /* Disable recursive triggers */
   914    915   
   915    916   /*
   916    917   ** Possible values for the sqlite.magic field.
   917    918   ** The numbers are obtained at random and have no special meaning, other
   918    919   ** than being distinct from one another.
   919    920   */
   920    921   #define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
................................................................................
  1572   1573   
  1573   1574     /* If the EP_Reduced flag is set in the Expr.flags mask, then no
  1574   1575     ** space is allocated for the fields below this point. An attempt to
  1575   1576     ** access them will result in a segfault or malfunction.
  1576   1577     *********************************************************************/
  1577   1578   
  1578   1579     int iTable;            /* TK_COLUMN: cursor number of table holding column
  1579         -                         ** TK_REGISTER: register number */
         1580  +                         ** TK_REGISTER: register number
         1581  +                         ** TK_TRIGGER: 1 -> new, 0 -> old */
  1580   1582     i16 iColumn;           /* TK_COLUMN: column index.  -1 for rowid */
  1581   1583     i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
  1582   1584     i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
  1583   1585     u8 flags2;             /* Second set of flags.  EP2_... */
  1584   1586     u8 op2;                /* If a TK_REGISTER, the original value of Expr.op */
  1585   1587     AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
  1586   1588     Table *pTab;           /* Table for TK_COLUMN expressions. */
................................................................................
  2011   2013   /*
  2012   2014   ** Size of the column cache
  2013   2015   */
  2014   2016   #ifndef SQLITE_N_COLCACHE
  2015   2017   # define SQLITE_N_COLCACHE 10
  2016   2018   #endif
  2017   2019   
         2020  +/*
         2021  +** At least one instance of the following structure is created for each 
         2022  +** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
         2023  +** statement. All such objects are stored in the linked list headed at
         2024  +** Parse.pTriggerPrg and deleted once statement compilation has been
         2025  +** completed.
         2026  +**
         2027  +** A Vdbe sub-program that implements the body and WHEN clause of trigger
         2028  +** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
         2029  +** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
         2030  +** The Parse.pTriggerPrg list never contains two entries with the same
         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).
         2036  +*/
         2037  +struct TriggerPrg {
         2038  +  Trigger *pTrigger;      /* Trigger this program was coded from */
         2039  +  int orconf;             /* Default ON CONFLICT policy */
         2040  +  SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
         2041  +  u32 oldmask;            /* Mask of old.* columns accessed */
         2042  +  TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
         2043  +};
         2044  +
  2018   2045   /*
  2019   2046   ** An SQL parser context.  A copy of this structure is passed through
  2020   2047   ** the parser and down into all the parser action routine in order to
  2021   2048   ** carry around information that is global to the entire parse.
  2022   2049   **
  2023   2050   ** The structure is divided into two parts.  When the parser and code
  2024   2051   ** generate call themselves recursively, the first part of the structure
................................................................................
  2071   2098   #ifndef SQLITE_OMIT_SHARED_CACHE
  2072   2099     int nTableLock;        /* Number of locks in aTableLock */
  2073   2100     TableLock *aTableLock; /* Required table locks for shared-cache mode */
  2074   2101   #endif
  2075   2102     int regRowid;        /* Register holding rowid of CREATE TABLE entry */
  2076   2103     int regRoot;         /* Register holding root page number for new objects */
  2077   2104     AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
         2105  +  int nMaxArg;         /* Max args passed to user function by sub-program */
         2106  +
         2107  +  /* Information used while coding trigger programs. */
         2108  +  Parse *pToplevel;    /* Parse structure for main program (or NULL) */
         2109  +  Table *pTriggerTab;  /* Table triggers are being coded for */
         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 */
  2078   2113   
  2079   2114     /* Above is constant between recursions.  Below is reset before and after
  2080   2115     ** each recursion */
  2081   2116   
  2082   2117     int nVar;            /* Number of '?' variables seen in the SQL so far */
  2083   2118     int nVarExpr;        /* Number of used slots in apVarExpr[] */
  2084   2119     int nVarExprAlloc;   /* Number of allocated slots in apVarExpr[] */
................................................................................
  2088   2123     int *aAlias;         /* Register used to hold aliased result */
  2089   2124     u8 explain;          /* True if the EXPLAIN flag is found on the query */
  2090   2125     Token sNameToken;    /* Token with unqualified schema object name */
  2091   2126     Token sLastToken;    /* The last token parsed */
  2092   2127     const char *zTail;   /* All SQL text past the last semicolon parsed */
  2093   2128     Table *pNewTable;    /* A table being constructed by CREATE TABLE */
  2094   2129     Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
  2095         -  TriggerStack *trigStack;  /* Trigger actions being coded */
  2096   2130     const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
  2097   2131   #ifndef SQLITE_OMIT_VIRTUALTABLE
  2098   2132     Token sArg;                /* Complete text of a module argument */
  2099   2133     u8 declareVtab;            /* True if inside sqlite3_declare_vtab() */
  2100   2134     int nVtabLock;             /* Number of virtual tables to lock */
  2101   2135     Table **apVtabLock;        /* Pointer to virtual tables needing locking */
  2102   2136   #endif
  2103   2137     int nHeight;            /* Expression tree height of current sub-select */
  2104   2138     Table *pZombieTab;      /* List of Table objects to delete after code gen */
         2139  +  TriggerPrg *pTriggerPrg;    /* Linked list of coded triggers */
  2105   2140   };
  2106   2141   
  2107   2142   #ifdef SQLITE_OMIT_VIRTUALTABLE
  2108   2143     #define IN_DECLARE_VTAB 0
  2109   2144   #else
  2110   2145     #define IN_DECLARE_VTAB (pParse->declareVtab)
  2111   2146   #endif
................................................................................
  2140   2175    *    linked list is stored as the "pTrigger" member of the associated
  2141   2176    *    struct Table.
  2142   2177    *
  2143   2178    * The "step_list" member points to the first element of a linked list
  2144   2179    * containing the SQL statements specified as the trigger program.
  2145   2180    */
  2146   2181   struct Trigger {
  2147         -  char *name;             /* The name of the trigger                        */
         2182  +  char *zName;            /* The name of the trigger                        */
  2148   2183     char *table;            /* The table or view to which the trigger applies */
  2149   2184     u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
  2150   2185     u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  2151   2186     Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
  2152   2187     IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
  2153   2188                                the <column-list> is stored here */
  2154   2189     Schema *pSchema;        /* Schema containing the trigger */
................................................................................
  2214   2249     Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
  2215   2250     ExprList *pExprList; /* SET clause for UPDATE.  VALUES clause for INSERT */
  2216   2251     IdList *pIdList;     /* Column names for INSERT */
  2217   2252     TriggerStep *pNext;  /* Next in the link-list */
  2218   2253     TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
  2219   2254   };
  2220   2255   
  2221         -/*
  2222         - * An instance of struct TriggerStack stores information required during code
  2223         - * generation of a single trigger program. While the trigger program is being
  2224         - * coded, its associated TriggerStack instance is pointed to by the
  2225         - * "pTriggerStack" member of the Parse structure.
  2226         - *
  2227         - * The pTab member points to the table that triggers are being coded on. The 
  2228         - * newIdx member contains the index of the vdbe cursor that points at the temp
  2229         - * table that stores the new.* references. If new.* references are not valid
  2230         - * for the trigger being coded (for example an ON DELETE trigger), then newIdx
  2231         - * is set to -1. The oldIdx member is analogous to newIdx, for old.* references.
  2232         - *
  2233         - * The ON CONFLICT policy to be used for the trigger program steps is stored 
  2234         - * as the orconf member. If this is OE_Default, then the ON CONFLICT clause 
  2235         - * specified for individual triggers steps is used.
  2236         - *
  2237         - * struct TriggerStack has a "pNext" member, to allow linked lists to be
  2238         - * constructed. When coding nested triggers (triggers fired by other triggers)
  2239         - * each nested trigger stores its parent trigger's TriggerStack as the "pNext" 
  2240         - * pointer. Once the nested trigger has been coded, the pNext value is restored
  2241         - * to the pTriggerStack member of the Parse stucture and coding of the parent
  2242         - * trigger continues.
  2243         - *
  2244         - * Before a nested trigger is coded, the linked list pointed to by the 
  2245         - * pTriggerStack is scanned to ensure that the trigger is not about to be coded
  2246         - * recursively. If this condition is detected, the nested trigger is not coded.
  2247         - */
  2248         -struct TriggerStack {
  2249         -  Table *pTab;         /* Table that triggers are currently being coded on */
  2250         -  int newIdx;          /* Index of vdbe cursor to "new" temp table */
  2251         -  int oldIdx;          /* Index of vdbe cursor to "old" temp table */
  2252         -  u32 newColMask;
  2253         -  u32 oldColMask;
  2254         -  int orconf;          /* Current orconf policy */
  2255         -  int ignoreJump;      /* where to jump to for a RAISE(IGNORE) */
  2256         -  Trigger *pTrigger;   /* The trigger currently being coded */
  2257         -  TriggerStack *pNext; /* Next trigger down on the trigger stack */
  2258         -};
  2259         -
  2260   2256   /*
  2261   2257   ** The following structure contains information used by the sqliteFix...
  2262   2258   ** routines as they walk the parse tree to make database references
  2263   2259   ** explicit.  
  2264   2260   */
  2265   2261   typedef struct DbFixer DbFixer;
  2266   2262   struct DbFixer {
................................................................................
  2647   2643   int sqlite3ExprIsInteger(Expr*, int*);
  2648   2644   int sqlite3IsRowid(const char*);
  2649   2645   void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int);
  2650   2646   void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
  2651   2647   int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
  2652   2648   void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
  2653   2649                                        int*,int,int,int,int,int*);
  2654         -void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int,int,int);
         2650  +void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
  2655   2651   int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
  2656   2652   void sqlite3BeginWriteOperation(Parse*, int, int);
  2657   2653   Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
  2658   2654   ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
  2659   2655   SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
  2660   2656   IdList *sqlite3IdListDup(sqlite3*,IdList*);
  2661   2657   Select *sqlite3SelectDup(sqlite3*,Select*,int);
................................................................................
  2683   2679     void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
  2684   2680                              Expr*,int, int);
  2685   2681     void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
  2686   2682     void sqlite3DropTrigger(Parse*, SrcList*, int);
  2687   2683     void sqlite3DropTriggerPtr(Parse*, Trigger*);
  2688   2684     Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
  2689   2685     Trigger *sqlite3TriggerList(Parse *, Table *);
  2690         -  int sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
  2691         -                            int, int, int, int, u32*, u32*);
         2686  +  void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
         2687  +                            int, int, int, int);
  2692   2688     void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
  2693   2689     void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
  2694   2690     TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
  2695   2691     TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
  2696   2692                                           ExprList*,Select*,u8);
  2697   2693     TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
  2698   2694     TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
  2699   2695     void sqlite3DeleteTrigger(sqlite3*, Trigger*);
  2700   2696     void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
         2697  +  u32 sqlite3TriggerOldmask(Parse*,Trigger*,int,ExprList*,Table*,int);
         2698  +# define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
  2701   2699   #else
  2702   2700   # define sqlite3TriggersExist(B,C,D,E,F) 0
  2703   2701   # define sqlite3DeleteTrigger(A,B)
  2704   2702   # define sqlite3DropTriggerPtr(A,B)
  2705   2703   # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
  2706         -# define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I,J,K,L) 0
         2704  +# define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I,J)
  2707   2705   # define sqlite3TriggerList(X, Y) 0
         2706  +# define sqlite3ParseToplevel(p) p
  2708   2707   #endif
  2709   2708   
  2710   2709   int sqlite3JoinType(Parse*, Token*, Token*, Token*);
  2711   2710   void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
  2712   2711   void sqlite3DeferForeignKey(Parse*, int);
  2713   2712   #ifndef SQLITE_OMIT_AUTHORIZATION
  2714   2713     void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);

Changes to src/trigger.c.

   215    215     if (tr_tm == TK_INSTEAD){
   216    216       tr_tm = TK_BEFORE;
   217    217     }
   218    218   
   219    219     /* Build the Trigger object */
   220    220     pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
   221    221     if( pTrigger==0 ) goto trigger_cleanup;
   222         -  pTrigger->name = zName;
          222  +  pTrigger->zName = zName;
   223    223     zName = 0;
   224    224     pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
   225    225     pTrigger->pSchema = db->aDb[iDb].pSchema;
   226    226     pTrigger->pTabSchema = pTab->pSchema;
   227    227     pTrigger->op = (u8)op;
   228    228     pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
   229    229     pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
................................................................................
   258    258     DbFixer sFix;
   259    259     int iDb;                                 /* Database containing the trigger */
   260    260     Token nameToken;           /* Trigger name for error reporting */
   261    261   
   262    262     pTrig = pParse->pNewTrigger;
   263    263     pParse->pNewTrigger = 0;
   264    264     if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
   265         -  zName = pTrig->name;
          265  +  zName = pTrig->zName;
   266    266     iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
   267    267     pTrig->step_list = pStepList;
   268    268     while( pStepList ){
   269    269       pStepList->pTrig = pTrig;
   270    270       pStepList = pStepList->pNext;
   271    271     }
   272         -  nameToken.z = pTrig->name;
          272  +  nameToken.z = pTrig->zName;
   273    273     nameToken.n = sqlite3Strlen30(nameToken.z);
   274    274     if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken) 
   275    275             && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
   276    276       goto triggerfinish_cleanup;
   277    277     }
   278    278   
   279    279     /* if we are not initializing, and this trigger is not on a TEMP table, 
................................................................................
   447    447   
   448    448   /* 
   449    449   ** Recursively delete a Trigger structure
   450    450   */
   451    451   void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
   452    452     if( pTrigger==0 ) return;
   453    453     sqlite3DeleteTriggerStep(db, pTrigger->step_list);
   454         -  sqlite3DbFree(db, pTrigger->name);
          454  +  sqlite3DbFree(db, pTrigger->zName);
   455    455     sqlite3DbFree(db, pTrigger->table);
   456    456     sqlite3ExprDelete(db, pTrigger->pWhen);
   457    457     sqlite3IdListDelete(db, pTrigger->pColumns);
   458    458     sqlite3DbFree(db, pTrigger);
   459    459   }
   460    460   
   461    461   /*
................................................................................
   527    527     assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
   528    528   #ifndef SQLITE_OMIT_AUTHORIZATION
   529    529     {
   530    530       int code = SQLITE_DROP_TRIGGER;
   531    531       const char *zDb = db->aDb[iDb].zName;
   532    532       const char *zTab = SCHEMA_TABLE(iDb);
   533    533       if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
   534         -    if( sqlite3AuthCheck(pParse, code, pTrigger->name, pTable->zName, zDb) ||
          534  +    if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
   535    535         sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
   536    536         return;
   537    537       }
   538    538     }
   539    539   #endif
   540    540   
   541    541     /* Generate code to destroy the database record of the trigger.
................................................................................
   554    554         { OP_Delete,     0, 0,        0},
   555    555         { OP_Next,       0, ADDR(1),  0}, /* 8 */
   556    556       };
   557    557   
   558    558       sqlite3BeginWriteOperation(pParse, 0, iDb);
   559    559       sqlite3OpenMasterTable(pParse, iDb);
   560    560       base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
   561         -    sqlite3VdbeChangeP4(v, base+1, pTrigger->name, 0);
          561  +    sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, 0);
   562    562       sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
   563    563       sqlite3ChangeCookie(pParse, iDb);
   564    564       sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
   565         -    sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->name, 0);
          565  +    sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
   566    566       if( pParse->nMem<3 ){
   567    567         pParse->nMem = 3;
   568    568       }
   569    569     }
   570    570   }
   571    571   
   572    572   /*
................................................................................
   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 * pTriggerStep = pStepList;
   678         -  int orconf;
          677  +  TriggerStep *pStep;
   679    678     Vdbe *v = pParse->pVdbe;
   680    679     sqlite3 *db = pParse->db;
   681    680   
   682         -  assert( pTriggerStep!=0 );
          681  +  assert( pParse->pTriggerTab && pParse->pToplevel );
          682  +  assert( pStepList );
   683    683     assert( v!=0 );
   684         -  sqlite3VdbeAddOp2(v, OP_ContextPush, 0, 0);
   685         -  VdbeComment((v, "begin trigger %s", pStepList->pTrig->name));
   686         -  while( pTriggerStep ){
   687         -    sqlite3ExprCacheClear(pParse);
   688         -    orconf = (orconfin == OE_Default)?pTriggerStep->orconf:orconfin;
   689         -    pParse->trigStack->orconf = orconf;
   690         -    switch( pTriggerStep->op ){
          684  +  for(pStep=pStepList; pStep; pStep=pStep->pNext){
          685  +    /* Figure out the ON CONFLICT policy that will be used for this step
          686  +    ** of the trigger program. If the statement that caused this trigger
          687  +    ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
          688  +    ** the ON CONFLICT policy that was specified as part of the trigger
          689  +    ** step statement. Example:
          690  +    **
          691  +    **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
          692  +    **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
          693  +    **   END;
          694  +    **
          695  +    **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
          696  +    **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
          697  +    */
          698  +    pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:orconf;
          699  +
          700  +    switch( pStep->op ){
   691    701         case TK_UPDATE: {
   692         -        SrcList *pSrc;
   693         -        pSrc = targetSrcList(pParse, pTriggerStep);
   694         -        sqlite3VdbeAddOp2(v, OP_ResetCount, 0, 0);
   695         -        sqlite3Update(pParse, pSrc,
   696         -                sqlite3ExprListDup(db, pTriggerStep->pExprList, 0), 
   697         -                sqlite3ExprDup(db, pTriggerStep->pWhere, 0), orconf);
   698         -        sqlite3VdbeAddOp2(v, OP_ResetCount, 1, 0);
          702  +        sqlite3Update(pParse, 
          703  +          targetSrcList(pParse, pStep),
          704  +          sqlite3ExprListDup(db, pStep->pExprList, 0), 
          705  +          sqlite3ExprDup(db, pStep->pWhere, 0), 
          706  +          pParse->eOrconf
          707  +        );
   699    708           break;
   700    709         }
   701    710         case TK_INSERT: {
   702         -        SrcList *pSrc;
   703         -        pSrc = targetSrcList(pParse, pTriggerStep);
   704         -        sqlite3VdbeAddOp2(v, OP_ResetCount, 0, 0);
   705         -        sqlite3Insert(pParse, pSrc,
   706         -          sqlite3ExprListDup(db, pTriggerStep->pExprList, 0), 
   707         -          sqlite3SelectDup(db, pTriggerStep->pSelect, 0), 
   708         -          sqlite3IdListDup(db, pTriggerStep->pIdList), orconf);
   709         -        sqlite3VdbeAddOp2(v, OP_ResetCount, 1, 0);
          711  +        sqlite3Insert(pParse, 
          712  +          targetSrcList(pParse, pStep),
          713  +          sqlite3ExprListDup(db, pStep->pExprList, 0), 
          714  +          sqlite3SelectDup(db, pStep->pSelect, 0), 
          715  +          sqlite3IdListDup(db, pStep->pIdList), 
          716  +          pParse->eOrconf
          717  +        );
   710    718           break;
   711    719         }
   712    720         case TK_DELETE: {
   713         -        SrcList *pSrc;
   714         -        sqlite3VdbeAddOp2(v, OP_ResetCount, 0, 0);
   715         -        pSrc = targetSrcList(pParse, pTriggerStep);
   716         -        sqlite3DeleteFrom(pParse, pSrc, 
   717         -                          sqlite3ExprDup(db, pTriggerStep->pWhere, 0));
   718         -        sqlite3VdbeAddOp2(v, OP_ResetCount, 1, 0);
          721  +        sqlite3DeleteFrom(pParse, 
          722  +          targetSrcList(pParse, pStep),
          723  +          sqlite3ExprDup(db, pStep->pWhere, 0)
          724  +        );
   719    725           break;
   720    726         }
   721         -      default: assert( pTriggerStep->op==TK_SELECT ); {
   722         -        Select *ss = sqlite3SelectDup(db, pTriggerStep->pSelect, 0);
   723         -        if( ss ){
   724         -          SelectDest dest;
   725         -
   726         -          sqlite3SelectDestInit(&dest, SRT_Discard, 0);
   727         -          sqlite3Select(pParse, ss, &dest);
   728         -          sqlite3SelectDelete(db, ss);
   729         -        }
          727  +      default: assert( pStep->op==TK_SELECT ); {
          728  +        SelectDest sDest;
          729  +        Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
          730  +        sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
          731  +        sqlite3Select(pParse, pSelect, &sDest);
          732  +        sqlite3SelectDelete(db, pSelect);
   730    733           break;
   731    734         }
   732    735       } 
   733         -    pTriggerStep = pTriggerStep->pNext;
          736  +    if( pStep->op!=TK_SELECT ){
          737  +      sqlite3VdbeAddOp1(v, OP_ResetCount, 1);
          738  +    }
   734    739     }
   735         -  sqlite3VdbeAddOp2(v, OP_ContextPop, 0, 0);
   736         -  VdbeComment((v, "end trigger %s", pStepList->pTrig->name));
   737    740   
   738    741     return 0;
   739    742   }
          743  +
          744  +#ifdef SQLITE_DEBUG
          745  +/*
          746  +** This function is used to add VdbeComment() annotations to a VDBE
          747  +** program. It is not used in production code, only for debugging.
          748  +*/
          749  +static const char *onErrorText(int onError){
          750  +  switch( onError ){
          751  +    case OE_Abort:    return "abort";
          752  +    case OE_Rollback: return "rollback";
          753  +    case OE_Fail:     return "fail";
          754  +    case OE_Replace:  return "replace";
          755  +    case OE_Ignore:   return "ignore";
          756  +    case OE_Default:  return "default";
          757  +  }
          758  +  return "n/a";
          759  +}
          760  +#endif
          761  +
          762  +/*
          763  +** Parse context structure pFrom has just been used to create a sub-vdbe
          764  +** (trigger program). If an error has occurred, transfer error information
          765  +** from pFrom to pTo.
          766  +*/
          767  +static void transferParseError(Parse *pTo, Parse *pFrom){
          768  +  assert( pFrom->zErrMsg==0 || pFrom->nErr );
          769  +  assert( pTo->zErrMsg==0 || pTo->nErr );
          770  +  if( pTo->nErr==0 ){
          771  +    pTo->zErrMsg = pFrom->zErrMsg;
          772  +    pTo->nErr = pFrom->nErr;
          773  +  }else{
          774  +    sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
          775  +  }
          776  +}
          777  +
          778  +/*
          779  +** Create and populate a new TriggerPrg object with a sub-program 
          780  +** implementing trigger pTrigger with ON CONFLICT policy orconf.
          781  +*/
          782  +static TriggerPrg *codeRowTrigger(
          783  +  Parse *pParse,       /* Current parse context */
          784  +  Trigger *pTrigger,   /* Trigger to code */
          785  +  Table *pTab,         /* The table pTrigger is attached to */
          786  +  int orconf           /* ON CONFLICT policy to code trigger program with */
          787  +){
          788  +  Parse *pTop = sqlite3ParseToplevel(pParse);
          789  +  sqlite3 *db = pParse->db;   /* Database handle */
          790  +  TriggerPrg *pPrg;           /* Value to return */
          791  +  Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
          792  +  Vdbe *v;                    /* Temporary VM */
          793  +  NameContext sNC;            /* Name context for sub-vdbe */
          794  +  SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
          795  +  Parse *pSubParse;           /* Parse context for sub-vdbe */
          796  +  int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
          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.  */
          803  +  pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
          804  +  if( !pPrg ) return 0;
          805  +  pPrg->pNext = pTop->pTriggerPrg;
          806  +  pTop->pTriggerPrg = pPrg;
          807  +  pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
          808  +  if( !pProgram ) return 0;
          809  +  pProgram->nRef = 1;
          810  +  pPrg->pTrigger = pTrigger;
          811  +  pPrg->orconf = orconf;
          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;
          817  +  memset(&sNC, 0, sizeof(sNC));
          818  +  sNC.pParse = pSubParse;
          819  +  pSubParse->db = db;
          820  +  pSubParse->pTriggerTab = pTab;
          821  +  pSubParse->pToplevel = pTop;
          822  +  pSubParse->zAuthContext = pTrigger->zName;
          823  +  pSubParse->eTriggerOp = pTrigger->op;
          824  +
          825  +  v = sqlite3GetVdbe(pSubParse);
          826  +  if( v ){
          827  +    VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)", 
          828  +      pTrigger->zName, onErrorText(orconf),
          829  +      (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
          830  +        (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
          831  +        (pTrigger->op==TK_INSERT ? "INSERT" : ""),
          832  +        (pTrigger->op==TK_DELETE ? "DELETE" : ""),
          833  +      pTab->zName
          834  +    ));
          835  +#ifndef SQLITE_OMIT_TRACE
          836  +    sqlite3VdbeChangeP4(v, -1, 
          837  +      sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
          838  +    );
          839  +#endif
          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.  */
          844  +    if( pTrigger->pWhen ){
          845  +      pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
          846  +      if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen) 
          847  +       && db->mallocFailed==0 
          848  +      ){
          849  +        iEndTrigger = sqlite3VdbeMakeLabel(v);
          850  +        sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
          851  +      }
          852  +      sqlite3ExprDelete(db, pWhen);
          853  +    }
          854  +
          855  +    /* Code the trigger program into the sub-vdbe. */
          856  +    codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
          857  +
          858  +    /* Insert an OP_Halt at the end of the sub-program. */
          859  +    if( iEndTrigger ){
          860  +      sqlite3VdbeResolveLabel(v, iEndTrigger);
          861  +    }
          862  +    sqlite3VdbeAddOp0(v, OP_Halt);
          863  +    VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
          864  +
          865  +    transferParseError(pParse, pSubParse);
          866  +    if( db->mallocFailed==0 ){
          867  +      pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
          868  +    }
          869  +    pProgram->nMem = pSubParse->nMem;
          870  +    pProgram->nCsr = pSubParse->nTab;
          871  +    pProgram->token = (void *)pTrigger;
          872  +    pPrg->oldmask = pSubParse->oldmask;
          873  +    sqlite3VdbeDelete(v);
          874  +  }
          875  +
          876  +  assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
          877  +  assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
          878  +  sqlite3StackFree(db, pSubParse);
          879  +
          880  +  return pPrg;
          881  +}
          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  +*/
          889  +static TriggerPrg *getRowTrigger(
          890  +  Parse *pParse,       /* Current parse context */
          891  +  Trigger *pTrigger,   /* Trigger to code */
          892  +  Table *pTab,         /* The table trigger pTrigger is attached to */
          893  +  int orconf           /* ON CONFLICT algorithm. */
          894  +){
          895  +  Parse *pRoot = sqlite3ParseToplevel(pParse);
          896  +  TriggerPrg *pPrg;
          897  +
          898  +  assert( pTab==tableOfTrigger(pTrigger) );
          899  +
          900  +  /* It may be that this trigger has already been coded (or is in the
          901  +  ** process of being coded). If this is the case, then an entry with
          902  +  ** a matching TriggerPrg.pTrigger field will be present somewhere
          903  +  ** in the Parse.pTriggerPrg list. Search for such an entry.  */
          904  +  for(pPrg=pRoot->pTriggerPrg; 
          905  +      pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf); 
          906  +      pPrg=pPrg->pNext
          907  +  );
          908  +
          909  +  /* If an existing TriggerPrg could not be located, create a new one. */
          910  +  if( !pPrg ){
          911  +    pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
          912  +  }
          913  +
          914  +  return pPrg;
          915  +}
   740    916   
   741    917   /*
   742    918   ** This is called to code FOR EACH ROW triggers.
   743    919   **
   744    920   ** When the code that this function generates is executed, the following 
   745    921   ** must be true:
   746    922   **
................................................................................
   761    937   ** are set to values that describe the columns used by the trigger program
   762    938   ** in the OLD.* and NEW.* tables respectively. If column N of the 
   763    939   ** pseudo-table is read at least once, the corresponding bit of the output
   764    940   ** mask is set. If a column with an index greater than 32 is read, the
   765    941   ** output mask is set to the special value 0xffffffff.
   766    942   **
   767    943   */
   768         -int sqlite3CodeRowTrigger(
          944  +void sqlite3CodeRowTrigger(
   769    945     Parse *pParse,       /* Parse context */
   770    946     Trigger *pTrigger,   /* List of triggers on table pTab */
   771    947     int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
   772    948     ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
   773    949     int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
   774    950     Table *pTab,         /* The table to code triggers from */
   775    951     int newIdx,          /* The indice of the "new" row to access */
   776    952     int oldIdx,          /* The indice of the "old" row to access */
   777    953     int orconf,          /* ON CONFLICT policy */
   778         -  int ignoreJump,      /* Instruction to jump to for RAISE(IGNORE) */
   779         -  u32 *piOldColMask,   /* OUT: Mask of columns used from the OLD.* table */
   780         -  u32 *piNewColMask    /* OUT: Mask of columns used from the NEW.* table */
          954  +  int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
   781    955   ){
   782    956     Trigger *p;
   783         -  sqlite3 *db = pParse->db;
   784         -  TriggerStack trigStackEntry;
   785         -
   786         -  trigStackEntry.oldColMask = 0;
   787         -  trigStackEntry.newColMask = 0;
   788    957   
   789    958     assert(op == TK_UPDATE || op == TK_INSERT || op == TK_DELETE);
   790    959     assert(tr_tm == TRIGGER_BEFORE || tr_tm == TRIGGER_AFTER );
   791    960   
   792         -  assert(newIdx != -1 || oldIdx != -1);
   793         -
   794    961     for(p=pTrigger; p; p=p->pNext){
   795         -    int fire_this = 0;
   796    962   
   797    963       /* Sanity checking:  The schema for the trigger and for the table are
   798    964       ** always defined.  The trigger must be in the same schema as the table
   799    965       ** or else it must be a TEMP trigger. */
   800    966       assert( p->pSchema!=0 );
   801    967       assert( p->pTabSchema!=0 );
   802         -    assert( p->pSchema==p->pTabSchema || p->pSchema==db->aDb[1].pSchema );
          968  +    assert( p->pSchema==p->pTabSchema 
          969  +         || p->pSchema==pParse->db->aDb[1].pSchema );
   803    970   
   804    971       /* Determine whether we should code this trigger */
   805         -    if( 
   806         -      p->op==op && 
   807         -      p->tr_tm==tr_tm && 
   808         -      checkColumnOverlap(p->pColumns,pChanges)
          972  +    if( p->op==op 
          973  +     && p->tr_tm==tr_tm 
          974  +     && checkColumnOverlap(p->pColumns,pChanges)
   809    975       ){
   810         -      TriggerStack *pS;      /* Pointer to trigger-stack entry */
   811         -      for(pS=pParse->trigStack; pS && p!=pS->pTrigger; pS=pS->pNext){}
   812         -      if( !pS ){
   813         -        fire_this = 1;
          976  +      Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
          977  +      TriggerPrg *pPrg;
          978  +      pPrg = getRowTrigger(pParse, p, pTab, orconf);
          979  +      assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
          980  +
          981  +      /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program 
          982  +      ** is a pointer to the sub-vdbe containing the trigger program.  */
          983  +      if( pPrg ){
          984  +        sqlite3VdbeAddOp3(v, OP_Program, oldIdx, ignoreJump, ++pParse->nMem);
          985  +        pPrg->pProgram->nRef++;
          986  +        sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
          987  +        VdbeComment((v, "Call: %s.%s", p->zName, onErrorText(orconf)));
   814    988         }
   815         -#if 0    /* Give no warning for recursive triggers.  Just do not do them */
   816         -      else{
   817         -        sqlite3ErrorMsg(pParse, "recursive triggers not supported (%s)",
   818         -            p->name);
   819         -        return SQLITE_ERROR;
   820         -      }
   821         -#endif
   822    989       }
   823         - 
   824         -    if( fire_this ){
   825         -      int endTrigger;
   826         -      Expr * whenExpr;
   827         -      AuthContext sContext;
   828         -      NameContext sNC;
          990  +  }
          991  +}
   829    992   
   830         -#ifndef SQLITE_OMIT_TRACE
   831         -      sqlite3VdbeAddOp4(pParse->pVdbe, OP_Trace, 0, 0, 0,
   832         -                        sqlite3MPrintf(db, "-- TRIGGER %s", p->name),
   833         -                        P4_DYNAMIC);
   834         -#endif
   835         -      memset(&sNC, 0, sizeof(sNC));
   836         -      sNC.pParse = pParse;
   837         -
   838         -      /* Push an entry on to the trigger stack */
   839         -      trigStackEntry.pTrigger = p;
   840         -      trigStackEntry.newIdx = newIdx;
   841         -      trigStackEntry.oldIdx = oldIdx;
   842         -      trigStackEntry.pTab = pTab;
   843         -      trigStackEntry.pNext = pParse->trigStack;
   844         -      trigStackEntry.ignoreJump = ignoreJump;
   845         -      pParse->trigStack = &trigStackEntry;
   846         -      sqlite3AuthContextPush(pParse, &sContext, p->name);
          993  +/*
          994  +** Triggers fired by UPDATE or DELETE statements may access values stored
          995  +** in the old.* pseudo-table. This function returns a 32-bit bitmask
          996  +** indicating which columns of the old.* table actually are used by
          997  +** triggers. This information may be used by the caller to avoid having
          998  +** to load the entire old.* record into memory when executing an UPDATE
          999  +** or DELETE command.
         1000  +**
         1001  +** Bit 0 of the returned mask is set if the left-most column of the
         1002  +** table may be accessed using an old.<col> reference. Bit 1 is set if
         1003  +** the second leftmost column value is required, and so on. If there
         1004  +** are more than 32 columns in the table, and at least one of the columns
         1005  +** with an index greater than 32 may be accessed, 0xffffffff is returned.
         1006  +**
         1007  +** It is not possible to determine if the old.rowid column is accessed
         1008  +** by triggers. The caller must always assume that it is.
         1009  +**
         1010  +** There is no equivalent function for new.* references.
         1011  +*/
         1012  +u32 sqlite3TriggerOldmask(
         1013  +  Parse *pParse,       /* Parse context */
         1014  +  Trigger *pTrigger,   /* List of triggers on table pTab */
         1015  +  int op,              /* Either TK_UPDATE or TK_DELETE */
         1016  +  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
         1017  +  Table *pTab,         /* The table to code triggers from */
         1018  +  int orconf           /* Default ON CONFLICT policy for trigger steps */
         1019  +){
         1020  +  u32 mask = 0;
         1021  +  Trigger *p;
   847   1022   
   848         -      /* code the WHEN clause */
   849         -      endTrigger = sqlite3VdbeMakeLabel(pParse->pVdbe);
   850         -      whenExpr = sqlite3ExprDup(db, p->pWhen, 0);
   851         -      if( db->mallocFailed || sqlite3ResolveExprNames(&sNC, whenExpr) ){
   852         -        pParse->trigStack = trigStackEntry.pNext;
   853         -        sqlite3ExprDelete(db, whenExpr);
   854         -        return 1;
         1023  +  assert(op==TK_UPDATE || op==TK_DELETE);
         1024  +  for(p=pTrigger; p; p=p->pNext){
         1025  +    if( p->op==op && checkColumnOverlap(p->pColumns,pChanges) ){
         1026  +      TriggerPrg *pPrg;
         1027  +      pPrg = getRowTrigger(pParse, p, pTab, orconf);
         1028  +      if( pPrg ){
         1029  +        mask |= pPrg->oldmask;
   855   1030         }
   856         -      sqlite3ExprIfFalse(pParse, whenExpr, endTrigger, SQLITE_JUMPIFNULL);
   857         -      sqlite3ExprDelete(db, whenExpr);
   858         -
   859         -      sqlite3ExprCachePush(pParse);
   860         -      codeTriggerProgram(pParse, p->step_list, orconf); 
   861         -      sqlite3ExprCachePop(pParse, 1);
   862         -
   863         -      /* Pop the entry off the trigger stack */
   864         -      pParse->trigStack = trigStackEntry.pNext;
   865         -      sqlite3AuthContextPop(&sContext);
   866         -
   867         -      sqlite3VdbeResolveLabel(pParse->pVdbe, endTrigger);
   868   1031       }
   869   1032     }
   870         -  if( piOldColMask ) *piOldColMask |= trigStackEntry.oldColMask;
   871         -  if( piNewColMask ) *piNewColMask |= trigStackEntry.newColMask;
   872         -  return 0;
         1033  +
         1034  +  return mask;
   873   1035   }
         1036  +
   874   1037   #endif /* !defined(SQLITE_OMIT_TRIGGER) */

Changes to src/update.c.

   116    116     int j1;                /* Addresses of jump instructions */
   117    117     int okOnePass;         /* True for one-pass algorithm without the FIFO */
   118    118   
   119    119   #ifndef SQLITE_OMIT_TRIGGER
   120    120     int isView;                  /* Trying to update a view */
   121    121     Trigger *pTrigger;           /* List of triggers on pTab, if required */
   122    122   #endif
   123         -  int iBeginAfterTrigger = 0;  /* Address of after trigger program */
   124         -  int iEndAfterTrigger = 0;    /* Exit of after trigger program */
   125         -  int iBeginBeforeTrigger = 0; /* Address of before trigger program */
   126         -  int iEndBeforeTrigger = 0;   /* Exit of before trigger program */
   127         -  u32 old_col_mask = 0;        /* Mask of OLD.* columns in use */
   128         -  u32 new_col_mask = 0;        /* Mask of NEW.* columns in use */
   129         -
   130         -  int newIdx      = -1;  /* index of trigger "new" temp table       */
   131         -  int oldIdx      = -1;  /* index of trigger "old" temp table       */
          123  +  u32 oldmask = 0;        /* Mask of OLD.* columns in use */
   132    124   
   133    125     /* Register Allocations */
   134    126     int regRowCount = 0;   /* A count of rows changed */
   135    127     int regOldRowid;       /* The old rowid */
   136    128     int regNewRowid;       /* The new rowid */
   137         -  int regData;           /* New data for the row */
          129  +  int regNew;
          130  +  int regOld;
   138    131     int regRowSet = 0;     /* Rowset of rows to be updated */
          132  +  int regRec;            /* Register used for new table record to insert */
   139    133   
   140    134     memset(&sContext, 0, sizeof(sContext));
   141    135     db = pParse->db;
   142    136     if( pParse->nErr || db->mallocFailed ){
   143    137       goto update_cleanup;
   144    138     }
   145    139     assert( pTabList->nSrc==1 );
................................................................................
   147    141     /* Locate the table which we want to update. 
   148    142     */
   149    143     pTab = sqlite3SrcListLookup(pParse, pTabList);
   150    144     if( pTab==0 ) goto update_cleanup;
   151    145     iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   152    146   
   153    147     /* Figure out if we have any triggers and if the table being
   154         -  ** updated is a view
          148  +  ** updated is a view.
   155    149     */
   156    150   #ifndef SQLITE_OMIT_TRIGGER
   157    151     pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, 0);
   158    152     isView = pTab->pSelect!=0;
   159    153   #else
   160    154   # define pTrigger 0
   161    155   # define isView 0
................................................................................
   171    165     if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
   172    166       goto update_cleanup;
   173    167     }
   174    168     aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
   175    169     if( aXRef==0 ) goto update_cleanup;
   176    170     for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
   177    171   
   178         -  /* If there are FOR EACH ROW triggers, allocate cursors for the
   179         -  ** special OLD and NEW tables
   180         -  */
   181         -  if( pTrigger ){
   182         -    newIdx = pParse->nTab++;
   183         -    oldIdx = pParse->nTab++;
   184         -  }
   185         -
   186    172     /* Allocate a cursors for the main database table and for all indices.
   187    173     ** The index cursors might not be used, but if they are used they
   188    174     ** need to occur right after the database cursor.  So go ahead and
   189    175     ** allocate enough space, just in case.
   190    176     */
   191    177     pTabList->a[0].iCursor = iCur = pParse->nTab++;
   192    178     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
................................................................................
   264    250             break;
   265    251           }
   266    252         }
   267    253       }
   268    254       aRegIdx[j] = reg;
   269    255     }
   270    256   
   271         -  /* Allocate a block of register used to store the change record
   272         -  ** sent to sqlite3GenerateConstraintChecks().  There are either
   273         -  ** one or two registers for holding the rowid.  One rowid register
   274         -  ** is used if chngRowid is false and two are used if chngRowid is
   275         -  ** true.  Following these are pTab->nCol register holding column
   276         -  ** data.
   277         -  */
   278         -  regOldRowid = regNewRowid = pParse->nMem + 1;
   279         -  pParse->nMem += pTab->nCol + 1;
   280         -  if( chngRowid ){
   281         -    regNewRowid++;
   282         -    pParse->nMem++;
   283         -  }
   284         -  regData = regNewRowid+1;
   285         - 
   286         -
   287         -  /* Begin generating code.
   288         -  */
          257  +  /* Begin generating code. */
   289    258     v = sqlite3GetVdbe(pParse);
   290    259     if( v==0 ) goto update_cleanup;
   291    260     if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
   292    261     sqlite3BeginWriteOperation(pParse, 1, iDb);
   293    262   
   294    263   #ifndef SQLITE_OMIT_VIRTUALTABLE
   295    264     /* Virtual tables must be handled separately */
................................................................................
   298    267                          pWhere);
   299    268       pWhere = 0;
   300    269       pTabList = 0;
   301    270       goto update_cleanup;
   302    271     }
   303    272   #endif
   304    273   
   305         -  /* Start the view context
   306         -  */
          274  +  /* Allocate required registers. */
          275  +  regOldRowid = regNewRowid = ++pParse->nMem;
          276  +  if( pTrigger ){
          277  +    regOld = pParse->nMem + 1;
          278  +    pParse->nMem += pTab->nCol;
          279  +  }
          280  +  if( chngRowid || pTrigger ){
          281  +    regNewRowid = ++pParse->nMem;
          282  +  }
          283  +  regNew = pParse->nMem + 1;
          284  +  pParse->nMem += pTab->nCol;
          285  +  regRec = ++pParse->nMem;
          286  +
          287  +  /* Start the view context. */
   307    288     if( isView ){
   308    289       sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
   309    290     }
   310    291   
   311         -  /* Generate the code for triggers.
   312         -  */
   313         -  if( pTrigger ){
   314         -    int iGoto;
   315         -
   316         -    /* Create pseudo-tables for NEW and OLD
   317         -    */
   318         -    sqlite3VdbeAddOp3(v, OP_OpenPseudo, oldIdx, 0, pTab->nCol);
   319         -    sqlite3VdbeAddOp3(v, OP_OpenPseudo, newIdx, 0, pTab->nCol);
   320         -
   321         -    iGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
   322         -    addr = sqlite3VdbeMakeLabel(v);
   323         -    iBeginBeforeTrigger = sqlite3VdbeCurrentAddr(v);
   324         -    if( sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
   325         -          TRIGGER_BEFORE, pTab, newIdx, oldIdx, onError, addr, 
   326         -          &old_col_mask, &new_col_mask) ){
   327         -      goto update_cleanup;
   328         -    }
   329         -    iEndBeforeTrigger = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
   330         -    iBeginAfterTrigger = sqlite3VdbeCurrentAddr(v);
   331         -    if( sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
   332         -          TRIGGER_AFTER, pTab, newIdx, oldIdx, onError, addr, 
   333         -          &old_col_mask, &new_col_mask) ){
   334         -      goto update_cleanup;
   335         -    }
   336         -    iEndAfterTrigger = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
   337         -    sqlite3VdbeJumpHere(v, iGoto);
   338         -  }
          292  +  /* If there are any triggers, set oldmask and new_col_mask. */
          293  +  oldmask = sqlite3TriggerOldmask(
          294  +      pParse, pTrigger, TK_UPDATE, pChanges, pTab, onError);
   339    295   
   340    296     /* If we are trying to update a view, realize that view into
   341    297     ** a ephemeral table.
   342    298     */
   343    299   #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
   344    300     if( isView ){
   345    301       sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
................................................................................
   370    326   
   371    327     /* End the database scan loop.
   372    328     */
   373    329     sqlite3WhereEnd(pWInfo);
   374    330   
   375    331     /* Initialize the count of updated rows
   376    332     */
   377         -  if( db->flags & SQLITE_CountRows && !pParse->trigStack ){
          333  +  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
   378    334       regRowCount = ++pParse->nMem;
   379    335       sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
   380    336     }
   381    337   
   382    338     if( !isView ){
   383    339       /* 
   384    340       ** Open every index that needs updating.  Note that if any
................................................................................
   403    359           KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
   404    360           sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
   405    361                          (char*)pKey, P4_KEYINFO_HANDOFF);
   406    362           assert( pParse->nTab>iCur+i+1 );
   407    363         }
   408    364       }
   409    365     }
   410         -  
   411         -  /* Jump back to this point if a trigger encounters an IGNORE constraint. */
   412         -  if( pTrigger ){
   413         -    sqlite3VdbeResolveLabel(v, addr);
   414         -  }
   415    366   
   416    367     /* Top of the update loop */
   417    368     if( okOnePass ){
   418    369       int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
   419    370       addr = sqlite3VdbeAddOp0(v, OP_Goto);
   420    371       sqlite3VdbeJumpHere(v, a1);
   421    372     }else{
   422    373       addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
   423    374     }
   424    375   
          376  +  /* Make cursor iCur point to the record that is being updated. If
          377  +  ** this record does not exist for some reason (deleted by a trigger,
          378  +  ** for example, then jump to the next iteration of the RowSet loop.  */
          379  +  sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
          380  +
          381  +  /* If there are triggers on this table, populate an array of registers 
          382  +  ** with the required old.* column data.  */
   425    383     if( pTrigger ){
   426         -    int regRowid;
   427         -    int regRow;
   428         -    int regCols;
   429         -
   430         -    /* Make cursor iCur point to the record that is being updated.
   431         -    */
   432         -    sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
   433         -
   434         -    /* Generate the OLD table
   435         -    */
   436         -    regRowid = sqlite3GetTempReg(pParse);
   437         -    regRow = sqlite3GetTempReg(pParse);
   438         -    sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regRowid);
   439         -    if( !old_col_mask ){
   440         -      sqlite3VdbeAddOp2(v, OP_Null, 0, regRow);
   441         -    }else{
   442         -      sqlite3VdbeAddOp2(v, OP_RowData, iCur, regRow);
          384  +    for(i=0; i<pTab->nCol; i++){
          385  +      if( aXRef[i]<0 || oldmask==0xffffffff || (oldmask & (1<<i)) ){
          386  +        sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regOld+i);
          387  +        sqlite3ColumnDefault(v, pTab, i, regOld+i);
          388  +      }else{
          389  +        sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
          390  +      }
   443    391       }
   444         -    sqlite3VdbeAddOp3(v, OP_Insert, oldIdx, regRow, regRowid);
          392  +  }
   445    393   
   446         -    /* Generate the NEW table
   447         -    */
   448         -    if( chngRowid ){
   449         -      sqlite3ExprCodeAndCache(pParse, pRowidExpr, regRowid);
   450         -      sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
          394  +  /* If the record number will change, set register regNewRowid to
          395  +  ** contain the new value. If the record number is not being modified,
          396  +  ** then regNewRowid is the same register as regOldRowid, which is
          397  +  ** already populated.  */
          398  +  assert( chngRowid || pTrigger || regOldRowid==regNewRowid );
          399  +  if( chngRowid ){
          400  +    sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
          401  +    sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
          402  +  }else if( pTrigger ){
          403  +    sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
          404  +  }
          405  +
          406  +  /* Populate the array of registers beginning at regNew with the new
          407  +  ** row data. This array is used to check constaints, create the new
          408  +  ** table and index records, and as the values for any new.* references
          409  +  ** made by triggers.  */
          410  +  for(i=0; i<pTab->nCol; i++){
          411  +    if( i==pTab->iPKey ){
          412  +      sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
   451    413       }else{
   452         -      sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regRowid);
   453         -    }
   454         -    regCols = sqlite3GetTempRange(pParse, pTab->nCol);
   455         -    for(i=0; i<pTab->nCol; i++){
   456         -      if( i==pTab->iPKey ){
   457         -        sqlite3VdbeAddOp2(v, OP_Null, 0, regCols+i);
   458         -        continue;
   459         -      }
   460    414         j = aXRef[i];
   461         -      if( (i<32 && (new_col_mask&((u32)1<<i))!=0) || new_col_mask==0xffffffff ){
   462         -        if( j<0 ){
   463         -          sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regCols+i);
   464         -          sqlite3ColumnDefault(v, pTab, i, -1);
   465         -        }else{
   466         -          sqlite3ExprCodeAndCache(pParse, pChanges->a[j].pExpr, regCols+i);
   467         -        }
          415  +      if( j<0 ){
          416  +        sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
          417  +        sqlite3ColumnDefault(v, pTab, i, regNew+i);
   468    418         }else{
   469         -        sqlite3VdbeAddOp2(v, OP_Null, 0, regCols+i);
          419  +        sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
   470    420         }
   471    421       }
   472         -    sqlite3VdbeAddOp3(v, OP_MakeRecord, regCols, pTab->nCol, regRow);
   473         -    if( !isView ){
   474         -      sqlite3TableAffinityStr(v, pTab);
   475         -      sqlite3ExprCacheAffinityChange(pParse, regCols, pTab->nCol);
   476         -    }
   477         -    sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol);
   478         -    /* if( pParse->nErr ) goto update_cleanup; */
   479         -    sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRow, regRowid);
   480         -    sqlite3ReleaseTempReg(pParse, regRowid);
   481         -    sqlite3ReleaseTempReg(pParse, regRow);
          422  +  }
   482    423   
   483         -    sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginBeforeTrigger);
   484         -    sqlite3VdbeJumpHere(v, iEndBeforeTrigger);
          424  +  /* Fire any BEFORE UPDATE triggers. This happens before constraints are
          425  +  ** verified. One could argue that this is wrong.  */
          426  +  if( pTrigger ){
          427  +    sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
          428  +    sqlite3TableAffinityStr(v, pTab);
          429  +    sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
          430  +        TRIGGER_BEFORE, pTab, -1, regOldRowid, onError, addr);
   485    431     }
   486    432   
   487    433     if( !isView ){
   488         -    /* Loop over every record that needs updating.  We have to load
   489         -    ** the old data for each record to be updated because some columns
   490         -    ** might not change and we will need to copy the old value.
   491         -    ** Also, the old data is needed to delete the old index entries.
   492         -    ** So make the cursor point at the old record.
   493         -    */
   494         -    sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
   495    434   
   496         -    /* If the record number will change, push the record number as it
   497         -    ** will be after the update. (The old record number is currently
   498         -    ** on top of the stack.)
   499         -    */
   500         -    if( chngRowid ){
   501         -      sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
   502         -      sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
   503         -    }
   504         -
   505         -    /* Compute new data for this record.  
   506         -    */
   507         -    for(i=0; i<pTab->nCol; i++){
   508         -      if( i==pTab->iPKey ){
   509         -        sqlite3VdbeAddOp2(v, OP_Null, 0, regData+i);
   510         -        continue;
   511         -      }
   512         -      j = aXRef[i];
   513         -      if( j<0 ){
   514         -        sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regData+i);
   515         -        sqlite3ColumnDefault(v, pTab, i, regData+i);
   516         -      }else{
   517         -        sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regData+i);
   518         -      }
   519         -    }
   520         -
   521         -    /* Do constraint checks
   522         -    */
          435  +    /* Do constraint checks. */
   523    436       sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
   524         -                                    aRegIdx, chngRowid, 1,
   525         -                                    onError, addr, 0);
          437  +        aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
   526    438   
   527         -    /* Delete the old indices for the current record.
   528         -    */
          439  +    /* Delete the index entries associated with the current record.  */
   529    440       j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
   530    441       sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
   531         -
   532         -    /* If changing the record number, delete the old record.
   533         -    */
          442  +  
          443  +    /* If changing the record number, delete the old record.  */
   534    444       if( chngRowid ){
   535    445         sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
   536    446       }
   537    447       sqlite3VdbeJumpHere(v, j1);
   538         -
   539         -    /* Create the new index entries and the new record.
   540         -    */
   541         -    sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, 
   542         -                             aRegIdx, 1, -1, 0, 0);
          448  +  
          449  +    /* Insert the new index entries and the new record. */
          450  +    sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
   543    451     }
   544    452   
   545    453     /* Increment the row counter 
   546    454     */
   547         -  if( db->flags & SQLITE_CountRows && !pParse->trigStack){
          455  +  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
   548    456       sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
   549    457     }
   550    458   
   551         -  /* If there are triggers, close all the cursors after each iteration
   552         -  ** through the loop.  The fire the after triggers.
   553         -  */
   554         -  if( pTrigger ){
   555         -    sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginAfterTrigger);
   556         -    sqlite3VdbeJumpHere(v, iEndAfterTrigger);
   557         -  }
          459  +  sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
          460  +      TRIGGER_AFTER, pTab, -1, regOldRowid, onError, addr);
   558    461   
   559    462     /* Repeat the above with the next record to be updated, until
   560    463     ** all record selected by the WHERE clause have been updated.
   561    464     */
   562    465     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
   563    466     sqlite3VdbeJumpHere(v, addr);
   564    467   
................................................................................
   565    468     /* Close all tables */
   566    469     for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
   567    470       if( openAll || aRegIdx[i]>0 ){
   568    471         sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
   569    472       }
   570    473     }
   571    474     sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
   572         -  if( pTrigger ){
   573         -    sqlite3VdbeAddOp2(v, OP_Close, newIdx, 0);
   574         -    sqlite3VdbeAddOp2(v, OP_Close, oldIdx, 0);
   575         -  }
   576    475   
   577    476     /* Update the sqlite_sequence table by storing the content of the
   578    477     ** maximum rowid counter values recorded while inserting into
   579    478     ** autoincrement tables.
   580    479     */
   581         -  if( pParse->nested==0 && pParse->trigStack==0 ){
          480  +  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
   582    481       sqlite3AutoincrementEnd(pParse);
   583    482     }
   584    483   
   585    484     /*
   586    485     ** Return the number of rows that were changed. If this routine is 
   587    486     ** generating code because of a call to sqlite3NestedParse(), do not
   588    487     ** invoke the callback function.
   589    488     */
   590         -  if( db->flags & SQLITE_CountRows && !pParse->trigStack && pParse->nested==0 ){
          489  +  if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
   591    490       sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
   592    491       sqlite3VdbeSetNumCols(v, 1);
   593    492       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
   594    493     }
   595    494   
   596    495   update_cleanup:
   597    496     sqlite3AuthContextPop(&sContext);

Changes to src/vdbe.c.

   842    842   ** If P4 is not null then it is an error message string.
   843    843   **
   844    844   ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
   845    845   ** every program.  So a jump past the last instruction of the program
   846    846   ** is the same as executing Halt.
   847    847   */
   848    848   case OP_Halt: {
          849  +  if( pOp->p1==SQLITE_OK && p->pFrame ){
          850  +    /* Halt the sub-program. Return control to the parent frame. */
          851  +    VdbeFrame *pFrame = p->pFrame;
          852  +    p->pFrame = pFrame->pParent;
          853  +    p->nFrame--;
          854  +    sqlite3VdbeSetChanges(db, p->nChange);
          855  +    pc = sqlite3VdbeFrameRestore(pFrame);
          856  +    if( pOp->p2==OE_Ignore ){
          857  +      /* Instruction pc is the OP_Program that invoked the sub-program 
          858  +      ** currently being halted. If the p2 instruction of this OP_Halt
          859  +      ** instruction is set to OE_Ignore, then the sub-program is throwing
          860  +      ** an IGNORE exception. In this case jump to the address specified
          861  +      ** as the p2 of the calling OP_Program.  */
          862  +      pc = p->aOp[pc].p2-1;
          863  +    }
          864  +    break;
          865  +  }
          866  +
   849    867     p->rc = pOp->p1;
   850         -  p->pc = pc;
   851    868     p->errorAction = (u8)pOp->p2;
          869  +  p->pc = pc;
   852    870     if( pOp->p4.z ){
   853    871       sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
   854    872     }
   855    873     rc = sqlite3VdbeHalt(p);
   856    874     assert( rc==SQLITE_BUSY || rc==SQLITE_OK );
   857    875     if( rc==SQLITE_BUSY ){
   858    876       p->rc = rc = SQLITE_BUSY;
................................................................................
  3533   3551   /* Opcode: NewRowid P1 P2 P3 * *
  3534   3552   **
  3535   3553   ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
  3536   3554   ** The record number is not previously used as a key in the database
  3537   3555   ** table that cursor P1 points to.  The new record number is written
  3538   3556   ** written to register P2.
  3539   3557   **
  3540         -** If P3>0 then P3 is a register that holds the largest previously
  3541         -** generated record number.  No new record numbers are allowed to be less
  3542         -** than this value.  When this value reaches its maximum, a SQLITE_FULL
  3543         -** error is generated.  The P3 register is updated with the generated
  3544         -** record number.  This P3 mechanism is used to help implement the
         3558  +** If P3>0 then P3 is a register in the root frame of this VDBE that holds 
         3559  +** the largest previously generated record number. No new record numbers are
         3560  +** allowed to be less than this value. When this value reaches its maximum, 
         3561  +** a SQLITE_FULL error is generated. The P3 register is updated with the '
         3562  +** generated record number. This P3 mechanism is used to help implement the
  3545   3563   ** AUTOINCREMENT feature.
  3546   3564   */
  3547   3565   case OP_NewRowid: {           /* out2-prerelease */
  3548   3566     i64 v;                 /* The new rowid */
  3549   3567     VdbeCursor *pC;        /* Cursor of table to get the new rowid */
  3550   3568     int res;               /* Result of an sqlite3BtreeLast() */
  3551   3569     int cnt;               /* Counter to limit the number of searches */
  3552   3570     Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
         3571  +  VdbeFrame *pFrame;     /* Root frame of VDBE */
  3553   3572   
  3554   3573     v = 0;
  3555   3574     res = 0;
  3556   3575     assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  3557   3576     pC = p->apCsr[pOp->p1];
  3558   3577     assert( pC!=0 );
  3559   3578     if( NEVER(pC->pCursor==0) ){
................................................................................
  3604   3623               v++;
  3605   3624             }
  3606   3625           }
  3607   3626         }
  3608   3627   
  3609   3628   #ifndef SQLITE_OMIT_AUTOINCREMENT
  3610   3629         if( pOp->p3 ){
  3611         -        assert( pOp->p3>0 && pOp->p3<=p->nMem ); /* P3 is a valid memory cell */
  3612         -        pMem = &p->aMem[pOp->p3];
  3613         -	REGISTER_TRACE(pOp->p3, pMem);
         3630  +        if( p->pFrame ){
         3631  +          for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
         3632  +          pMem = &pFrame->aMem[pOp->p3];
         3633  +        }else{
         3634  +          pMem = &p->aMem[pOp->p3];
         3635  +        }
         3636  +        /* Assert that P3 is a valid memory cell. */
         3637  +        assert( pOp->p3>0 && pOp->p3<=(p->pFrame ? pFrame->nMem : p->nMem) );
         3638  +
         3639  +        REGISTER_TRACE(pOp->p3, pMem);
  3614   3640           sqlite3VdbeMemIntegerify(pMem);
  3615   3641           assert( (pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
  3616   3642           if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
  3617   3643             rc = SQLITE_FULL;
  3618   3644             goto abort_due_to_error;
  3619   3645           }
  3620   3646           if( v<pMem->u.i+1 ){
................................................................................
  4727   4753       sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
  4728   4754     }
  4729   4755     break;
  4730   4756   }
  4731   4757   
  4732   4758   
  4733   4759   #ifndef SQLITE_OMIT_TRIGGER
  4734         -/* Opcode: ContextPush * * * 
  4735         -**
  4736         -** Save the current Vdbe context such that it can be restored by a ContextPop
  4737         -** opcode. The context stores the last insert row id, the last statement change
  4738         -** count, and the current statement change count.
  4739         -*/
  4740         -case OP_ContextPush: {
  4741         -  int i;
  4742         -  Context *pContext;
  4743         -
  4744         -  i = p->contextStackTop++;
  4745         -  assert( i>=0 );
  4746         -  /* FIX ME: This should be allocated as part of the vdbe at compile-time */
  4747         -  if( i>=p->contextStackDepth ){
  4748         -    p->contextStackDepth = i+1;
  4749         -    p->contextStack = sqlite3DbReallocOrFree(db, p->contextStack,
  4750         -                                          sizeof(Context)*(i+1));
  4751         -    if( p->contextStack==0 ) goto no_mem;
  4752         -  }
  4753         -  pContext = &p->contextStack[i];
  4754         -  pContext->lastRowid = db->lastRowid;
  4755         -  pContext->nChange = p->nChange;
  4756         -  break;
  4757         -}
  4758         -
  4759         -/* Opcode: ContextPop * * * 
  4760         -**
  4761         -** Restore the Vdbe context to the state it was in when contextPush was last
  4762         -** executed. The context stores the last insert row id, the last statement
  4763         -** change count, and the current statement change count.
  4764         -*/
  4765         -case OP_ContextPop: {
  4766         -  Context *pContext;
  4767         -  pContext = &p->contextStack[--p->contextStackTop];
  4768         -  assert( p->contextStackTop>=0 );
  4769         -  db->lastRowid = pContext->lastRowid;
  4770         -  p->nChange = pContext->nChange;
  4771         -  break;
  4772         -}
         4760  +
         4761  +/* Opcode: Program P1 P2 P3 P4 *
         4762  +**
         4763  +** Execute the trigger program passed as P4 (type P4_SUBPROGRAM). 
         4764  +**
         4765  +** P1 contains the address of the memory cell that contains the first memory 
         4766  +** cell in an array of values used as arguments to the sub-program. P2 
         4767  +** contains the address to jump to if the sub-program throws an IGNORE 
         4768  +** exception using the RAISE() function. Register P3 contains the address 
         4769  +** of a memory cell in this (the parent) VM that is used to allocate the 
         4770  +** memory required by the sub-vdbe at runtime.
         4771  +**
         4772  +** P4 is a pointer to the VM containing the trigger program.
         4773  +*/
         4774  +case OP_Program: {        /* jump */
         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];
         4786  +  assert( pProgram->nOp>0 );
         4787  +  
         4788  +  /* If the SQLITE_NoRecTriggers flag it set, then recursive invocation of
         4789  +  ** triggers is disabled for backwards compatibility (flag set/cleared by
         4790  +  ** the "PRAGMA disable_recursive_triggers" command). 
         4791  +  ** 
         4792  +  ** It is recursive invocation of triggers, at the SQL level, that is 
         4793  +  ** disabled. In some cases a single trigger may generate more than one 
         4794  +  ** SubProgram (if the trigger may be executed with more than one different 
         4795  +  ** ON CONFLICT algorithm). SubProgram structures associated with a
         4796  +  ** single trigger all have the same value for the SubProgram.token 
         4797  +  ** variable.
         4798  +  */
         4799  +  if( db->flags&SQLITE_NoRecTriggers ){
         4800  +    t = pProgram->token;
         4801  +    for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
         4802  +    if( pFrame ) break;
         4803  +  }
         4804  +
         4805  +  /* TODO: This constant should be configurable. */
         4806  +  if( p->nFrame>1000 ){
         4807  +    rc = SQLITE_ERROR;
         4808  +    sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
         4809  +    break;
         4810  +  }
         4811  +
         4812  +  /* Register pRt is used to store the memory required to save the state
         4813  +  ** of the current program, and the memory required at runtime to execute
         4814  +  ** the trigger program. If this trigger has been fired before, then pRt 
         4815  +  ** is already allocated. Otherwise, it must be initialized.  */
         4816  +  if( (pRt->flags&MEM_Frame)==0 ){
         4817  +    /* SubProgram.nMem is set to the number of memory cells used by the 
         4818  +    ** program stored in SubProgram.aOp. As well as these, one memory
         4819  +    ** cell is required for each cursor used by the program. Set local
         4820  +    ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
         4821  +    */
         4822  +    nMem = pProgram->nMem + pProgram->nCsr;
         4823  +    nByte = ROUND8(sizeof(VdbeFrame))
         4824  +              + nMem * sizeof(Mem)
         4825  +              + pProgram->nCsr * sizeof(VdbeCursor *);
         4826  +    pFrame = sqlite3DbMallocZero(db, nByte);
         4827  +    if( !pFrame ){
         4828  +      goto no_mem;
         4829  +    }
         4830  +    sqlite3VdbeMemRelease(pRt);
         4831  +    pRt->flags = MEM_Frame;
         4832  +    pRt->u.pFrame = pFrame;
         4833  +
         4834  +    pFrame->v = p;
         4835  +    pFrame->nChildMem = nMem;
         4836  +    pFrame->nChildCsr = pProgram->nCsr;
         4837  +    pFrame->pc = pc;
         4838  +    pFrame->aMem = p->aMem;
         4839  +    pFrame->nMem = p->nMem;
         4840  +    pFrame->apCsr = p->apCsr;
         4841  +    pFrame->nCursor = p->nCursor;
         4842  +    pFrame->aOp = p->aOp;
         4843  +    pFrame->nOp = p->nOp;
         4844  +    pFrame->token = pProgram->token;
         4845  +
         4846  +    pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
         4847  +    for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
         4848  +      pMem->flags = MEM_Null;
         4849  +      pMem->db = db;
         4850  +    }
         4851  +  }else{
         4852  +    pFrame = pRt->u.pFrame;
         4853  +    assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem );
         4854  +    assert( pProgram->nCsr==pFrame->nChildCsr );
         4855  +    assert( pc==pFrame->pc );
         4856  +  }
         4857  +
         4858  +  p->nFrame++;
         4859  +  pFrame->pParent = p->pFrame;
         4860  +  pFrame->lastRowid = db->lastRowid;
         4861  +  pFrame->nChange = p->nChange;
         4862  +  p->nChange = 0;
         4863  +  p->pFrame = pFrame;
         4864  +  p->aMem = &VdbeFrameMem(pFrame)[-1];
         4865  +  p->nMem = pFrame->nChildMem;
         4866  +  p->nCursor = pFrame->nChildCsr;
         4867  +  p->apCsr = (VdbeCursor **)&p->aMem[p->nMem+1];
         4868  +  p->aOp = pProgram->aOp;
         4869  +  p->nOp = pProgram->nOp;
         4870  +  pc = -1;
         4871  +
         4872  +  break;
         4873  +}
         4874  +
         4875  +/* Opcode: Param P1 P2 * * *
         4876  +**
         4877  +** This opcode is only ever present in sub-programs called via the 
         4878  +** OP_Program instruction. Copy a value currently stored in a memory 
         4879  +** cell of the calling (parent) frame to cell P2 in the current frames 
         4880  +** address space. This is used by trigger programs to access the new.* 
         4881  +** and old.* values.
         4882  +**
         4883  +** The address of the cell in the parent frame is determined by adding
         4884  +** the value of the P1 argument to the value of the P1 argument to the
         4885  +** calling OP_Program instruction.
         4886  +*/
         4887  +case OP_Param: {           /* out2-prerelease */
         4888  +  VdbeFrame *pFrame;
         4889  +  Mem *pIn;
         4890  +  pFrame = p->pFrame;
         4891  +  pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];   
         4892  +  sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
         4893  +  break;
         4894  +}
         4895  +
  4773   4896   #endif /* #ifndef SQLITE_OMIT_TRIGGER */
  4774   4897   
  4775   4898   #ifndef SQLITE_OMIT_AUTOINCREMENT
  4776   4899   /* Opcode: MemMax P1 P2 * * *
  4777   4900   **
  4778         -** Set the value of register P1 to the maximum of its current value
  4779         -** and the value in register P2.
         4901  +** P1 is a register in the root frame of this VM (the root frame is
         4902  +** different from the current frame if this instruction is being executed
         4903  +** within a sub-program). Set the value of register P1 to the maximum of 
         4904  +** its current value and the value in register P2.
  4780   4905   **
  4781   4906   ** This instruction throws an error if the memory cell is not initially
  4782   4907   ** an integer.
  4783   4908   */
  4784         -case OP_MemMax: {        /* in1, in2 */
         4909  +case OP_MemMax: {        /* in2 */
         4910  +  Mem *pIn1;
         4911  +  VdbeFrame *pFrame;
         4912  +  if( p->pFrame ){
         4913  +    for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
         4914  +    pIn1 = &pFrame->aMem[pOp->p1];
         4915  +  }else{
         4916  +    pIn1 = &p->aMem[pOp->p1];
         4917  +  }
  4785   4918     sqlite3VdbeMemIntegerify(pIn1);
  4786   4919     sqlite3VdbeMemIntegerify(pIn2);
  4787   4920     if( pIn1->u.i<pIn2->u.i){
  4788   4921       pIn1->u.i = pIn2->u.i;
  4789   4922     }
  4790   4923     break;
  4791   4924   }

Changes to src/vdbe.h.

    30     30   
    31     31   /*
    32     32   ** The names of the following types declared in vdbeInt.h are required
    33     33   ** for the VdbeOp definition.
    34     34   */
    35     35   typedef struct VdbeFunc VdbeFunc;
    36     36   typedef struct Mem Mem;
           37  +typedef struct SubProgram SubProgram;
    37     38   
    38     39   /*
    39     40   ** A single instruction of the virtual machine has an opcode
    40     41   ** and as many as three operands.  The instruction is recorded
    41     42   ** as an instance of the following structure:
    42     43   */
    43     44   struct VdbeOp {
................................................................................
    44     45     u8 opcode;          /* What operation to perform */
    45     46     signed char p4type; /* One of the P4_xxx constants for p4 */
    46     47     u8 opflags;         /* Not currently used */
    47     48     u8 p5;              /* Fifth parameter is an unsigned character */
    48     49     int p1;             /* First operand */
    49     50     int p2;             /* Second parameter (often the jump destination) */
    50     51     int p3;             /* The third parameter */
    51         -  union {             /* forth parameter */
           52  +  union {             /* fourth parameter */
    52     53       int i;                 /* Integer value if p4type==P4_INT32 */
    53     54       void *p;               /* Generic pointer */
    54     55       char *z;               /* Pointer to data for string (char array) types */
    55     56       i64 *pI64;             /* Used when p4type is P4_INT64 */
    56     57       double *pReal;         /* Used when p4type is P4_REAL */
    57     58       FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
    58     59       VdbeFunc *pVdbeFunc;   /* Used when p4type is P4_VDBEFUNC */
    59     60       CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
    60     61       Mem *pMem;             /* Used when p4type is P4_MEM */
    61     62       VTable *pVtab;         /* Used when p4type is P4_VTAB */
    62     63       KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
    63     64       int *ai;               /* Used when p4type is P4_INTARRAY */
           65  +    SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
    64     66     } p4;
    65     67   #ifdef SQLITE_DEBUG
    66     68     char *zComment;          /* Comment to improve readability */
    67     69   #endif
    68     70   #ifdef VDBE_PROFILE
    69     71     int cnt;                 /* Number of times this instruction was executed */
    70     72     u64 cycles;              /* Total time spent executing this instruction */
    71     73   #endif
    72     74   };
    73     75   typedef struct VdbeOp VdbeOp;
    74     76   
           77  +
           78  +/*
           79  +** A sub-routine used to implement a trigger program.
           80  +*/
           81  +struct SubProgram {
           82  +  VdbeOp *aOp;                  /* Array of opcodes for sub-program */
           83  +  int nOp;                      /* Elements in aOp[] */
           84  +  int nMem;                     /* Number of memory cells required */
           85  +  int nCsr;                     /* Number of cursors required */
           86  +  int nRef;                     /* Number of pointers to this structure */
           87  +  void *token;                  /* id that may be used to recursive triggers */
           88  +};
           89  +
    75     90   /*
    76     91   ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
    77     92   ** it takes up less space.
    78     93   */
    79     94   struct VdbeOpList {
    80     95     u8 opcode;          /* What operation to perform */
    81     96     signed char p1;     /* First operand */
    82     97     signed char p2;     /* Second parameter (often the jump destination) */
    83     98     signed char p3;     /* Third parameter */
    84     99   };
    85    100   typedef struct VdbeOpList VdbeOpList;
    86    101   
    87    102   /*
    88         -** Allowed values of VdbeOp.p3type
          103  +** Allowed values of VdbeOp.p4type
    89    104   */
    90    105   #define P4_NOTUSED    0   /* The P4 parameter is not used */
    91    106   #define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
    92    107   #define P4_STATIC   (-2)  /* Pointer to a static string */
    93    108   #define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
    94    109   #define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
    95    110   #define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
................................................................................
    98    113   #define P4_TRANSIENT (-9) /* P4 is a pointer to a transient string */
    99    114   #define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
   100    115   #define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
   101    116   #define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
   102    117   #define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
   103    118   #define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
   104    119   #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
          120  +#define P4_SUBPROGRAM  (-18) /* P4 is a pointer to a SubProgram structure */
   105    121   
   106    122   /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
   107    123   ** is made.  That copy is freed when the Vdbe is finalized.  But if the
   108    124   ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used.  It still
   109    125   ** gets freed when the Vdbe is finalized so it still should be obtained
   110    126   ** from a single sqliteMalloc().  But no copy is made and the calling
   111    127   ** function should *not* try to free the KeyInfo.
................................................................................
   164    180   void sqlite3VdbeJumpHere(Vdbe*, int addr);
   165    181   void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N);
   166    182   void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
   167    183   void sqlite3VdbeUsesBtree(Vdbe*, int);
   168    184   VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
   169    185   int sqlite3VdbeMakeLabel(Vdbe*);
   170    186   void sqlite3VdbeDelete(Vdbe*);
   171         -void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int);
          187  +void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int,int);
   172    188   int sqlite3VdbeFinalize(Vdbe*);
   173    189   void sqlite3VdbeResolveLabel(Vdbe*, int);
   174    190   int sqlite3VdbeCurrentAddr(Vdbe*);
   175    191   #ifdef SQLITE_DEBUG
   176    192     void sqlite3VdbeTrace(Vdbe*,FILE*);
   177    193   #endif
   178    194   void sqlite3VdbeResetStepResult(Vdbe*);
................................................................................
   179    195   int sqlite3VdbeReset(Vdbe*);
   180    196   void sqlite3VdbeSetNumCols(Vdbe*,int);
   181    197   int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
   182    198   void sqlite3VdbeCountChanges(Vdbe*);
   183    199   sqlite3 *sqlite3VdbeDb(Vdbe*);
   184    200   void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
   185    201   void sqlite3VdbeSwap(Vdbe*,Vdbe*);
          202  +VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
          203  +void sqlite3VdbeProgramDelete(sqlite3 *, SubProgram *, int);
   186    204   
   187    205   #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
   188    206   int sqlite3VdbeReleaseMemory(int);
   189    207   #endif
   190    208   UnpackedRecord *sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,char*,int);
   191    209   void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord*);
   192    210   int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);

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  +*/
          105  +typedef struct VdbeFrame VdbeFrame;
          106  +struct VdbeFrame {
          107  +  Vdbe *v;                /* VM this frame belongs to */
          108  +  int pc;                 /* Program Counter */
          109  +  Op *aOp;                /* Program instructions */
          110  +  int nOp;                /* Size of aOp array */
          111  +  Mem *aMem;              /* Array of memory cells */
          112  +  int nMem;               /* Number of entries in aMem */
          113  +  VdbeCursor **apCsr;     /* Element of Vdbe cursors */
          114  +  u16 nCursor;            /* Number of entries in apCsr */
          115  +  void *token;            /* Copy of SubProgram.token */
          116  +  int nChildMem;          /* Number of memory cells for child frame */
          117  +  int nChildCsr;          /* Number of cursors for child frame */
          118  +  i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
          119  +  int nChange;            /* Statement changes (Vdbe.nChanges)     */
          120  +  VdbeFrame *pParent;     /* Parent of this frame */
          121  +};
          122  +
          123  +#define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
          124  +
    92    125   /*
    93    126   ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
    94    127   */
    95    128   #define CACHE_STALE 0
    96    129   
    97    130   /*
    98    131   ** Internally, the vdbe manipulates nearly all SQL values as Mem
................................................................................
   107    140   */
   108    141   struct Mem {
   109    142     union {
   110    143       i64 i;              /* Integer value. */
   111    144       int nZero;          /* Used when bit MEM_Zero is set in flags */
   112    145       FuncDef *pDef;      /* Used only when flags==MEM_Agg */
   113    146       RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
          147  +    VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
   114    148     } u;
   115    149     double r;           /* Real value */
   116    150     sqlite3 *db;        /* The associated database connection */
   117    151     char *z;            /* String or BLOB value */
   118    152     int n;              /* Number of characters in string value, excluding '\0' */
   119    153     u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
   120    154     u8  type;           /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
................................................................................
   140    174   */
   141    175   #define MEM_Null      0x0001   /* Value is NULL */
   142    176   #define MEM_Str       0x0002   /* Value is a string */
   143    177   #define MEM_Int       0x0004   /* Value is an integer */
   144    178   #define MEM_Real      0x0008   /* Value is a real number */
   145    179   #define MEM_Blob      0x0010   /* Value is a BLOB */
   146    180   #define MEM_RowSet    0x0020   /* Value is a RowSet object */
          181  +#define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
   147    182   #define MEM_TypeMask  0x00ff   /* Mask of type bits */
   148    183   
   149    184   /* Whenever Mem contains a valid string or blob representation, one of
   150    185   ** the following flags must be set to determine the memory management
   151    186   ** policy for Mem.z.  The MEM_Term flag tells us whether or not the
   152    187   ** string is \000 or \u0000 terminated
   153    188   */
................................................................................
   219    254   */
   220    255   typedef struct Set Set;
   221    256   struct Set {
   222    257     Hash hash;             /* A set is just a hash table */
   223    258     HashElem *prev;        /* Previously accessed hash elemen */
   224    259   };
   225    260   
   226         -/*
   227         -** A Context stores the last insert rowid, the last statement change count,
   228         -** and the current statement change count (i.e. changes since last statement).
   229         -** The current keylist is also stored in the context.
   230         -** Elements of Context structure type make up the ContextStack, which is
   231         -** updated by the ContextPush and ContextPop opcodes (used by triggers).
   232         -** The context is pushed before executing a trigger a popped when the
   233         -** trigger finishes.
   234         -*/
   235         -typedef struct Context Context;
   236         -struct Context {
   237         -  i64 lastRowid;    /* Last insert rowid (sqlite3.lastRowid) */
   238         -  int nChange;      /* Statement changes (Vdbe.nChanges)     */
   239         -};
   240         -
   241    261   /*
   242    262   ** An instance of the virtual machine.  This structure contains the complete
   243    263   ** state of the virtual machine.
   244    264   **
   245    265   ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_compile()
   246    266   ** is really a pointer to an instance of this structure.
   247    267   **
................................................................................
   273    293     u16 nVar;               /* Number of entries in aVar[] */
   274    294     Mem *aVar;              /* Values for the OP_Variable opcode. */
   275    295     char **azVar;           /* Name of variables */
   276    296     u32 magic;              /* Magic number for sanity checking */
   277    297     int nMem;               /* Number of memory locations currently allocated */
   278    298     Mem *aMem;              /* The memory locations */
   279    299     int cacheCtr;           /* VdbeCursor row cache generation counter */
   280         -  int contextStackTop;    /* Index of top element in the context stack */
   281         -  int contextStackDepth;  /* The size of the "context" stack */
   282         -  Context *contextStack;  /* Stack used by opcodes ContextPush & ContextPop*/
   283    300     int pc;                 /* The program counter */
   284    301     int rc;                 /* Value to return */
   285    302     char *zErrMsg;          /* Error message written here */
   286    303     u8 explain;             /* True if EXPLAIN present on SQL command */
   287    304     u8 changeCntOn;         /* True to update the change-counter */
   288    305     u8 expired;             /* True if the VM needs to be recompiled */
   289    306     u8 minWriteFileFormat;  /* Minimum file format for writable database files */
................................................................................
   298    315     int aCounter[2];        /* Counters used by sqlite3_stmt_status() */
   299    316     char *zSql;             /* Text of the SQL statement that generated this */
   300    317     void *pFree;            /* Free this when deleting the vdbe */
   301    318     int iStatement;         /* Statement number (or 0 if has not opened stmt) */
   302    319   #ifdef SQLITE_DEBUG
   303    320     FILE *trace;            /* Write an execution trace here, if not NULL */
   304    321   #endif
          322  +  VdbeFrame *pFrame;      /* Parent frame */
          323  +  int nFrame;             /* Number of frames in pFrame list */
   305    324   };
   306    325   
   307    326   /*
   308    327   ** The following are allowed values for Vdbe.magic
   309    328   */
   310    329   #define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
   311    330   #define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
................................................................................
   358    377   void sqlite3VdbeMemRelease(Mem *p);
   359    378   void sqlite3VdbeMemReleaseExternal(Mem *p);
   360    379   int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
   361    380   const char *sqlite3OpcodeName(int);
   362    381   int sqlite3VdbeOpcodeHasProperty(int, int);
   363    382   int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
   364    383   int sqlite3VdbeCloseStatement(Vdbe *, int);
          384  +void sqlite3VdbeFrameDelete(VdbeFrame*);
          385  +int sqlite3VdbeFrameRestore(VdbeFrame *);
   365    386   #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
   366    387   int sqlite3VdbeReleaseBuffers(Vdbe *p);
   367    388   #endif
   368    389   
   369    390   #ifndef SQLITE_OMIT_SHARED_CACHE
   370    391   void sqlite3VdbeMutexArrayEnter(Vdbe *p);
   371    392   #else

Changes to src/vdbeapi.c.

    72     72     int rc;
    73     73     if( pStmt==0 ){
    74     74       rc = SQLITE_OK;
    75     75     }else{
    76     76       Vdbe *v = (Vdbe*)pStmt;
    77     77       sqlite3_mutex_enter(v->db->mutex);
    78     78       rc = sqlite3VdbeReset(v);
    79         -    sqlite3VdbeMakeReady(v, -1, 0, 0, 0);
           79  +    sqlite3VdbeMakeReady(v, -1, 0, 0, 0, 0);
    80     80       assert( (rc & (v->db->errMask))==rc );
    81     81       rc = sqlite3ApiExit(v->db, rc);
    82     82       sqlite3_mutex_leave(v->db->mutex);
    83     83     }
    84     84     return rc;
    85     85   }
    86     86   

Changes to src/vdbeaux.c.

   262    262   **
   263    263   ** If no such instruction is found, then every Statement instruction 
   264    264   ** is changed to a Noop.  In this way, we avoid creating the statement 
   265    265   ** journal file unnecessarily.
   266    266   */
   267    267   static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
   268    268     int i;
   269         -  int nMaxArgs = 0;
          269  +  int nMaxArgs = *pMaxFuncArgs;
   270    270     Op *pOp;
   271    271     int *aLabel = p->aLabel;
   272    272     int doesStatementRollback = 0;
   273    273     int hasStatementBegin = 0;
   274    274     p->readOnly = 1;
   275    275     p->usesStmtJournal = 0;
   276    276     for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
................................................................................
   291    291         hasStatementBegin = 1;
   292    292         p->usesStmtJournal = 1;
   293    293       }else if( opcode==OP_Destroy ){
   294    294         doesStatementRollback = 1;
   295    295       }else if( opcode==OP_Transaction && pOp->p2!=0 ){
   296    296         p->readOnly = 0;
   297    297   #ifndef SQLITE_OMIT_VIRTUALTABLE
   298         -    }else if( opcode==OP_VUpdate || opcode==OP_VRename ){
          298  +    }else if( opcode==OP_VUpdate || opcode==OP_VRename || opcode==OP_Program ){
   299    299         doesStatementRollback = 1;
   300    300       }else if( opcode==OP_VFilter ){
   301    301         int n;
   302    302         assert( p->nOp - i >= 3 );
   303    303         assert( pOp[-1].opcode==OP_Integer );
   304    304         n = pOp[-1].p1;
   305    305         if( n>nMaxArgs ) nMaxArgs = n;
................................................................................
   334    334   /*
   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  +
          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  +*/
          353  +VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
          354  +  VdbeOp *aOp = p->aOp;
          355  +  assert( aOp && !p->db->mallocFailed );
          356  +
          357  +  /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
          358  +  assert( p->aMutex.nMutex==0 );
          359  +
          360  +  resolveP2Values(p, pnMaxArg);
          361  +  *pnOp = p->nOp;
          362  +  p->aOp = 0;
          363  +  return aOp;
          364  +}
   341    365   
   342    366   /*
   343    367   ** Add a whole list of operations to the operation stack.  Return the
   344    368   ** address of the first operation added.
   345    369   */
   346    370   int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
   347    371     int addr;
................................................................................
   478    502           sqlite3ValueFree((sqlite3_value*)p4);
   479    503           break;
   480    504         }
   481    505         case P4_VTAB : {
   482    506           sqlite3VtabUnlock((VTable *)p4);
   483    507           break;
   484    508         }
          509  +      case P4_SUBPROGRAM : {
          510  +        sqlite3VdbeProgramDelete(db, (SubProgram *)p4, 1);
          511  +        break;
          512  +      }
          513  +    }
          514  +  }
          515  +}
          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  +*/
          522  +static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
          523  +  if( aOp ){
          524  +    Op *pOp;
          525  +    for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
          526  +      freeP4(db, pOp->p4type, pOp->p4.p);
          527  +#ifdef SQLITE_DEBUG
          528  +      sqlite3DbFree(db, pOp->zComment);
          529  +#endif     
          530  +    }
          531  +  }
          532  +  sqlite3DbFree(db, aOp);
          533  +}
          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  +*/
          548  +void sqlite3VdbeProgramDelete(sqlite3 *db, SubProgram *p, int freeop){
          549  +  if( p ){
          550  +    assert( p->nRef>0 );
          551  +    if( freeop || p->nRef==1 ){
          552  +      Op *aOp = p->aOp;
          553  +      p->aOp = 0;
          554  +      vdbeFreeOpArray(db, aOp, p->nOp);
          555  +      p->nOp = 0;
          556  +    }
          557  +    p->nRef--;
          558  +    if( p->nRef==0 ){
          559  +      sqlite3DbFree(db, p);
   485    560       }
   486    561     }
   487    562   }
   488    563   
   489    564   
   490    565   /*
   491    566   ** Change N opcodes starting at addr to No-ops.
................................................................................
   600    675   ** Change the comment on the the most recently coded instruction.  Or
   601    676   ** insert a No-op and add the comment to that new instruction.  This
   602    677   ** makes the code easier to read during debugging.  None of this happens
   603    678   ** in a production build.
   604    679   */
   605    680   void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
   606    681     va_list ap;
          682  +  if( !p ) return;
   607    683     assert( p->nOp>0 || p->aOp==0 );
   608    684     assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
   609    685     if( p->nOp ){
   610    686       char **pz = &p->aOp[p->nOp-1].zComment;
   611    687       va_start(ap, zFormat);
   612    688       sqlite3DbFree(p->db, *pz);
   613    689       *pz = sqlite3VMPrintf(p->db, zFormat, ap);
   614    690       va_end(ap);
   615    691     }
   616    692   }
   617    693   void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
   618    694     va_list ap;
          695  +  if( !p ) return;
   619    696     sqlite3VdbeAddOp0(p, OP_Noop);
   620    697     assert( p->nOp>0 || p->aOp==0 );
   621    698     assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
   622    699     if( p->nOp ){
   623    700       char **pz = &p->aOp[p->nOp-1].zComment;
   624    701       va_start(ap, zFormat);
   625    702       sqlite3DbFree(p->db, *pz);
................................................................................
   747    824         sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
   748    825         break;
   749    826       }
   750    827   #endif
   751    828       case P4_INTARRAY: {
   752    829         sqlite3_snprintf(nTemp, zTemp, "intarray");
   753    830         break;
          831  +    }
          832  +    case P4_SUBPROGRAM: {
          833  +      sqlite3_snprintf(nTemp, zTemp, "program");
          834  +      break;
   754    835       }
   755    836       default: {
   756    837         zP4 = pOp->p4.z;
   757    838         if( zP4==0 ){
   758    839           zP4 = zTemp;
   759    840           zTemp[0] = 0;
   760    841         }
................................................................................
   763    844     assert( zP4!=0 );
   764    845     return zP4;
   765    846   }
   766    847   #endif
   767    848   
   768    849   /*
   769    850   ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
   770         -**
   771    851   */
   772    852   void sqlite3VdbeUsesBtree(Vdbe *p, int i){
   773    853     int mask;
   774    854     assert( i>=0 && i<p->db->nDb && i<sizeof(u32)*8 );
   775    855     assert( i<(int)sizeof(p->btreeMask)*8 );
   776    856     mask = ((u32)1)<<i;
   777    857     if( (p->btreeMask & mask)==0 ){
................................................................................
   822    902         ** callgrind, this causes a certain test case to hit the CPU 4.7 
   823    903         ** percent less (x86 linux, gcc version 4.1.2, -O6) than if 
   824    904         ** sqlite3MemRelease() were called from here. With -O2, this jumps
   825    905         ** to 6.6 percent. The test case is inserting 1000 rows into a table 
   826    906         ** with no indexes using a single prepared INSERT statement, bind() 
   827    907         ** and reset(). Inserts are grouped into a transaction.
   828    908         */
   829         -      if( p->flags&(MEM_Agg|MEM_Dyn) ){
          909  +      if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
   830    910           sqlite3VdbeMemRelease(p);
   831    911         }else if( p->zMalloc ){
   832    912           sqlite3DbFree(db, p->zMalloc);
   833    913           p->zMalloc = 0;
   834    914         }
   835    915   
   836    916         p->flags = MEM_Null;
   837    917       }
   838    918       db->mallocFailed = malloc_failed;
   839    919     }
   840    920   }
          921  +
          922  +/*
          923  +** Delete a VdbeFrame object and its contents. VdbeFrame objects are
          924  +** allocated by the OP_Program opcode in sqlite3VdbeExec().
          925  +*/
          926  +void sqlite3VdbeFrameDelete(VdbeFrame *p){
          927  +  int i;
          928  +  Mem *aMem = VdbeFrameMem(p);
          929  +  VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
          930  +  for(i=0; i<p->nChildCsr; i++){
          931  +    sqlite3VdbeFreeCursor(p->v, apCsr[i]);
          932  +  }
          933  +  releaseMemArray(aMem, p->nChildMem);
          934  +  sqlite3DbFree(p->v->db, p);
          935  +}
          936  +
   841    937   
   842    938   #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
   843    939   int sqlite3VdbeReleaseBuffers(Vdbe *p){
   844    940     int ii;
   845    941     int nFree = 0;
   846    942     assert( sqlite3_mutex_held(p->db->mutex) );
   847    943     for(ii=1; ii<=p->nMem; ii++){
................................................................................
   871    967   ** p->explain==2, only OP_Explain instructions are listed and these
   872    968   ** are shown in a different format.  p->explain==2 is used to implement
   873    969   ** EXPLAIN QUERY PLAN.
   874    970   */
   875    971   int sqlite3VdbeList(
   876    972     Vdbe *p                   /* The VDBE */
   877    973   ){
          974  +  int nRow;                            /* Total number of rows to return */
          975  +  int nSub = 0;                        /* Number of sub-vdbes seen so far */
          976  +  SubProgram **apSub = 0;              /* Array of sub-vdbes */
          977  +  Mem *pSub = 0;
   878    978     sqlite3 *db = p->db;
   879    979     int i;
   880    980     int rc = SQLITE_OK;
   881    981     Mem *pMem = p->pResultSet = &p->aMem[1];
   882    982   
   883    983     assert( p->explain );
   884    984     assert( p->magic==VDBE_MAGIC_RUN );
................................................................................
   885    985     assert( db->magic==SQLITE_MAGIC_BUSY );
   886    986     assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
   887    987   
   888    988     /* Even though this opcode does not use dynamic strings for
   889    989     ** the result, result columns may become dynamic if the user calls
   890    990     ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
   891    991     */
   892         -  releaseMemArray(pMem, p->nMem);
          992  +  releaseMemArray(pMem, 8);
   893    993   
   894    994     if( p->rc==SQLITE_NOMEM ){
   895    995       /* This happens if a malloc() inside a call to sqlite3_column_text() or
   896    996       ** sqlite3_column_text16() failed.  */
   897    997       db->mallocFailed = 1;
   898    998       return SQLITE_ERROR;
   899    999     }
         1000  +
         1001  +  /* Figure out total number of rows that will be returned by this 
         1002  +  ** EXPLAIN program.  */
         1003  +  nRow = p->nOp;
         1004  +  if( p->explain==1 ){
         1005  +    pSub = &p->aMem[9];
         1006  +    if( pSub->flags&MEM_Blob ){
         1007  +      nSub = pSub->n/sizeof(Vdbe*);
         1008  +      apSub = (SubProgram **)pSub->z;
         1009  +    }
         1010  +    for(i=0; i<nSub; i++){
         1011  +      nRow += apSub[i]->nOp;
         1012  +    }
         1013  +  }
   900   1014   
   901   1015     do{
   902   1016       i = p->pc++;
   903         -  }while( i<p->nOp && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
   904         -  if( i>=p->nOp ){
         1017  +  }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
         1018  +  if( i>=nRow ){
   905   1019       p->rc = SQLITE_OK;
   906   1020       rc = SQLITE_DONE;
   907   1021     }else if( db->u1.isInterrupted ){
   908   1022       p->rc = SQLITE_INTERRUPT;
   909   1023       rc = SQLITE_ERROR;
   910   1024       sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
   911   1025     }else{
   912   1026       char *z;
   913         -    Op *pOp = &p->aOp[i];
         1027  +    Op *pOp;
         1028  +    if( i<p->nOp ){
         1029  +      pOp = &p->aOp[i];
         1030  +    }else{
         1031  +      int j;
         1032  +      i -= p->nOp;
         1033  +      for(j=0; i>=apSub[j]->nOp; j++){
         1034  +        i -= apSub[j]->nOp;
         1035  +      }
         1036  +      pOp = &apSub[j]->aOp[i];
         1037  +    }
   914   1038       if( p->explain==1 ){
   915   1039         pMem->flags = MEM_Int;
   916   1040         pMem->type = SQLITE_INTEGER;
   917   1041         pMem->u.i = i;                                /* Program counter */
   918   1042         pMem++;
   919   1043     
   920   1044         pMem->flags = MEM_Static|MEM_Str|MEM_Term;
   921   1045         pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */
   922   1046         assert( pMem->z!=0 );
   923   1047         pMem->n = sqlite3Strlen30(pMem->z);
   924   1048         pMem->type = SQLITE_TEXT;
   925   1049         pMem->enc = SQLITE_UTF8;
   926   1050         pMem++;
         1051  +
         1052  +      if( pOp->p4type==P4_SUBPROGRAM ){
         1053  +        int nByte = (nSub+1)*sizeof(SubProgram*);
         1054  +        int j;
         1055  +        for(j=0; j<nSub; j++){
         1056  +          if( apSub[j]==pOp->p4.pProgram ) break;
         1057  +        }
         1058  +        if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, 1) ){
         1059  +          apSub = (SubProgram **)pSub->z;
         1060  +          apSub[nSub++] = pOp->p4.pProgram;
         1061  +          pSub->flags |= MEM_Blob;
         1062  +          pSub->n = nSub*sizeof(SubProgram*);
         1063  +        }
         1064  +      }
   927   1065       }
   928   1066   
   929   1067       pMem->flags = MEM_Int;
   930   1068       pMem->u.i = pOp->p1;                          /* P1 */
   931   1069       pMem->type = SQLITE_INTEGER;
   932   1070       pMem++;
   933   1071   
................................................................................
  1094   1232   ** is passed -1 and nMem, nCursor and isExplain are all passed zero.
  1095   1233   */
  1096   1234   void sqlite3VdbeMakeReady(
  1097   1235     Vdbe *p,                       /* The VDBE */
  1098   1236     int nVar,                      /* Number of '?' see in the SQL statement */
  1099   1237     int nMem,                      /* Number of memory cells to allocate */
  1100   1238     int nCursor,                   /* Number of cursors to allocate */
         1239  +  int nArg,                      /* Maximum number of args in SubPrograms */
  1101   1240     int isExplain                  /* True if the EXPLAIN keywords is present */
  1102   1241   ){
  1103   1242     int n;
  1104   1243     sqlite3 *db = p->db;
  1105   1244   
  1106   1245     assert( p!=0 );
  1107   1246     assert( p->magic==VDBE_MAGIC_INIT );
................................................................................
  1129   1268     ** first time this function is called for a given VDBE, not when it is
  1130   1269     ** being called from sqlite3_reset() to reset the virtual machine.
  1131   1270     */
  1132   1271     if( nVar>=0 && ALWAYS(db->mallocFailed==0) ){
  1133   1272       u8 *zCsr = (u8 *)&p->aOp[p->nOp];
  1134   1273       u8 *zEnd = (u8 *)&p->aOp[p->nOpAlloc];
  1135   1274       int nByte;
  1136         -    int nArg;       /* Maximum number of args passed to a user function. */
  1137   1275       resolveP2Values(p, &nArg);
  1138   1276       if( isExplain && nMem<10 ){
  1139   1277         nMem = 10;
  1140   1278       }
  1141   1279       memset(zCsr, 0, zEnd-zCsr);
  1142   1280       zCsr += (zCsr - (u8*)0)&7;
  1143   1281       assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
................................................................................
  1227   1365       p->inVtabMethod = 0;
  1228   1366     }
  1229   1367   #endif
  1230   1368     if( !pCx->ephemPseudoTable ){
  1231   1369       sqlite3DbFree(p->db, pCx->pData);
  1232   1370     }
  1233   1371   }
         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  +*/
         1378  +int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
         1379  +  Vdbe *v = pFrame->v;
         1380  +  v->aOp = pFrame->aOp;
         1381  +  v->nOp = pFrame->nOp;
         1382  +  v->aMem = pFrame->aMem;
         1383  +  v->nMem = pFrame->nMem;
         1384  +  v->apCsr = pFrame->apCsr;
         1385  +  v->nCursor = pFrame->nCursor;
         1386  +  v->db->lastRowid = pFrame->lastRowid;
         1387  +  v->nChange = pFrame->nChange;
         1388  +  return pFrame->pc;
         1389  +}
  1234   1390   
  1235   1391   /*
  1236   1392   ** Close all cursors.
         1393  +**
         1394  +** Also release any dynamic memory held by the VM in the Vdbe.aMem memory 
         1395  +** cell array. This is necessary as the memory cell array may contain
         1396  +** pointers to VdbeFrame objects, which may in turn contain pointers to
         1397  +** open cursors.
  1237   1398   */
  1238   1399   static void closeAllCursors(Vdbe *p){
  1239         -  int i;
  1240         -  if( p->apCsr==0 ) return;
  1241         -  for(i=0; i<p->nCursor; i++){
  1242         -    VdbeCursor *pC = p->apCsr[i];
  1243         -    if( pC ){
  1244         -      sqlite3VdbeFreeCursor(p, pC);
  1245         -      p->apCsr[i] = 0;
         1400  +  if( p->pFrame ){
         1401  +    VdbeFrame *pFrame = p->pFrame;
         1402  +    for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
         1403  +    sqlite3VdbeFrameRestore(pFrame);
         1404  +  }
         1405  +  p->pFrame = 0;
         1406  +  p->nFrame = 0;
         1407  +
         1408  +  if( p->apCsr ){
         1409  +    int i;
         1410  +    for(i=0; i<p->nCursor; i++){
         1411  +      VdbeCursor *pC = p->apCsr[i];
         1412  +      if( pC ){
         1413  +        sqlite3VdbeFreeCursor(p, pC);
         1414  +        p->apCsr[i] = 0;
         1415  +      }
  1246   1416       }
  1247   1417     }
         1418  +  if( p->aMem ){
         1419  +    releaseMemArray(&p->aMem[1], p->nMem);
         1420  +  }
  1248   1421   }
  1249   1422   
  1250   1423   /*
  1251   1424   ** Clean up the VM after execution.
  1252   1425   **
  1253   1426   ** This routine will automatically close any cursors, lists, and/or
  1254   1427   ** sorters that were left open.  It also deletes the values of
  1255   1428   ** variables in the aVar[] array.
  1256   1429   */
  1257   1430   static void Cleanup(Vdbe *p){
  1258         -  int i;
  1259   1431     sqlite3 *db = p->db;
  1260         -  Mem *pMem;
  1261         -  closeAllCursors(p);
  1262         -  for(pMem=&p->aMem[1], i=1; i<=p->nMem; i++, pMem++){
  1263         -    if( pMem->flags & MEM_RowSet ){
  1264         -      sqlite3RowSetClear(pMem->u.pRowSet);
  1265         -    }
  1266         -    MemSetTypeFlag(pMem, MEM_Null);
  1267         -  }
  1268         -  releaseMemArray(&p->aMem[1], p->nMem);
  1269         -  if( p->contextStack ){
  1270         -    sqlite3DbFree(db, p->contextStack);
  1271         -  }
  1272         -  p->contextStack = 0;
  1273         -  p->contextStackDepth = 0;
  1274         -  p->contextStackTop = 0;
         1432  +
         1433  +#ifdef SQLITE_DEBUG
         1434  +  /* Execute assert() statements to ensure that the Vdbe.apCsr[] and 
         1435  +  ** Vdbe.aMem[] arrays have already been cleaned up.  */
         1436  +  int i;
         1437  +  for(i=0; i<p->nCursor; i++) assert( p->apCsr==0 || p->apCsr[i]==0 );
         1438  +  for(i=1; i<=p->nMem; i++) assert( p->aMem==0 || p->aMem[i].flags==MEM_Null );
         1439  +#endif
         1440  +
  1275   1441     sqlite3DbFree(db, p->zErrMsg);
  1276   1442     p->zErrMsg = 0;
  1277   1443     p->pResultSet = 0;
  1278   1444   }
  1279   1445   
  1280   1446   /*
  1281   1447   ** Set the number of result columns that will be returned by this SQL
................................................................................
  1992   2158     }
  1993   2159   }
  1994   2160   
  1995   2161   /*
  1996   2162   ** Delete an entire VDBE.
  1997   2163   */
  1998   2164   void sqlite3VdbeDelete(Vdbe *p){
  1999         -  int i;
  2000   2165     sqlite3 *db;
  2001   2166   
  2002   2167     if( NEVER(p==0) ) return;
  2003   2168     db = p->db;
  2004   2169     if( p->pPrev ){
  2005   2170       p->pPrev->pNext = p->pNext;
  2006   2171     }else{
  2007   2172       assert( db->pVdbe==p );
  2008   2173       db->pVdbe = p->pNext;
  2009   2174     }
  2010   2175     if( p->pNext ){
  2011   2176       p->pNext->pPrev = p->pPrev;
  2012   2177     }
  2013         -  if( p->aOp ){
  2014         -    Op *pOp = p->aOp;
  2015         -    for(i=0; i<p->nOp; i++, pOp++){
  2016         -      freeP4(db, pOp->p4type, pOp->p4.p);
  2017         -#ifdef SQLITE_DEBUG
  2018         -      sqlite3DbFree(db, pOp->zComment);
  2019         -#endif     
  2020         -    }
  2021         -  }
  2022   2178     releaseMemArray(p->aVar, p->nVar);
  2023         -  sqlite3DbFree(db, p->aLabel);
  2024   2179     releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
         2180  +  vdbeFreeOpArray(db, p->aOp, p->nOp);
         2181  +  sqlite3DbFree(db, p->aLabel);
  2025   2182     sqlite3DbFree(db, p->aColName);
  2026   2183     sqlite3DbFree(db, p->zSql);
  2027   2184     p->magic = VDBE_MAGIC_DEAD;
  2028         -  sqlite3DbFree(db, p->aOp);
  2029   2185     sqlite3DbFree(db, p->pFree);
  2030   2186     sqlite3DbFree(db, p);
  2031   2187   }
  2032   2188   
  2033   2189   /*
  2034   2190   ** Make sure the cursor p is ready to read or write the row to which it
  2035   2191   ** was last positioned.  Return an error code if an OOM fault or I/O error

Changes to src/vdbeblob.c.

   200    200         ** always return an SQL NULL. This is useful because it means
   201    201         ** we can invoke OP_Column to fill in the vdbe cursors type 
   202    202         ** and offset cache without causing any IO.
   203    203         */
   204    204         sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
   205    205         sqlite3VdbeChangeP2(v, 7, pTab->nCol);
   206    206         if( !db->mallocFailed ){
   207         -        sqlite3VdbeMakeReady(v, 1, 1, 1, 0);
          207  +        sqlite3VdbeMakeReady(v, 1, 1, 1, 0, 0);
   208    208         }
   209    209       }
   210    210      
   211    211       sqlite3BtreeLeaveAll(db);
   212    212       rc = sqlite3SafetyOff(db);
   213    213       if( NEVER(rc!=SQLITE_OK) || db->mallocFailed ){
   214    214         goto blob_open_out;

Changes to src/vdbemem.c.

   266    266   /*
   267    267   ** If the memory cell contains a string value that must be freed by
   268    268   ** invoking an external callback, free it now. Calling this function
   269    269   ** does not free any Mem.zMalloc buffer.
   270    270   */
   271    271   void sqlite3VdbeMemReleaseExternal(Mem *p){
   272    272     assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
   273         -  if( p->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet) ){
          273  +  if( p->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame) ){
   274    274       if( p->flags&MEM_Agg ){
   275    275         sqlite3VdbeMemFinalize(p, p->u.pDef);
   276    276         assert( (p->flags & MEM_Agg)==0 );
   277    277         sqlite3VdbeMemRelease(p);
   278    278       }else if( p->flags&MEM_Dyn && p->xDel ){
   279    279         assert( (p->flags&MEM_RowSet)==0 );
   280    280         p->xDel((void *)p->z);
   281    281         p->xDel = 0;
   282    282       }else if( p->flags&MEM_RowSet ){
   283    283         sqlite3RowSetClear(p->u.pRowSet);
          284  +    }else if( p->flags&MEM_Frame ){
          285  +      sqlite3VdbeFrameDelete(p->u.pFrame);
          286  +      p->flags &= ~MEM_Frame;
   284    287       }
   285    288     }
   286    289   }
   287    290   
   288    291   /*
   289    292   ** Release any memory held by the Mem. This may leave the Mem in an
   290    293   ** inconsistent state, for example with (Mem.z==0) and
................................................................................
   478    481     return SQLITE_OK;
   479    482   }
   480    483   
   481    484   /*
   482    485   ** Delete any previous value and set the value stored in *pMem to NULL.
   483    486   */
   484    487   void sqlite3VdbeMemSetNull(Mem *pMem){
          488  +  if( pMem->flags & MEM_Frame ){
          489  +    sqlite3VdbeFrameDelete(pMem->u.pFrame);
          490  +  }
   485    491     if( pMem->flags & MEM_RowSet ){
   486    492       sqlite3RowSetClear(pMem->u.pRowSet);
   487    493     }
   488    494     MemSetTypeFlag(pMem, MEM_Null);
   489    495     pMem->type = SQLITE_NULL;
   490    496   }
   491    497   

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    947   
   947    948     assert( IsVirtual(pTab) );
   948         -  for(i=0; i<pParse->nVtabLock; i++){
   949         -    if( pTab==pParse->apVtabLock[i] ) return;
          949  +  for(i=0; i<pToplevel->nVtabLock; i++){
          950  +    if( pTab==pToplevel->apVtabLock[i] ) return;
   950    951     }
   951         -  n = (pParse->nVtabLock+1)*sizeof(pParse->apVtabLock[0]);
   952         -  apVtabLock = sqlite3_realloc(pParse->apVtabLock, n);
          952  +  n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
          953  +  apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
   953    954     if( apVtabLock ){
   954         -    pParse->apVtabLock = apVtabLock;
   955         -    pParse->apVtabLock[pParse->nVtabLock++] = pTab;
          955  +    pToplevel->apVtabLock = apVtabLock;
          956  +    pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
   956    957     }else{
   957         -    pParse->db->mallocFailed = 1;
          958  +    pToplevel->db->mallocFailed = 1;
   958    959     }
   959    960   }
   960    961   
   961    962   #endif /* SQLITE_OMIT_VIRTUALTABLE */

Changes to test/attach3.test.

    19     19   source $testdir/tester.tcl
    20     20   
    21     21   ifcapable !attach {
    22     22     finish_test
    23     23     return
    24     24   }
    25     25   
           26  +# The tests in this file were written before SQLite supported recursive
           27  +# trigger invocation, and some tests depend on that to pass. So disable
           28  +# recursive triggers for this file.
           29  +catchsql { pragma disable_recursive_triggers = 1 } 
           30  +
    26     31   # Create tables t1 and t2 in the main database
    27     32   execsql {
    28     33     CREATE TABLE t1(a, b);
    29     34     CREATE TABLE t2(c, d);
    30     35   }
    31     36   
    32     37   # Create tables t1 and t2 in database file test2.db
................................................................................
   313    318   do_test attach3-12.9 {
   314    319     execsql {
   315    320       ATTACH DATABASE '' AS NULL
   316    321     }
   317    322     db_list
   318    323   } {main temp {}}
   319    324   do_test attach3-12.10 {
          325  +breakpoint
   320    326     execsql {
   321    327       DETACH ?
   322    328     }
   323    329     db_list
   324    330   } {main temp}
   325    331   do_test attach3-12.11 {
   326    332     catchsql {

Changes to test/auth.test.

  2269   2269     set authargs {}
  2270   2270     execsql {
  2271   2271       DELETE FROM v1 WHERE x=117
  2272   2272     }
  2273   2273     set authargs
  2274   2274   } [list \
  2275   2275     SQLITE_DELETE v1     {} main {} \
  2276         -  SQLITE_INSERT v1chng {} main r3 \
  2277         -  SQLITE_READ   v1     x  main r3 \
  2278   2276     SQLITE_SELECT {}     {} {}   v1 \
  2279   2277     SQLITE_READ   t2     a  main v1 \
  2280   2278     SQLITE_READ   t2     b  main v1 \
  2281   2279     SQLITE_SELECT {}     {} {}   {} \
  2282   2280     SQLITE_READ   v1     x  main v1 \
         2281  +  SQLITE_INSERT v1chng {} main r3 \
         2282  +  SQLITE_READ   v1     x  main r3 \
  2283   2283   ]
  2284   2284   
  2285   2285   } ;# ifcapable view && trigger
  2286   2286   
  2287   2287   # Ticket #1338:  Make sure authentication works in the presence of an AS
  2288   2288   # clause.
  2289   2289   #

Changes to test/autoinc.test.

    21     21   # skip all tests in this file.
    22     22   #
    23     23   ifcapable {!autoinc} {
    24     24     finish_test
    25     25     return
    26     26   }
    27     27   
           28  +sqlite3_db_config_lookaside db 0 0 0
           29  +
    28     30   # The database is initially empty.
    29     31   #
    30     32   do_test autoinc-1.1 {
    31     33     execsql {
    32     34       SELECT name FROM sqlite_master WHERE type='table';
    33     35     }
    34     36   } {}
................................................................................
   551    553       INSERT INTO t2 VALUES(NULL, 1);
   552    554       CREATE TABLE t3(a INTEGER PRIMARY KEY AUTOINCREMENT, b);
   553    555       INSERT INTO t3 SELECT * FROM t2 WHERE y>1;
   554    556   
   555    557       SELECT * FROM sqlite_sequence WHERE name='t3';
   556    558     }
   557    559   } {t3 0}
          560  +
          561  +catchsql { pragma disable_recursive_triggers = 1 } 
   558    562   
   559    563   # Ticket #3928.  Make sure that triggers to not make extra slots in
   560    564   # the SQLITE_SEQUENCE table.
   561    565   #
   562    566   do_test autoinc-3928.1 {
   563    567     db eval {
   564    568       CREATE TABLE t3928(a INTEGER PRIMARY KEY AUTOINCREMENT, b);

Changes to test/misc2.test.

    14     14   # left out of other test files.
    15     15   #
    16     16   # $Id: misc2.test,v 1.28 2007/09/12 17:01:45 danielk1977 Exp $
    17     17   
    18     18   set testdir [file dirname $argv0]
    19     19   source $testdir/tester.tcl
    20     20   
           21  +# The tests in this file were written before SQLite supported recursive
           22  +# trigger invocation, and some tests depend on that to pass. So disable
           23  +# recursive triggers for this file.
           24  +catchsql { pragma disable_recursive_triggers = 1 } 
           25  +
    21     26   ifcapable {trigger} {
    22     27   # Test for ticket #360
    23     28   #
    24     29   do_test misc2-1.1 {
    25     30     catchsql {
    26     31       CREATE TABLE FOO(bar integer);
    27     32       CREATE TRIGGER foo_insert BEFORE INSERT ON foo BEGIN
................................................................................
   354    359       execsql {SELECT * FROM t1}
   355    360     } {1 2 3 4 5 6 7 8 9 10}
   356    361   }
   357    362   
   358    363   db close
   359    364   file delete -force test.db
   360    365   sqlite3 db test.db
          366  +catchsql { pragma disable_recursive_triggers = 1 } 
   361    367   
   362    368   # Ticket #453.  If the SQL ended with "-", the tokenizer was calling that
   363    369   # an incomplete token, which caused problem.  The solution was to just call
   364    370   # it a minus sign.
   365    371   #
   366    372   do_test misc2-8.1 {
   367    373     catchsql {-}

Changes to test/tkt3731.test.

    13     13   
    14     14   set testdir [file dirname $argv0]
    15     15   source $testdir/tester.tcl
    16     16   ifcapable {!trigger} {
    17     17     finish_test
    18     18     return
    19     19   }
           20  +
           21  +# The tests in this file were written before SQLite supported recursive
           22  +# trigger invocation, and some tests depend on that to pass. So disable
           23  +# recursive triggers for this file.
           24  +catchsql { pragma disable_recursive_triggers = 1 } 
    20     25   
    21     26   do_test tkt3731-1.1 {
    22     27     execsql {
    23     28       CREATE TABLE t1(a PRIMARY KEY, b);
    24     29       CREATE TRIGGER tr1 AFTER INSERT ON t1 BEGIN
    25     30         INSERT INTO t1 VALUES(new.a || '+', new.b || '+');
    26     31       END;

Changes to test/tkt3992.test.

    68     68         SELECT tcl('set res', typeof(new.c));
    69     69       END;
    70     70   
    71     71       UPDATE t2 SET a = 'I';
    72     72     }
    73     73     set res
    74     74   } {real}
    75         -explain {
    76         -    UPDATE t2 SET a = 'I';
    77         -}
    78     75   
    79     76   
    80     77   finish_test

Changes to test/trigger1.test.

    59     59     catchsql {
    60     60        CREATE TRIGGER trig UPDATE ON t1 FOR EACH STATEMENT BEGIN
    61     61           SELECT * FROM sqlite_master;
    62     62        END;
    63     63     }
    64     64   } {1 {near "STATEMENT": syntax error}}
    65     65   execsql {
    66         -	CREATE TRIGGER tr1 INSERT ON t1 BEGIN
    67         -	  INSERT INTO t1 values(1);
    68         - 	END;
           66  +        CREATE TRIGGER tr1 INSERT ON t1 BEGIN
           67  +          INSERT INTO t1 values(1);
           68  +         END;
    69     69   }
    70     70   do_test trigger1-1.2.0 {
    71     71       catchsql {
    72         -	CREATE TRIGGER IF NOT EXISTS tr1 DELETE ON t1 BEGIN
    73         -	    SELECT * FROM sqlite_master;
    74         - 	END
           72  +        CREATE TRIGGER IF NOT EXISTS tr1 DELETE ON t1 BEGIN
           73  +            SELECT * FROM sqlite_master;
           74  +         END
    75     75        }
    76     76   } {0 {}}
    77     77   do_test trigger1-1.2.1 {
    78     78       catchsql {
    79         -	CREATE TRIGGER tr1 DELETE ON t1 BEGIN
    80         -	    SELECT * FROM sqlite_master;
    81         - 	END
           79  +        CREATE TRIGGER tr1 DELETE ON t1 BEGIN
           80  +            SELECT * FROM sqlite_master;
           81  +         END
    82     82        }
    83     83   } {1 {trigger tr1 already exists}}
    84     84   do_test trigger1-1.2.2 {
    85     85       catchsql {
    86         -	CREATE TRIGGER "tr1" DELETE ON t1 BEGIN
    87         -	    SELECT * FROM sqlite_master;
    88         - 	END
           86  +        CREATE TRIGGER "tr1" DELETE ON t1 BEGIN
           87  +            SELECT * FROM sqlite_master;
           88  +         END
    89     89        }
    90     90   } {1 {trigger "tr1" already exists}}
    91     91   do_test trigger1-1.2.3 {
    92     92       catchsql {
    93         -	CREATE TRIGGER [tr1] DELETE ON t1 BEGIN
    94         -	    SELECT * FROM sqlite_master;
    95         - 	END
           93  +        CREATE TRIGGER [tr1] DELETE ON t1 BEGIN
           94  +            SELECT * FROM sqlite_master;
           95  +         END
    96     96        }
    97     97   } {1 {trigger [tr1] already exists}}
    98     98   
    99     99   do_test trigger1-1.3 {
   100    100       catchsql {
   101         -	BEGIN;
   102         -	CREATE TRIGGER tr2 INSERT ON t1 BEGIN
   103         -	    SELECT * from sqlite_master; END;
          101  +        BEGIN;
          102  +        CREATE TRIGGER tr2 INSERT ON t1 BEGIN
          103  +            SELECT * from sqlite_master; END;
   104    104           ROLLBACK;
   105         -	CREATE TRIGGER tr2 INSERT ON t1 BEGIN
   106         -	    SELECT * from sqlite_master; END;
          105  +        CREATE TRIGGER tr2 INSERT ON t1 BEGIN
          106  +            SELECT * from sqlite_master; END;
   107    107       }
   108    108   } {0 {}}
   109    109   
   110    110   do_test trigger1-1.4 {
   111    111       catchsql {
   112         -	DROP TRIGGER IF EXISTS tr1;
   113         -	CREATE TRIGGER tr1 DELETE ON t1 BEGIN
   114         -	    SELECT * FROM sqlite_master;
   115         -	END
          112  +        DROP TRIGGER IF EXISTS tr1;
          113  +        CREATE TRIGGER tr1 DELETE ON t1 BEGIN
          114  +            SELECT * FROM sqlite_master;
          115  +        END
   116    116       }
   117    117   } {0 {}}
   118    118   
   119    119   do_test trigger1-1.5 {
   120    120       execsql {
   121         -	BEGIN;
   122         -	DROP TRIGGER tr2;
   123         -	ROLLBACK;
   124         -	DROP TRIGGER tr2;
          121  +        BEGIN;
          122  +        DROP TRIGGER tr2;
          123  +        ROLLBACK;
          124  +        DROP TRIGGER tr2;
   125    125       }
   126    126   } {}
   127    127   
   128    128   do_test trigger1-1.6.1 {
   129    129       catchsql {
   130         -	DROP TRIGGER IF EXISTS biggles;
          130  +        DROP TRIGGER IF EXISTS biggles;
   131    131       }
   132    132   } {0 {}}
   133    133   
   134    134   do_test trigger1-1.6.2 {
   135    135       catchsql {
   136         -	DROP TRIGGER biggles;
          136  +        DROP TRIGGER biggles;
   137    137       }
   138    138   } {1 {no such trigger: biggles}}
   139    139   
   140    140   do_test trigger1-1.7 {
   141    141       catchsql {
   142         -	DROP TABLE t1;
   143         -	DROP TRIGGER tr1;
          142  +        DROP TABLE t1;
          143  +        DROP TRIGGER tr1;
   144    144       }
   145    145   } {1 {no such trigger: tr1}}
   146    146   
   147    147   ifcapable tempdb {
   148    148     execsql {
   149    149       CREATE TEMP TABLE temp_table(a);
   150    150     }
   151    151     do_test trigger1-1.8 {
   152    152       execsql {
   153         -  	CREATE TRIGGER temp_trig UPDATE ON temp_table BEGIN
   154         -  	    SELECT * from sqlite_master;
   155         -  	END;
   156         -  	SELECT count(*) FROM sqlite_master WHERE name = 'temp_trig';
          153  +          CREATE TRIGGER temp_trig UPDATE ON temp_table BEGIN
          154  +              SELECT * from sqlite_master;
          155  +          END;
          156  +          SELECT count(*) FROM sqlite_master WHERE name = 'temp_trig';
   157    157       } 
   158    158     } {0}
   159    159   }
   160    160   
   161    161   do_test trigger1-1.9 {
   162    162     catchsql {
   163    163       CREATE TRIGGER tr1 AFTER UPDATE ON sqlite_master BEGIN
................................................................................
   399    399   }
   400    400   do_test trigger1-6.1 {
   401    401     execsql {SELECT type, name FROM sqlite_master}
   402    402   } [concat $view_v1 {table t2}]
   403    403   do_test trigger1-6.2 {
   404    404     execsql {
   405    405       CREATE TRIGGER t2 BEFORE DELETE ON t2 BEGIN
   406         -      SELECT RAISE(ABORT,'deletes are not allows');
          406  +      SELECT RAISE(ABORT,'deletes are not permitted');
   407    407       END;
   408    408       SELECT type, name FROM sqlite_master;
   409    409     }
   410    410   } [concat $view_v1 {table t2 trigger t2}]
   411    411   do_test trigger1-6.3 {
   412    412     catchsql {DELETE FROM t2}
   413         -} {1 {deletes are not allows}}
          413  +} {1 {deletes are not permitted}}
   414    414   do_test trigger1-6.4 {
   415    415     execsql {SELECT * FROM t2}
   416    416   } {3 4 7 8}
   417    417   do_test trigger1-6.5 {
   418    418     db close
   419    419     sqlite3 db test.db
   420    420     execsql {SELECT type, name FROM sqlite_master}

Changes to test/trigger2.test.

    49     49   
    50     50   set testdir [file dirname $argv0]
    51     51   source $testdir/tester.tcl
    52     52   ifcapable {!trigger} {
    53     53     finish_test
    54     54     return
    55     55   }
           56  +
           57  +# The tests in this file were written before SQLite supported recursive
           58  +# trigger invocation, and some tests depend on that to pass. So disable
           59  +# recursive triggers for this file.
           60  +catchsql { pragma disable_recursive_triggers = 1 } 
    56     61   
    57     62   # 1.
    58     63   ifcapable subquery {
    59     64     set ii 0
    60     65     set tbl_definitions [list \
    61     66     	{CREATE TABLE tbl (a, b);}                                      \
    62     67     	{CREATE TABLE tbl (a INTEGER PRIMARY KEY, b);}                  \

Changes to test/trigger3.test.

    13     13   
    14     14   set testdir [file dirname $argv0]
    15     15   source $testdir/tester.tcl
    16     16   ifcapable {!trigger} {
    17     17     finish_test
    18     18     return
    19     19   }
           20  +
           21  +# The tests in this file were written before SQLite supported recursive }
           22  +# trigger invocation, and some tests depend on that to pass. So disable
           23  +# recursive triggers for this file.
           24  +catchsql { pragma disable_recursive_triggers = 1 } 
    20     25   
    21     26   # Test that we can cause ROLLBACK, FAIL and ABORT correctly
    22         -# catchsql { DROP TABLE tbl; }
    23         -catchsql { CREATE TABLE tbl (a, b, c) }
    24         -
           27  +#
           28  +catchsql { CREATE TABLE tbl(a, b ,c) }
    25     29   execsql {
    26     30       CREATE TRIGGER before_tbl_insert BEFORE INSERT ON tbl BEGIN SELECT CASE 
    27     31   	WHEN (new.a = 4) THEN RAISE(IGNORE) END;
    28     32       END;
    29     33   
    30     34       CREATE TRIGGER after_tbl_insert AFTER INSERT ON tbl BEGIN SELECT CASE 
    31     35   	WHEN (new.a = 1) THEN RAISE(ABORT,    'Trigger abort') 
................................................................................
    50     54   do_test trigger3-1.3 {
    51     55       execsql {SELECT * FROM tbl}
    52     56   } {}
    53     57   
    54     58   # FAIL
    55     59   do_test trigger3-2.1 {
    56     60       catchsql {
    57         -	BEGIN;
           61  +        BEGIN;
    58     62           INSERT INTO tbl VALUES (5, 5, 6);
    59     63           INSERT INTO tbl VALUES (2, 5, 6);
    60     64       }
    61     65   } {1 {Trigger fail}}
    62     66   do_test trigger3-2.2 {
    63     67       execsql {
    64     68   	SELECT * FROM tbl;

Changes to test/trigger8.test.

    28     28   # heap, use 1000.
    29     29   #
    30     30   set nStatement 10000
    31     31   if {$tcl_platform(platform) == "symbian"} {
    32     32     set nStatement 1000
    33     33   }
    34     34   
           35  +set nStatement 5
    35     36   do_test trigger8-1.1 {
    36     37     execsql {
    37     38       CREATE TABLE t1(x);
    38     39       CREATE TABLE t2(y);
    39     40     }
    40     41     set sql "CREATE TRIGGER r${nStatement} AFTER INSERT ON t1 BEGIN\n"
    41     42     for {set i 0} {$i<$nStatement} {incr i} {

Changes to test/trigger9.test.

    71     71         END;
    72     72         DELETE FROM t1;
    73     73         SELECT * FROM t2;
    74     74     }
    75     75   } {1 2 3}
    76     76   do_test trigger9-1.3.2 {
    77     77     has_rowdata {DELETE FROM t1}
    78         -} 1
           78  +} 0
    79     79   do_test trigger9-1.3.3 { execsql { ROLLBACK } } {}
    80     80   
    81     81   do_test trigger9-1.4.1 {
    82     82     execsql {
    83     83       BEGIN;
    84     84         CREATE TRIGGER trig1 BEFORE DELETE ON t1 WHEN old.x='1' BEGIN
    85     85           INSERT INTO t2 VALUES(old.rowid);
................................................................................
    86     86         END;
    87     87         DELETE FROM t1;
    88     88         SELECT * FROM t2;
    89     89     }
    90     90   } {1}
    91     91   do_test trigger9-1.4.2 {
    92     92     has_rowdata {DELETE FROM t1}
    93         -} 1
           93  +} 0
    94     94   do_test trigger9-1.4.3 { execsql { ROLLBACK } } {}
    95     95   
    96     96   do_test trigger9-1.5.1 {
    97     97     execsql {
    98     98       BEGIN;
    99     99         CREATE TRIGGER trig1 BEFORE UPDATE ON t1 BEGIN
   100    100           INSERT INTO t2 VALUES(old.rowid);
................................................................................
   116    116         END;
   117    117         UPDATE t1 SET y = '';
   118    118         SELECT * FROM t2;
   119    119     }
   120    120   } {1 2 3}
   121    121   do_test trigger9-1.6.2 {
   122    122     has_rowdata {UPDATE t1 SET y = ''}
   123         -} 1
          123  +} 0
   124    124   do_test trigger9-1.6.3 { execsql { ROLLBACK } } {}
   125    125   
   126    126   do_test trigger9-1.7.1 {
   127    127     execsql {
   128    128       BEGIN;
   129    129         CREATE TRIGGER trig1 BEFORE UPDATE ON t1 WHEN old.x>='2' BEGIN
   130    130           INSERT INTO t2 VALUES(old.x);
................................................................................
   131    131         END;
   132    132         UPDATE t1 SET y = '';
   133    133         SELECT * FROM t2;
   134    134     }
   135    135   } {2 3}
   136    136   do_test trigger9-1.7.2 {
   137    137     has_rowdata {UPDATE t1 SET y = ''}
   138         -} 1
          138  +} 0
   139    139   do_test trigger9-1.7.3 { execsql { ROLLBACK } } {}
   140    140   
   141    141   do_test trigger9-3.1 {
   142    142     execsql {
   143    143       CREATE TABLE t3(a, b);
   144    144       INSERT INTO t3 VALUES(1, 'one');
   145    145       INSERT INTO t3 VALUES(2, 'two');

Added test/triggerC.test.

            1  +# 2009 August 24
            2  +#
            3  +# The author disclaims copyright to this source code.  In place of
            4  +# a legal notice', here is a blessing:
            5  +#
            6  +#    May you do good and not evil.
            7  +#    May you find forgiveness for yourself and forgive others.
            8  +#    May you share freely, never taking more than you give.
            9  +#
           10  +#***********************************************************************
           11  +#
           12  +
           13  +set testdir [file dirname $argv0]
           14  +source $testdir/tester.tcl
           15  +ifcapable {!trigger} {
           16  +  finish_test
           17  +  return
           18  +}
           19  +
           20  +# Enable recursive triggers for this file.
           21  +#
           22  +execsql { PRAGMA disable_recursive_triggers = 0 }
           23  +
           24  +#sqlite3_db_config_lookaside db 0 0 0
           25  +
           26  +#-------------------------------------------------------------------------
           27  +# This block of tests, triggerC-1.*, are not aimed at any specific
           28  +# property of the triggers sub-system. They were created to debug
           29  +# specific problems while modifying SQLite to support recursive
           30  +# triggers. They are left here in case they can help debug the
           31  +# same problems again.
           32  +#
           33  +do_test triggerC-1.1 {
           34  +  execsql {
           35  +    CREATE TABLE t1(a, b, c);
           36  +    CREATE TABLE log(t, a1, b1, c1, a2, b2, c2);
           37  +    CREATE TRIGGER trig1 BEFORE INSERT ON t1 BEGIN
           38  +      INSERT INTO log VALUES('before', NULL, NULL, NULL, new.a, new.b, new.c);
           39  +    END;
           40  +    CREATE TRIGGER trig2 AFTER INSERT ON t1 BEGIN
           41  +      INSERT INTO log VALUES('after', NULL, NULL, NULL, new.a, new.b, new.c);
           42  +    END;
           43  +    CREATE TRIGGER trig3 BEFORE UPDATE ON t1 BEGIN
           44  +      INSERT INTO log VALUES('before', old.a,old.b,old.c, new.a,new.b,new.c);
           45  +    END;
           46  +    CREATE TRIGGER trig4 AFTER UPDATE ON t1 BEGIN
           47  +      INSERT INTO log VALUES('after', old.a,old.b,old.c, new.a,new.b,new.c);
           48  +    END;
           49  +
           50  +    CREATE TRIGGER trig5 BEFORE DELETE ON t1 BEGIN
           51  +      INSERT INTO log VALUES('before', old.a,old.b,old.c, NULL,NULL,NULL);
           52  +    END;
           53  +    CREATE TRIGGER trig6 AFTER DELETE ON t1 BEGIN
           54  +      INSERT INTO log VALUES('after', old.a,old.b,old.c, NULL,NULL,NULL);
           55  +    END;
           56  +  }
           57  +} {}
           58  +do_test triggerC-1.2 {
           59  +  execsql {
           60  +    INSERT INTO t1 VALUES('A', 'B', 'C');
           61  +    SELECT * FROM log;
           62  +  }
           63  +} {before {} {} {} A B C after {} {} {} A B C}
           64  +do_test triggerC-1.3 {
           65  +  execsql { SELECT * FROM t1 }
           66  +} {A B C}
           67  +do_test triggerC-1.4 {
           68  +  execsql {
           69  +    DELETE FROM log;
           70  +    UPDATE t1 SET a = 'a';
           71  +    SELECT * FROM log;
           72  +  }
           73  +} {before A B C a B C after A B C a B C}
           74  +do_test triggerC-1.5 {
           75  +  execsql { SELECT * FROM t1 }
           76  +} {a B C}
           77  +do_test triggerC-1.6 {
           78  +  execsql {
           79  +    DELETE FROM log;
           80  +    DELETE FROM t1;
           81  +    SELECT * FROM log;
           82  +  }
           83  +} {before a B C {} {} {} after a B C {} {} {}}
           84  +do_test triggerC-1.7 {
           85  +  execsql { SELECT * FROM t1 }
           86  +} {}
           87  +do_test triggerC-1.8 {
           88  +  execsql {
           89  +    CREATE TABLE t4(a, b);
           90  +    CREATE TRIGGER t4t AFTER DELETE ON t4 BEGIN
           91  +      SELECT RAISE(ABORT, 'delete is not supported');
           92  +    END;
           93  +  }
           94  +} {}
           95  +do_test triggerC-1.9 {
           96  +  execsql { INSERT INTO t4 VALUES(1, 2) }
           97  +  catchsql { DELETE FROM t4 }
           98  +} {1 {delete is not supported}}
           99  +do_test triggerC-1.10 {
          100  +  execsql { SELECT * FROM t4 }
          101  +} {1 2}
          102  +do_test triggerC-1.11 {
          103  +  execsql {
          104  +    CREATE TABLE t5 (a primary key, b, c);
          105  +    INSERT INTO t5 values (1, 2, 3);
          106  +    CREATE TRIGGER au_tbl AFTER UPDATE ON t5 BEGIN
          107  +      UPDATE OR IGNORE t5 SET a = new.a, c = 10;
          108  +    END;
          109  +  }
          110  +} {}
          111  +do_test triggerC-1.12 {
          112  +  catchsql { UPDATE OR REPLACE t5 SET a = 4 WHERE a = 1 }
          113  +} {1 {too many levels of trigger recursion}}
          114  +do_test triggerC-1.13 {
          115  +  execsql {
          116  +    CREATE TABLE t6(a INTEGER PRIMARY KEY, b);
          117  +    INSERT INTO t6 VALUES(1, 2);
          118  +    create trigger r1 after update on t6 for each row begin
          119  +      SELECT 1;
          120  +    end;
          121  +    UPDATE t6 SET a=a; 
          122  +  }
          123  +} {}
          124  +do_test triggerC-1.14 {
          125  +  execsql {
          126  +    DROP TABLE t1;
          127  +    CREATE TABLE cnt(n);
          128  +    INSERT INTO cnt VALUES(0);
          129  +    CREATE TABLE t1(a INTEGER PRIMARY KEY, b UNIQUE, c, d, e);
          130  +    CREATE INDEX t1cd ON t1(c,d);
          131  +    CREATE TRIGGER t1r1 AFTER UPDATE ON t1 BEGIN UPDATE cnt SET n=n+1; END;
          132  +    INSERT INTO t1 VALUES(1,2,3,4,5);
          133  +    INSERT INTO t1 VALUES(6,7,8,9,10);
          134  +    INSERT INTO t1 VALUES(11,12,13,14,15);
          135  +  }
          136  +} {}
          137  +do_test triggerC-1.15 {
          138  +  catchsql { UPDATE OR ROLLBACK t1 SET a=100 }
          139  +} {1 {PRIMARY KEY must be unique}}
          140  +
          141  +
          142  +#-------------------------------------------------------------------------
          143  +# This block of tests, triggerC-2.*, tests that recursive trigger
          144  +# programs (triggers that fire themselves) work. More specifically,
          145  +# this block focuses on recursive INSERT triggers.
          146  +#
          147  +do_test triggerC-2.1.0 {
          148  +  execsql {
          149  +    CREATE TABLE t2(a PRIMARY KEY);
          150  +  }
          151  +} {}
          152  +
          153  +foreach {n tdefn rc} {
          154  +  1 { 
          155  +    CREATE TRIGGER t2_trig AFTER INSERT ON t2 WHEN (new.a>0) BEGIN
          156  +      INSERT INTO t2 VALUES(new.a - 1);
          157  +    END; 
          158  +  } {0 {10 9 8 7 6 5 4 3 2 1 0}}
          159  +
          160  +  2 {
          161  +    CREATE TRIGGER t2_trig AFTER INSERT ON t2 BEGIN
          162  +      SELECT CASE WHEN new.a==2 THEN RAISE(IGNORE) ELSE NULL END;
          163  +      INSERT INTO t2 VALUES(new.a - 1);
          164  +    END;
          165  +  } {0 {10 9 8 7 6 5 4 3 2}}
          166  +
          167  +  3 { 
          168  +    CREATE TRIGGER t2_trig BEFORE INSERT ON t2 WHEN (new.a>0) BEGIN
          169  +      INSERT INTO t2 VALUES(new.a - 1);
          170  +    END; 
          171  +  } {0 {0 1 2 3 4 5 6 7 8 9 10}}
          172  +
          173  +  4 { 
          174  +    CREATE TRIGGER t2_trig BEFORE INSERT ON t2 BEGIN
          175  +      SELECT CASE WHEN new.a==2 THEN RAISE(IGNORE) ELSE NULL END;
          176  +      INSERT INTO t2 VALUES(new.a - 1);
          177  +    END;
          178  +  } {0 {3 4 5 6 7 8 9 10}}
          179  +
          180  +  5 { 
          181  +    CREATE TRIGGER t2_trig BEFORE INSERT ON t2 BEGIN
          182  +      INSERT INTO t2 VALUES(new.a - 1);
          183  +    END;
          184  +  } {1 {too many levels of trigger recursion}}
          185  +
          186  +  6 { 
          187  +    CREATE TRIGGER t2_trig AFTER INSERT ON t2 WHEN (new.a>0) BEGIN
          188  +      INSERT OR IGNORE INTO t2 VALUES(new.a);
          189  +    END;
          190  +  } {0 10}
          191  +
          192  +  7 { 
          193  +    CREATE TRIGGER t2_trig BEFORE INSERT ON t2 WHEN (new.a>0) BEGIN
          194  +      INSERT OR IGNORE INTO t2 VALUES(new.a);
          195  +    END;
          196  +  } {1 {too many levels of trigger recursion}}
          197  +} {
          198  +  do_test triggerC-2.1.$n {
          199  +    catchsql { DROP TRIGGER t2_trig }
          200  +    execsql  { DELETE FROM t2 }
          201  +    execsql  $tdefn
          202  +    catchsql {
          203  +      INSERT INTO t2 VALUES(10);
          204  +      SELECT * FROM t2;
          205  +    }
          206  +  } $rc
          207  +}
          208  +
          209  +do_test triggerC-2.2 {
          210  +  execsql {
          211  +    CREATE TABLE t22(x);
          212  +
          213  +    CREATE TRIGGER t22a AFTER INSERT ON t22 BEGIN
          214  +      INSERT INTO t22 SELECT x + (SELECT max(x) FROM t22) FROM t22;
          215  +    END;
          216  +    CREATE TRIGGER t22b BEFORE INSERT ON t22 BEGIN
          217  +      SELECT CASE WHEN (SELECT count(*) FROM t22) >= 100
          218  +                  THEN RAISE(IGNORE)
          219  +                  ELSE NULL END;
          220  +    END;
          221  +
          222  +    INSERT INTO t22 VALUES(1);
          223  +    SELECT count(*) FROM t22;
          224  +  }
          225  +} {100}
          226  +
          227  +do_test triggerC-2.3 {
          228  +  execsql {
          229  +    CREATE TABLE t23(x PRIMARY KEY);
          230  +
          231  +    CREATE TRIGGER t23a AFTER INSERT ON t23 BEGIN
          232  +      INSERT INTO t23 VALUES(new.x + 1);
          233  +    END;
          234  +
          235  +    CREATE TRIGGER t23b BEFORE INSERT ON t23 BEGIN
          236  +      SELECT CASE WHEN new.x>500
          237  +                  THEN RAISE(IGNORE)
          238  +                  ELSE NULL END;
          239  +    END;
          240  +
          241  +    INSERT INTO t23 VALUES(1);
          242  +    SELECT count(*) FROM t23;
          243  +  }
          244  +} {500}
          245  + 
          246  +
          247  +#-----------------------------------------------------------------------
          248  +# This block of tests, triggerC-3.*, test that SQLite throws an exception
          249  +# when it detects excessive recursion.
          250  +#
          251  +do_test triggerC-3.1.1 {
          252  +  execsql {
          253  +    CREATE TABLE t3(a, b);
          254  +    CREATE TRIGGER t3i AFTER INSERT ON t3 BEGIN
          255  +      DELETE FROM t3 WHERE rowid = new.rowid;
          256  +    END;
          257  +    CREATE TRIGGER t3d AFTER DELETE ON t3 BEGIN
          258  +      INSERT INTO t3 VALUES(old.a, old.b);
          259  +    END;
          260  +  }
          261  +} {}
          262  +do_test triggerC-3.1.2 {
          263  +  catchsql { INSERT INTO t3 VALUES(0,0) }
          264  +} {1 {too many levels of trigger recursion}}
          265  +do_test triggerC-3.1.3 {
          266  +  execsql { SELECT * FROM t3 }
          267  +} {}
          268  +
          269  +#-----------------------------------------------------------------------
          270  +# This next block of tests, triggerC-4.*, checks that affinity 
          271  +# transformations and constraint processing is performed at the correct 
          272  +# times relative to BEFORE and AFTER triggers.
          273  +#
          274  +# For an INSERT statement, for each row to be inserted:
          275  +#
          276  +#   1. Apply affinities to non-rowid values to be inserted.
          277  +#   2. Fire BEFORE triggers.
          278  +#   3. Process constraints.
          279  +#   4. Insert new record.
          280  +#   5. Fire AFTER triggers.
          281  +#
          282  +# If the value of the rowid field is to be automatically assigned, it is
          283  +# set to -1 in the new.* record. Even if it is explicitly set to NULL
          284  +# by the INSERT statement.
          285  +#
          286  +# For an UPDATE statement, for each row to be deleted:
          287  +#
          288  +#   1. Apply affinities to non-rowid values to be inserted.
          289  +#   2. Fire BEFORE triggers.
          290  +#   3. Process constraints.
          291  +#   4. Insert new record.
          292  +#   5. Fire AFTER triggers.
          293  +#
          294  +# For a DELETE statement, for each row to be deleted:
          295  +#
          296  +#   1. Fire BEFORE triggers.
          297  +#   2. Remove database record.
          298  +#   3. Fire AFTER triggers.
          299  +#
          300  +# When a numeric value that as an exact integer representation is stored
          301  +# in a column with REAL affinity, it is actually stored as an integer.
          302  +# These tests check that the typeof() such values is always 'real',
          303  +# not 'integer'.
          304  +#
          305  +# triggerC-4.1.*: Check that affinity transformations are made before
          306  +#                 triggers are invoked.
          307  +#
          308  +do_test triggerC-4.1.1 {
          309  +  catchsql { DROP TABLE log }
          310  +  catchsql { DROP TABLE t4 }
          311  +  execsql {
          312  +    CREATE TABLE log(t);
          313  +    CREATE TABLE t4(a TEXT,b INTEGER,c REAL);
          314  +    CREATE TRIGGER t4bi BEFORE INSERT ON t4 BEGIN
          315  +      INSERT INTO log VALUES(new.rowid || ' ' || typeof(new.rowid) || ' ' ||
          316  +                             new.a     || ' ' || typeof(new.a)     || ' ' ||
          317  +                             new.b     || ' ' || typeof(new.b)     || ' ' ||
          318  +                             new.c     || ' ' || typeof(new.c)
          319  +      );
          320  +    END;
          321  +    CREATE TRIGGER t4ai AFTER INSERT ON t4 BEGIN
          322  +      INSERT INTO log VALUES(new.rowid || ' ' || typeof(new.rowid) || ' ' ||
          323  +                             new.a     || ' ' || typeof(new.a)     || ' ' ||
          324  +                             new.b     || ' ' || typeof(new.b)     || ' ' ||
          325  +                             new.c     || ' ' || typeof(new.c)
          326  +      );
          327  +    END;
          328  +    CREATE TRIGGER t4bd BEFORE DELETE ON t4 BEGIN
          329  +      INSERT INTO log VALUES(old.rowid || ' ' || typeof(old.rowid) || ' ' ||
          330  +                             old.a     || ' ' || typeof(old.a)     || ' ' ||
          331  +                             old.b     || ' ' || typeof(old.b)     || ' ' ||
          332  +                             old.c     || ' ' || typeof(old.c)
          333  +      );
          334  +    END;
          335  +    CREATE TRIGGER t4ad AFTER DELETE ON t4 BEGIN
          336  +      INSERT INTO log VALUES(old.rowid || ' ' || typeof(old.rowid) || ' ' ||
          337  +                             old.a     || ' ' || typeof(old.a)     || ' ' ||
          338  +                             old.b     || ' ' || typeof(old.b)     || ' ' ||
          339  +                             old.c     || ' ' || typeof(old.c)
          340  +      );
          341  +    END;
          342  +    CREATE TRIGGER t4bu BEFORE UPDATE ON t4 BEGIN
          343  +      INSERT INTO log VALUES(old.rowid || ' ' || typeof(old.rowid) || ' ' ||
          344  +                             old.a     || ' ' || typeof(old.a)     || ' ' ||
          345  +                             old.b     || ' ' || typeof(old.b)     || ' ' ||
          346  +                             old.c     || ' ' || typeof(old.c)
          347  +      );
          348  +      INSERT INTO log VALUES(new.rowid || ' ' || typeof(new.rowid) || ' ' ||
          349  +                             new.a     || ' ' || typeof(new.a)     || ' ' ||
          350  +                             new.b     || ' ' || typeof(new.b)     || ' ' ||
          351  +                             new.c     || ' ' || typeof(new.c)
          352  +      );
          353  +    END;
          354  +    CREATE TRIGGER t4au AFTER UPDATE ON t4 BEGIN
          355  +      INSERT INTO log VALUES(old.rowid || ' ' || typeof(old.rowid) || ' ' ||
          356  +                             old.a     || ' ' || typeof(old.a)     || ' ' ||
          357  +                             old.b     || ' ' || typeof(old.b)     || ' ' ||
          358  +                             old.c     || ' ' || typeof(old.c)
          359  +      );
          360  +      INSERT INTO log VALUES(new.rowid || ' ' || typeof(new.rowid) || ' ' ||
          361  +                             new.a     || ' ' || typeof(new.a)     || ' ' ||
          362  +                             new.b     || ' ' || typeof(new.b)     || ' ' ||
          363  +                             new.c     || ' ' || typeof(new.c)
          364  +      );
          365  +    END;
          366  +  }
          367  +} {}
          368  +foreach {n insert log} {
          369  +
          370  +  2 { 
          371  +   INSERT INTO t4 VALUES('1', '1', '1');
          372  +   DELETE FROM t4;
          373  +  } {
          374  +    -1 integer 1 text 1 integer 1.0 real 
          375  +     1 integer 1 text 1 integer 1.0 real
          376  +     1 integer 1 text 1 integer 1.0 real 
          377  +     1 integer 1 text 1 integer 1.0 real
          378  +  }
          379  +
          380  +  3 { 
          381  +   INSERT INTO t4(rowid,a,b,c) VALUES(45, 45, 45, 45);
          382  +   DELETE FROM t4;
          383  +  } {
          384  +    45 integer 45 text 45 integer 45.0 real
          385  +    45 integer 45 text 45 integer 45.0 real
          386  +    45 integer 45 text 45 integer 45.0 real
          387  +    45 integer 45 text 45 integer 45.0 real
          388  +  }
          389  +
          390  +  4 { 
          391  +   INSERT INTO t4(rowid,a,b,c) VALUES(-42.0, -42.0, -42.0, -42.0);
          392  +   DELETE FROM t4;
          393  +  } {
          394  +    -42 integer -42.0 text -42 integer -42.0 real 
          395  +    -42 integer -42.0 text -42 integer -42.0 real
          396  +    -42 integer -42.0 text -42 integer -42.0 real 
          397  +    -42 integer -42.0 text -42 integer -42.0 real
          398  +  }
          399  +
          400  +  5 { 
          401  +   INSERT INTO t4(rowid,a,b,c) VALUES(NULL, -42.4, -42.4, -42.4);
          402  +   DELETE FROM t4;
          403  +  } {
          404  +    -1 integer -42.4 text -42.4 real -42.4 real
          405  +     1 integer -42.4 text -42.4 real -42.4 real
          406  +     1 integer -42.4 text -42.4 real -42.4 real
          407  +     1 integer -42.4 text -42.4 real -42.4 real
          408  +  }
          409  +
          410  +  6 { 
          411  +   INSERT INTO t4 VALUES(7, 7, 7);
          412  +   UPDATE t4 SET a=8, b=8, c=8;
          413  +  } {
          414  +    -1 integer 7 text 7 integer 7.0 real
          415  +     1 integer 7 text 7 integer 7.0 real
          416  +     1 integer 7 text 7 integer 7.0 real
          417  +     1 integer 8 text 8 integer 8.0 real
          418  +     1 integer 7 text 7 integer 7.0 real
          419  +     1 integer 8 text 8 integer 8.0 real
          420  +  }
          421  +
          422  +  7 { 
          423  +   UPDATE t4 SET rowid=2;
          424  +  } {
          425  +     1 integer 8 text 8 integer 8.0 real
          426  +     2 integer 8 text 8 integer 8.0 real
          427  +     1 integer 8 text 8 integer 8.0 real
          428  +     2 integer 8 text 8 integer 8.0 real
          429  +  }
          430  +
          431  +  8 { 
          432  +   UPDATE t4 SET a='9', b='9', c='9';
          433  +  } {
          434  +     2 integer 8 text 8 integer 8.0 real
          435  +     2 integer 9 text 9 integer 9.0 real
          436  +     2 integer 8 text 8 integer 8.0 real
          437  +     2 integer 9 text 9 integer 9.0 real
          438  +  }
          439  +
          440  +  9 { 
          441  +   UPDATE t4 SET a='9.1', b='9.1', c='9.1';
          442  +  } {
          443  +     2 integer 9   text 9   integer 9.0 real
          444  +     2 integer 9.1 text 9.1 real    9.1 real
          445  +     2 integer 9   text 9   integer 9.0 real
          446  +     2 integer 9.1 text 9.1 real    9.1 real
          447  +  }
          448  +} {
          449  +  do_test triggerC-4.1.$n {
          450  +    eval concat [execsql " 
          451  +      DELETE FROM log;
          452  +      $insert ; 
          453  +      SELECT * FROM log;
          454  +    "]
          455  +  } [join $log " "]
          456  +} 
          457  +
          458  +finish_test
          459  +
          460  +

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