/ Check-in [deacbd21]
Login

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

Overview
Comment:Moving UPDATE towards the iDataCur/iIdxCur representation. Still not working for WITHOUT ROWID, though.
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | omit-rowid
Files: files | file ages | folders
SHA1: deacbd21b50cc8c63a1572d14a4bbc7af4052d37
User & Date: drh 2013-10-31 12:13:37
Context
2013-10-31
15:37
Improved comments and variable names in infrastructure routines of UPDATE, DELETE, and INSERT. check-in: ad90e762 user: drh tags: omit-rowid
12:13
Moving UPDATE towards the iDataCur/iIdxCur representation. Still not working for WITHOUT ROWID, though. check-in: deacbd21 user: drh tags: omit-rowid
11:15
Refactor the INSERT, DELETE, and UPDATE code generators to distinguish between the "data cursor" and the "first index cursor", which are no longer consecutive in the case of a WITHOUT ROWID table. check-in: 1adfca60 user: drh tags: omit-rowid
Changes
Hide Diffs Side-by-Side Diffs Ignore Whitespace Patch

Changes to src/insert.c.

  1117   1117   #endif
  1118   1118   #ifdef pTrigger
  1119   1119    #undef pTrigger
  1120   1120   #endif
  1121   1121   #ifdef tmask
  1122   1122    #undef tmask
  1123   1123   #endif
  1124         -
  1125         -/*
  1126         -** Locate the "principle btree" for a table.  This is the table itself for
  1127         -** ordinary tables, but for WITHOUT ROWID tables, the principle btree is the
  1128         -** PRIMARY KEY index.
  1129         -**
  1130         -** Inputs are pTab and baseCur.  The *ppPk is written with a pointer to the
  1131         -** PRIMARY KEY index for WITHOUT ROWID tables or with NULL for ordinary
  1132         -** tables.  The *piPkCur is written with the cursor to use, assuming that the
  1133         -** table cursor is baseCur and that index cursors are consecutively numbered
  1134         -** thereafter.
  1135         -*/
  1136         -void sqlite3PrincipleBtree(
  1137         -  Table *pTab,        /* The main Table object */
  1138         -  int baseCur,        /* VDBE cursor for main table. */
  1139         -  Index **ppPk,       /* Write PRIMARY KEY index of WITHOUT ROWID tables here */
  1140         -  int *piPkCur        /* Either baseCur or the cursor for *ppPk */
  1141         -){
  1142         -  int pkCur;
  1143         -  Index *pPk;
  1144         -  if( !HasRowid(pTab) ){
  1145         -    pkCur = baseCur+1;
  1146         -    pPk = pTab->pIndex;
  1147         -    while( ALWAYS(pPk) && pPk->autoIndex!=2 ){
  1148         -      pPk=pPk->pNext;
  1149         -      pkCur++;
  1150         -    }
  1151         -  }else{
  1152         -    pkCur = baseCur;
  1153         -    pPk = 0;
  1154         -  }
  1155         -  *ppPk = pPk;
  1156         -  *piPkCur = pkCur;
  1157         -}
  1158         -
  1159   1124   
  1160   1125   /*
  1161   1126   ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
  1162   1127   **
  1163   1128   ** The input is a range of consecutive registers as follows:
  1164   1129   **
  1165   1130   **    1.  The rowid of the row after the update, or NULL

Changes to src/sqliteInt.h.

  2918   2918   int sqlite3ExprCanBeNull(const Expr*);
  2919   2919   void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
  2920   2920   int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
  2921   2921   int sqlite3IsRowid(const char*);
  2922   2922   void sqlite3GenerateRowDelete(Parse*,Table*,Trigger*,int,int,int,i16,u8,u8);
  2923   2923   void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*);
  2924   2924   int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*);
  2925         -void sqlite3PrincipleBtree(Table*,int,Index**,int*);
  2926   2925   void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,int,
  2927   2926                                        int*,int,int,int,int,int*);
  2928   2927   void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
  2929   2928   int sqlite3OpenTableAndIndices(Parse*, Table*, int, int, int*, int*);
  2930   2929   void sqlite3BeginWriteOperation(Parse*, int, int);
  2931   2930   void sqlite3MultiWrite(Parse*);
  2932   2931   void sqlite3MayAbort(Parse*);

Changes to src/update.c.

    97     97     Table *pTab;           /* The table to be updated */
    98     98     int addr = 0;          /* VDBE instruction address of the start of the loop */
    99     99     WhereInfo *pWInfo;     /* Information about the WHERE clause */
   100    100     Vdbe *v;               /* The virtual database engine */
   101    101     Index *pIdx;           /* For looping over indices */
   102    102     Index *pPk;            /* The PRIMARY KEY index for WITHOUT ROWID tables */
   103    103     int nIdx;              /* Number of indices that need updating */
   104         -  int iCur;              /* VDBE Cursor number of pTab */
   105         -  int pkCur;             /* VDBE Cursor for the pPk index */
          104  +  int iTabCur;           /* VDBE Cursor number of pTab */
          105  +  int iDataCur;          /* Cursor for the canonical data btree */
          106  +  int iIdxCur;           /* Cursor for the first index */
   106    107     sqlite3 *db;           /* The database structure */
   107    108     int *aRegIdx = 0;      /* One register assigned to each index to be updated */
   108    109     int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
   109    110                            ** an expression for the i-th column of the table.
   110    111                            ** aXRef[i]==-1 if the i-th column is not changed. */
   111         -  int chngRowid;         /* True if the record number is being changed */
          112  +  int chngPk;            /* True if the rowid or PRIMARY KEY is changed */
   112    113     Expr *pRowidExpr = 0;  /* Expression defining the new record number */
   113    114     int openAll = 0;       /* True if all indices need to be opened */
   114    115     AuthContext sContext;  /* The authorization context */
   115    116     NameContext sNC;       /* The name-context to resolve expressions in */
   116    117     int iDb;               /* Database containing the table being updated */
   117    118     int okOnePass;         /* True for one-pass algorithm without the FIFO */
   118    119     int hasFK;             /* True if foreign key processing is required */
................................................................................
   177    178     for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
   178    179   
   179    180     /* Allocate a cursors for the main database table and for all indices.
   180    181     ** The index cursors might not be used, but if they are used they
   181    182     ** need to occur right after the database cursor.  So go ahead and
   182    183     ** allocate enough space, just in case.
   183    184     */
   184         -  pTabList->a[0].iCursor = iCur = pParse->nTab++;
   185         -  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
          185  +  pTabList->a[0].iCursor = iTabCur = iDataCur = pParse->nTab++;
          186  +  iIdxCur = iTabCur+1;
          187  +  pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
          188  +  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
          189  +    if( pIdx->autoIndex==2 && pPk!=0 ) iDataCur = pParse->nTab;
   186    190       pParse->nTab++;
   187    191     }
   188    192   
   189         -  /* For WITHOUT ROWID tables, we'll need to know the Index and the cursor
   190         -  ** number for the PRIMARY KEY index */
   191         -  sqlite3PrincipleBtree(pTab, iCur, &pPk, &pkCur);
   192         -
   193    193     /* Initialize the name-context */
   194    194     memset(&sNC, 0, sizeof(sNC));
   195    195     sNC.pParse = pParse;
   196    196     sNC.pSrcList = pTabList;
   197    197   
   198    198     /* Resolve the column names in all the expressions of the
   199    199     ** of the UPDATE statement.  Also find the column index
   200    200     ** for each column to be updated in the pChanges array.  For each
   201    201     ** column to be updated, make sure we have authorization to change
   202    202     ** that column.
   203    203     */
   204         -  chngRowid = 0;
          204  +  chngPk = 0;
   205    205     for(i=0; i<pChanges->nExpr; i++){
   206    206       if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
   207    207         goto update_cleanup;
   208    208       }
   209    209       for(j=0; j<pTab->nCol; j++){
   210    210         if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
   211    211           if( j==pTab->iPKey ){
   212         -          chngRowid = 1;
          212  +          chngPk = 1;
   213    213             pRowidExpr = pChanges->a[i].pExpr;
          214  +        }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
          215  +          chngPk = 1;
   214    216           }
   215    217           aXRef[j] = i;
   216    218           break;
   217    219         }
   218    220       }
   219    221       if( j>=pTab->nCol ){
   220    222         if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){
   221    223           j = -1;
   222         -        chngRowid = 1;
          224  +        chngPk = 1;
   223    225           pRowidExpr = pChanges->a[i].pExpr;
   224    226         }else{
   225    227           sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
   226    228           pParse->checkSchema = 1;
   227    229           goto update_cleanup;
   228    230         }
   229    231       }
................................................................................
   238    240         }else if( rc==SQLITE_IGNORE ){
   239    241           aXRef[j] = -1;
   240    242         }
   241    243       }
   242    244   #endif
   243    245     }
   244    246   
   245         -  hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);
          247  +  hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngPk);
   246    248   
   247    249     /* Allocate memory for the array aRegIdx[].  There is one entry in the
   248    250     ** array for each index associated with table being updated.  Fill in
   249    251     ** the value with a register number for indices that are to be used
   250    252     ** and with zero for unused indices.
   251    253     */
   252         -  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
   253    254     if( nIdx>0 ){
   254    255       aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
   255    256       if( aRegIdx==0 ) goto update_cleanup;
   256    257     }
   257    258     for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
   258    259       int reg;
   259         -    if( hasFK || chngRowid || pIdx->pPartIdxWhere ){
          260  +    if( hasFK || chngPk || pIdx->pPartIdxWhere ){
   260    261         reg = ++pParse->nMem;
   261    262       }else{
   262    263         reg = 0;
   263    264         for(i=0; i<pIdx->nColumn; i++){
   264    265           if( aXRef[pIdx->aiColumn[i]]>=0 ){
   265    266             reg = ++pParse->nMem;
   266    267             break;
................................................................................
   290    291     /* Allocate required registers. */
   291    292     regRowSet = ++pParse->nMem;
   292    293     regOldRowid = regNewRowid = ++pParse->nMem;
   293    294     if( pTrigger || hasFK ){
   294    295       regOld = pParse->nMem + 1;
   295    296       pParse->nMem += pTab->nCol;
   296    297     }
   297         -  if( chngRowid || pTrigger || hasFK ){
          298  +  if( chngPk || pTrigger || hasFK ){
   298    299       regNewRowid = ++pParse->nMem;
   299    300     }
   300    301     regNew = pParse->nMem + 1;
   301    302     pParse->nMem += pTab->nCol;
   302    303   
   303    304     /* Start the view context. */
   304    305     if( isView ){
................................................................................
   306    307     }
   307    308   
   308    309     /* If we are trying to update a view, realize that view into
   309    310     ** a ephemeral table.
   310    311     */
   311    312   #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
   312    313     if( isView ){
   313         -    sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
          314  +    sqlite3MaterializeView(pParse, pTab, pWhere, iTabCur);
   314    315     }
   315    316   #endif
   316    317   
   317    318     /* Resolve the column names in all the expressions in the
   318    319     ** WHERE clause.
   319    320     */
   320    321     if( sqlite3ResolveExprNames(&sNC, pWhere) ){
................................................................................
   329    330           pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, 0
   330    331       );
   331    332       if( pWInfo==0 ) goto update_cleanup;
   332    333       okOnePass = sqlite3WhereOkOnePass(pWInfo);
   333    334     
   334    335       /* Remember the rowid of every item to be updated.
   335    336       */
   336         -    sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
          337  +    sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOldRowid);
   337    338       if( !okOnePass ){
   338    339         sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
   339    340       }
   340    341     
   341    342       /* End the database scan loop.
   342    343       */
   343    344       sqlite3WhereEnd(pWInfo);
................................................................................
   353    354       iEph = pParse->nTab++;
   354    355       sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iEph, nPk, 0, 
   355    356                         (char*)sqlite3IndexKeyinfo(pParse, pPk),
   356    357                         P4_KEYINFO_HANDOFF);
   357    358       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, 0, 0);
   358    359       if( pWInfo==0 ) goto update_cleanup;
   359    360       for(i=0; i<nPk; i++){
   360         -      sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, pPk->aiColumn[i], iPk+i);
          361  +      sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, pPk->aiColumn[i],
          362  +                                      iPk+i);
   361    363       }
   362    364       sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
   363    365                         sqlite3IndexAffinityStr(v, pPk), P4_TRANSIENT);
   364    366       sqlite3VdbeAddOp2(v, OP_IdxInsert, iEph, regKey);
   365    367       sqlite3WhereEnd(pWInfo);
   366    368       okOnePass = 0;
   367    369     }
................................................................................
   377    379       /* 
   378    380       ** Open every index that needs updating.  Note that if any
   379    381       ** index could potentially invoke a REPLACE conflict resolution 
   380    382       ** action, then we need to open all indices because we might need
   381    383       ** to be deleting some records.
   382    384       */
   383    385       if( !okOnePass && HasRowid(pTab) ){
   384         -      sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite); 
          386  +      sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenWrite); 
   385    387       }
   386    388       if( onError==OE_Replace ){
   387    389         openAll = 1;
   388    390       }else{
   389    391         openAll = 0;
   390    392         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   391    393           if( pIdx->onError==OE_Replace ){
................................................................................
   394    396           }
   395    397         }
   396    398       }
   397    399       for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
   398    400         assert( aRegIdx );
   399    401         if( openAll || aRegIdx[i]>0 ){
   400    402           KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
   401         -        sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
          403  +        sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdxCur+i, pIdx->tnum, iDb,
   402    404                          (char*)pKey, P4_KEYINFO_HANDOFF);
   403         -        assert( pParse->nTab>iCur+i+1 );
          405  +        assert( pParse->nTab>iIdxCur+i );
   404    406         }
   405    407       }
   406    408     }
   407    409   
   408    410     /* Top of the update loop */
   409    411     labelBreak = sqlite3VdbeMakeLabel(v);
   410    412     labelContinue = sqlite3VdbeMakeLabel(v);
................................................................................
   415    417     }else if( okOnePass ){
   416    418       int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
   417    419       addr = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelBreak);
   418    420       sqlite3VdbeJumpHere(v, a1);
   419    421     }else{
   420    422       addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, labelBreak,
   421    423                                regOldRowid);
   422         -    sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
          424  +    sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addr, regOldRowid);
   423    425     }
   424    426   
   425    427     /* If the record number will change, set register regNewRowid to
   426    428     ** contain the new value. If the record number is not being modified,
   427    429     ** then regNewRowid is the same register as regOldRowid, which is
   428    430     ** already populated.  */
   429         -  assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
   430         -  if( chngRowid ){
          431  +  assert( chngPk || pTrigger || hasFK || regOldRowid==regNewRowid );
          432  +  if( chngPk ){
   431    433       sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
   432    434       sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
   433    435     }
   434    436   
   435    437     /* If there are triggers on this table, populate an array of registers 
   436    438     ** with the required old.* column data.  */
   437    439     if( hasFK || pTrigger ){
   438    440       u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
   439    441       oldmask |= sqlite3TriggerColmask(pParse, 
   440    442           pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
   441    443       );
   442    444       for(i=0; i<pTab->nCol; i++){
   443    445         if( aXRef[i]<0 || oldmask==0xffffffff || (i<32 && (oldmask & (1<<i))) ){
   444         -        sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld+i);
          446  +        sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i);
   445    447         }else{
   446    448           sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
   447    449         }
   448    450       }
   449         -    if( chngRowid==0 ){
          451  +    if( chngPk==0 ){
   450    452         sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
   451    453       }
   452    454     }
   453    455   
   454    456     /* Populate the array of registers beginning at regNew with the new
   455    457     ** row data. This array is used to check constaints, create the new
   456    458     ** table and index records, and as the values for any new.* references
................................................................................
   479    481           /* This branch loads the value of a column that will not be changed 
   480    482           ** into a register. This is done if there are no BEFORE triggers, or
   481    483           ** if there are one or more BEFORE triggers that use this value via
   482    484           ** a new.* reference in a trigger program.
   483    485           */
   484    486           testcase( i==31 );
   485    487           testcase( i==32 );
   486         -        sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
          488  +        sqlite3VdbeAddOp3(v, OP_Column, iDataCur, i, regNew+i);
   487    489           sqlite3ColumnDefault(v, pTab, i, regNew+i);
   488    490         }
   489    491       }
   490    492     }
   491    493   
   492    494     /* Fire any BEFORE UPDATE triggers. This happens before constraints are
   493    495     ** verified. One could argue that this is wrong.
................................................................................
   500    502   
   501    503       /* The row-trigger may have deleted the row being updated. In this
   502    504       ** case, jump to the next row. No updates or AFTER triggers are 
   503    505       ** required. This behavior - what happens when the row being updated
   504    506       ** is deleted or renamed by a BEFORE trigger - is left undefined in the
   505    507       ** documentation.
   506    508       */
   507         -    sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
          509  +    sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addr, regOldRowid);
   508    510   
   509    511       /* If it did not delete it, the row-trigger may still have modified 
   510    512       ** some of the columns of the row being updated. Load the values for 
   511    513       ** all columns not modified by the update statement into their 
   512    514       ** registers in case this has happened.
   513    515       */
   514    516       for(i=0; i<pTab->nCol; i++){
   515    517         if( aXRef[i]<0 && i!=pTab->iPKey ){
   516         -        sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
          518  +        sqlite3VdbeAddOp3(v, OP_Column, iDataCur, i, regNew+i);
   517    519           sqlite3ColumnDefault(v, pTab, i, regNew+i);
   518    520         }
   519    521       }
   520    522     }
   521    523   
   522    524     if( !isView ){
   523    525       int j1;                       /* Address of jump instruction */
   524    526   
   525    527       /* Do constraint checks. */
   526         -    sqlite3GenerateConstraintChecks(pParse, pTab, iCur, iCur+1, regNewRowid,
   527         -        aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
          528  +    sqlite3GenerateConstraintChecks(pParse, pTab, iDataCur, iIdxCur,
          529  +        regNewRowid, aRegIdx, (chngPk?regOldRowid:0), 1, onError, addr, 0);
   528    530   
   529    531       /* Do FK constraint checks. */
   530    532       if( hasFK ){
   531         -      sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngRowid);
          533  +      sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngPk);
   532    534       }
   533    535   
   534    536       /* Delete the index entries associated with the current record.  */
   535    537       if( pPk ){
   536         -      j1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, pkCur, 0, regOldRowid, 1);
          538  +      j1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regOldRowid, 1);
   537    539       }else{
   538         -      j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
   539         -      sqlite3GenerateRowIndexDelete(pParse, pTab, pkCur, iCur+1, aRegIdx);
          540  +      j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid);
          541  +      sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx);
   540    542       }
   541    543     
   542    544       /* If changing the record number, delete the old record.  */
   543         -    if( hasFK || chngRowid ){
   544         -      sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
          545  +    if( hasFK || chngPk ){
          546  +      sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
   545    547       }
   546    548       sqlite3VdbeJumpHere(v, j1);
   547    549   
   548    550       if( hasFK ){
   549         -      sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngRowid);
          551  +      sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngPk);
   550    552       }
   551    553     
   552    554       /* Insert the new index entries and the new record. */
   553         -    sqlite3CompleteInsertion(pParse, pTab, iCur, iCur+1,
          555  +    sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
   554    556                                regNewRowid, aRegIdx, 1, 0, 0);
   555    557   
   556    558       /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
   557    559       ** handle rows (possibly in other tables) that refer via a foreign key
   558    560       ** to the row just updated. */ 
   559    561       if( hasFK ){
   560         -      sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngRowid);
          562  +      sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngPk);
   561    563       }
   562    564     }
   563    565   
   564    566     /* Increment the row counter 
   565    567     */
   566    568     if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
   567    569       sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
................................................................................
   581    583     }
   582    584     sqlite3VdbeResolveLabel(v, labelBreak);
   583    585   
   584    586     /* Close all tables */
   585    587     for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
   586    588       assert( aRegIdx );
   587    589       if( openAll || aRegIdx[i]>0 ){
   588         -      sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
          590  +      sqlite3VdbeAddOp2(v, OP_Close, iIdxCur, 0);
   589    591       }
   590    592     }
   591         -  sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
          593  +  if( iDataCur<iIdxCur ) sqlite3VdbeAddOp2(v, OP_Close, iDataCur, 0);
   592    594   
   593    595     /* Update the sqlite_sequence table by storing the content of the
   594    596     ** maximum rowid counter values recorded while inserting into
   595    597     ** autoincrement tables.
   596    598     */
   597    599     if( pParse->nested==0 && pParse->pTriggerTab==0 ){
   598    600       sqlite3AutoincrementEnd(pParse);