SQLite4
Check-in [4431ab2769f8140feb8f4477cfaea882711d87fc]
Not logged in

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

Overview
SHA1 Hash:4431ab2769f8140feb8f4477cfaea882711d87fc
Date: 2013-09-28 15:07:54
User: dan
Comment:Still further progress on the same.
Tags And Properties
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Changes to src/bt_main.c

277
278
279
280
281
282
283



284
285
286
287
288
289


290
291
292
293
294
295
296
...
600
601
602
603
604
605
606
607
608
609

610
611



612
613
614
615
616
617
618
...
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
...
746
747
748
749
750
751
752























753

754
755
756
757
758
759
760
...
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
...
809
810
811
812
813
814
815
816

817
818
819
820

821
822
823
824
825
826
827
828

829
830
831
832
833
834
835

836
837
838



839

840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
...
921
922
923
924
925
926
927

928
929
930
931
932
933
934
935
936
937
938
939
...
940
941
942
943
944
945
946

947
948

949
950
951
952
953
954
955

956

957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987






988
989
990
991
992
993
994
995
996
997
998
999
1000
1001

1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176


1177
1178
1179
1180

1181

1182








1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
....
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250

1251
1252
1253
1254
1255
1256
1257

1258

1259
1260
1261
1262
1263
1264
1265
....
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302

1303
1304
1305
1306
1307

1308
1309
1310
1311
1312
1313
1314
1315



1316
1317
1318

1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341

1342
1343
1344
1345
1346
1347
1348
1349
1350



1351

1352
1353


1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
....
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
static void printPage(FILE *f, u32 pgno, u8 *aData, int nData){
  int i;
  int nCell = (int)btCellCount(aData, nData);
  fprintf(f, "Page %d: ", pgno);
  fprintf(f, "nCell=%d ", nCell);
  fprintf(f, "iFree=%d ", (int)btFreeOffset(aData, nData));
  fprintf(f, "flags=%d ", (int)btFlags(aData, nData));



  fprintf(f, "cell-offsets=(");
  for(i=0; i<nCell; i++){
    u8 *ptr = btCellPtrFind(aData, nData, i);
    fprintf(f, "%s%d", i==0?"":" ", (int)btGetU16(ptr));
  }
  fprintf(f, ")\n");


}
#endif


/*
** This function compares the key passed via parameters pK and nK to the
** key stored as part of cell iCell on the database page stored in buffer
................................................................................

static u8 *btCellFindSize(u8 *aData, int nData, int iCell, int *pnByte){
  int nKey;
  u8 *pCell;
  u8 *p;

  p = pCell = btCellFind(aData, nData, iCell);

  p += sqlite4BtVarintGet32(p, &nKey);
  p += nKey;

  p += sqlite4BtVarintGet32(p, &nKey);
  p += nKey;




  *pnByte = (p - pCell);
  return pCell;
}

/*
** Allocate a new page buffer.
................................................................................
  int i;                          /* Used to iterate through cells */
  int bLeaf;                      /* True if pPg is a leaf page */
  int nHdr;                       /* Bytes in header of this page */

  if( btNewBuffer(pDb, &aTmp) ) return SQLITE4_NOMEM;

  aData = sqlite4BtPageData(pPg);
  assert( (btFlags(aData, pgsz) & BT_PGFLAGS_INTERNAL)==0 );
  nCell = btCellCount(aData, pgsz);

  bLeaf = 0==(btFlags(aData, pgsz) & BT_PGFLAGS_INTERNAL);
  nHdr = bLeaf ? 1 : 5;

  /* Set header bytes of new page */
  memcpy(aTmp, aData, nHdr);
................................................................................
    i += 4;
  }

  assert( i==btKVCellSize(pKV, pgsz) );
  return i;
}
























static int btGatherSiblings(bt_cursor *pCsr, BtPage **apPg, int *pnPg){

  bt_db * const pDb = pCsr->pDb; 
  const int pgsz = sqlite4BtPagerPagesize(pDb->pPager);

  int rc = SQLITE4_OK;
  int nCell;                      /* Number of cells in parent page */
  u8 *aParent;                    /* Buffer of parent page */
  int iChild;                     /* Index of child page */
................................................................................
  }else{
    nSib = 3;
  }

  if( iChild==0 ){
    iSib = 0;
  }else if( iChild==nCell ){
    iSib = nCell-2;
  }else{
    iSib = iChild-1;
  }

  for(i=0; i<nSib && rc==SQLITE4_OK; i++){
    u32 pgno = btChildPgno(aParent, pgsz, iSib+i);
    rc = sqlite4BtPageGet(pDb->pPager, pgno, &apPg[i]);
  }
  *pnPg = nSib;

  pCsr->aiCell[pCsr->nPg-2] = iSib;
  return rc;
}

static int btSetChildPgno(bt_db *pDb, BtPage *pPg, int iChild, u32 pgno){
  const int pgsz = sqlite4BtPagerPagesize(pDb->pPager);
................................................................................
      btPutU32(pCell, pgno);
    }
  }

  return rc;
}

/* Called recursively by btInsertAndRebalance(). todo: Fix this! */

static int btModifyPage(bt_cursor *, int, int, KeyValue *);

#if 0
/*

** An instance of this structure describes all the cells that will be
** redistributed by a single btRebalance() operation.
*/
struct BtRBIter {
  /* Input parameters */
  int nKV;                        /* Number of KV pairs to add */
  int iKVSib;                     /* Sibling to add KV pairs to */
  int iKVCell;                    /* Cell offset at which to insert KV pairs */

  int nSib;                       /* Number of sibling pages */
  /* Output parameters */
  int iSib;                       /* Sibling page to read cell from (or -ve) */
  int iCell;                      /* Index of cell to read (or -ve) */
};
static void btIterFirst(BtRBIter *p){
  p->iSib = 0;

  p->iCell = 0;
  if( p->iKVSib==0 && p->iKVCell==0 ){
    p->iSib = -1;



  }

}
static void btIterNext(BtRBIter *p){
  p->iCell++;
  /* Just finished the KV pairs */
  if( p->iSib<0 && p->iCell==p->nKV ){
    p->iSib = p->iKVSib;
    p->iCell = p->iKVCell;
  }
  if( p->iSib && p->iCell==p->nKV ){
    p->iSib = p->iKVSib;
    p->iCell = p->iKVCell;
  }
}

static void btIterValid(BtRBIter *p){
  return (p->iSib>=0 || p->iCell>=0);
}
#endif


typedef struct BalanceCtx BalanceCtx;
struct BalanceCtx {
  int pgsz;                       /* Database page size */
  int bLeaf;                      /* True if we are rebalancing leaf data */
  bt_cursor *pCsr;                /* Cursor identifying where to insert pKV */
  KeyValue *pKV;                  /* New KV pair being inserted */
  int nPg;                        /* Number of sibling pages */
  BtPage **apPg;                  /* Array of sibling pages */
  
  int *anOut;                     /* Cell counts for output pages */

  /* Variables used by btBalanceOutput */
  int nOut;                       /* Number of output pages */
  int iOut;                       /* Current output page */
  u8 **apOut;                     /* Buffers to assemble output in */


};

static int btBalanceOutput(
  BalanceCtx *p,                  /* Description of balance operation */
  int iCell,                      /* Cell number in this iteration */
  u8 *pCell, int nByte,           /* Binary cell to copy to output */
  KeyValue *pKV                   /* Key-value cell to write to output */
){
................................................................................
  BalanceCtx *p,
  int (*xVisit)(BalanceCtx*, int, u8*, int, KeyValue*)
){
  const int pgsz = sqlite4BtPagerPagesize(p->pCsr->pDb->pPager);
  int rc = SQLITE4_OK;            /* Return code */
  int iPg;                        /* Current page in apPg[] */
  int iCall = 0;


  BtPage *pIns = p->pCsr->apPage[p->pCsr->nPg-1];
  int iIns = p->pCsr->aiCell[p->pCsr->nPg-1];

  for(iPg=0; iPg<p->nPg && rc==SQLITE4_OK; iPg++){
    BtPage *pPg;                  /* Current page */
    u8 *aData;                    /* Page data */
    int nCell;                    /* Number of cells on page pPg */
    int iCell;                    /* Current cell in pPg */

    pPg = p->apPg[iPg];
    aData = sqlite4BtPageData(pPg);
................................................................................
    nCell = btCellCount(aData, pgsz);

    for(iCell=0; iCell<nCell && rc==SQLITE4_OK; iCell++){
      int nByte;
      u8 *pCell;

      if( pPg==pIns && iCell==iIns ){

        rc = xVisit(p, iCall++, 0, 0, p->pKV);
        if( rc!=SQLITE4_OK ) break;

      }

      pCell = btCellFindSize(aData, pgsz, iCell, &nByte);
      rc = xVisit(p, iCall++, pCell, nByte, 0);
    }

    if( pPg==pIns && iCell==nCell && rc==SQLITE4_OK ){

      rc = xVisit(p, iCall++, 0, 0, p->pKV);

    }
  }

  return rc;
}


int btInsertAndRebalance(bt_cursor *pCsr, KeyValue *pKV){
  bt_db * const pDb = pCsr->pDb; 
  const int pgsz = sqlite4BtPagerPagesize(pDb->pPager);
  const int nSpacePerPage = (pgsz - 1 - 6);

  int nIn = 0;                    /* Number of input pages */
  int iPg;                        /* Used to iterate through pages */
  int iCell;                      /* Used to iterate through cells */
  int nCell = 0;                  /* Total number of cells to redistribute */
  int *anCellSz;                  /* Array containing size in bytes of cells */
  int iIns;                       /* Index of new cell */
  int nOut;                       /* Number of output pages */

  BtPage *apPg[5];                /* Input/output pages */
  int anOut[5];                   /* Cell counts for output pages */
  u8 *apOut[5];                   /* Buffers for assembly of output pages */
  KeyValue aPCell[5];             /* Cells to push into the parent page */
  BtPage *pPar;                   /* Parent page */
  int iSib;                       /* Index of left-most sibling */

  int nTotal;                     /* Total bytes of content to distribute */
  int rc = SQLITE4_OK;            /* Return code */

  BalanceCtx ctx;







  memset(apOut, 0, sizeof(apOut));
  memset(apPg, 0, sizeof(apPg));
  memset(aPCell, 0, sizeof(aPCell));

  /* Gather the sibling pages from which cells will be redistributed into
  ** the apPg[] array.  */
  assert( pCsr->nPg>1 );
  rc = btGatherSiblings(pCsr, apPg, &nIn);
  if( rc!=SQLITE4_OK ) goto rebalance_out;
  pPar = pCsr->apPage[pCsr->nPg-2];
  iSib = pCsr->aiCell[pCsr->nPg-2];

  /* Count the cells on the input pages. This loop also sets iNew. */

  for(iPg=0; iPg<nIn; iPg++){
    u8 *aData = sqlite4BtPageData(apPg[iPg]);
    if( apPg[iPg]==pCsr->apPage[pCsr->nPg-1] ){
      iIns = (nCell + pCsr->aiCell[pCsr->nPg-1]);
      nCell++;
    }
    nCell += btCellCount(aData, pgsz);
  }

  /* Allocate and populate the anCellSz[] array */
  anCellSz = (int*)sqlite4_malloc(pDb->pEnv, sizeof(int) * nCell);
  if( anCellSz==0 ){
    rc = btErrorBkpt(SQLITE4_NOMEM);
    goto rebalance_out;
  }
  iCell = 0;
  for(iPg=0; iPg<nIn; iPg++){
    u8 *aData = sqlite4BtPageData(apPg[iPg]);
    int nPgCell;                  /* Number of cells on page apPg[iPg] */
    int iPgCell;                  /* Index of cell under analysis in page */

    nPgCell = btCellCount(aData, pgsz);
    for(iPgCell=0; iPgCell<nPgCell; iPgCell++){
      if( iCell==iIns ) iCell++;
      btCellFindSize(aData, pgsz, iCell, &anCellSz[iCell]);
      iCell++;
    }
  }
  anCellSz[iIns] = btKVCellSize(pKV, pgsz);

  /* Now figure out the number of output pages. Set nOut to this value. */
  iCell = 0;
  for(iPg=0; iCell<nCell; iPg++){
    int nByte = 0;                /* Number of bytes of content on page */
    assert( iPg<array_size(anOut) );
    for(/* noop */; iCell<nCell; iCell++){
      nByte += (anCellSz[iCell] + 2);
      if( nByte>nSpacePerPage ) break;
    }
    anOut[iPg] = iCell;
  }
  nOut = iPg;
  assert( anOut[nOut-1]==nCell );

  /* Calculate the total size of all cells. */
  nTotal = 0;
  for(iCell=0; iCell<nCell; iCell++) nTotal += (anCellSz[iCell] + 2);

  /* The loop in the previous block populated the anOut[] array in such a
  ** way as to make the (nOut-1) leftmost pages completely full but leave
  ** the rightmost page partially empty. This block redistributes cells
  ** a bit more evenly. This block may reduce one or more of the values in 
  ** the anOut[] array, but will not increase any. No values are reduced
  ** to values lower than 1.  */
  iCell = nCell;
  for(iPg=(nOut-2); iPg>=0; iPg--){
    int nByte = 0;                /* Number of bytes of content on page */
    int nGoal = nTotal / (iPg + 2);

    for(/* noop */; iCell>0 && ((nByte<nGoal) || iCell>anOut[iPg]); iCell--){
      int nThis = (anCellSz[iCell-1] + 2);
      if( (nThis + nByte)>nSpacePerPage ) break;
      nByte += nThis;
    }
    assert( iCell<=anOut[iPg] );
    anOut[iPg] = iCell;
    nTotal = nByte;
  }

#ifndef NDEBUG
  {
    int iDbg;
    fprintf(stderr, "btInsertAndRebalance(): nIn=%d anIn[] = ", nIn);
    for(iDbg=0; iDbg<nIn; iDbg++){
      u8 *aData = sqlite4BtPageData(apPg[iDbg]);
      fprintf(stderr, "%d ", btCellCount(aData, pgsz));
    }
    fprintf(stderr, " ->  nOut=%d anOut[] = ", nOut);
    for(iDbg=0; iDbg<nOut; iDbg++){
      fprintf(stderr, "%d ", anOut[iDbg]);
    }
    fprintf(stderr, "\n");
  }
#endif

  /* Allocate buffers for the output leaves */
  for(iPg=0; iPg<nOut; iPg++){
    rc = btNewBuffer(pDb, &apOut[iPg]);
    if( rc!=SQLITE4_OK ) goto rebalance_out;
    memset(apOut[iPg] + pgsz-6, 0, 6);
  }


  memset(&ctx, 0, sizeof(ctx));
  ctx.pCsr = pCsr;
  ctx.pKV = pKV;
  ctx.nPg = nIn;
  ctx.apPg = apPg;
  ctx.pgsz = pgsz;
  ctx.bLeaf = 1; /* todo */

  ctx.anOut = anOut;
  ctx.nOut = nOut;
  ctx.apOut = apOut;
  rc = btBalanceVisitCells(&ctx, btBalanceOutput);

#if 0
  /* Populate buffers for the output leaves */
  iPgOut = 0;                     /* Index of current output page */
  iPgIn = 0;                      /* Index of current input page */
  iPgInFirst = 0;
  for(iCell=0; iCell<nCell; iCell++){
    int iOff;                     /* Output page offset */
    u8 *aOut;                     /* Output page buffer */

    if( iCell==anOut[iPg] ) iPg++;
    aOut = apOut[iPg];
    iOff = btFreeOffset(aOut, pgsz);

    if( iCell==iIns ){
      iOff += btKVCellWrite(pKV, pgsz, &aOut[iOff]);
    }else{
      u8 *aIn = sqlite4BtPageData(apPg[iPgIn]);
      int iPgCell = iCell - iPgInFirst;
      if( iPgCell>=btCellCount(aIn, pgsz) ){
        iPgIn++;
        iPgInFirst = iCell;
        iPgCell = 0;
        aIn = sqlite4BtPageData(apPg[iPgIn]);
      }
      memcpy(&aOut[iOff], btCellFind(aIn, pgsz, iPgCell), anCellSz[iCell]);
      iOff += anCellSz[iCell];
    }
    btPutU16(&aOut[pgsz-6], iOff);
  }
  for(iPg=0; iPg<nOut; iPg++){
    u8 *aData = apOut[iPg];
    btPutU16(&aData[pgsz-2], anOut[iPg] - (iPg==0 ? 0 : anOut[iPg-1]));
  }
#endif

  /* Clobber the old pages with the new buffers */
  for(iPg=0; iPg<nOut; iPg++){
    if( iPg>=nIn ){
      rc = sqlite4BtPageAllocate(pDb->pPager, &apPg[iPg]);
      if( rc!=SQLITE4_OK ) goto rebalance_out;
    }
    btSetBuffer(pDb, apPg[iPg], apOut[iPg]);
    apOut[iPg] = 0;
  }

#ifndef NDEBUG
  {
    int iDbg;
    for(iDbg=0; iDbg<nOut; iDbg++){
      u8 *aData = sqlite4BtPageData(apPg[iDbg]);
      printPage(stderr, sqlite4BtPagePgno(apPg[iDbg]), aData, pgsz);
    }
  }
#endif

  /* The leaves are written. Now gather the keys and page numbers to
  ** push up into the parent page.  */ 
  for(iPg=0; iPg<(nOut-1); iPg++){
    u8 *aData = sqlite4BtPageData(apPg[iPg]);
    u8 *pCell;

    pCell = btCellFind(aData, pgsz, btCellCount(aData, pgsz)-1);
    aPCell[iPg].pgno = sqlite4BtPagePgno(apPg[iPg]);
    pCell += sqlite4BtVarintGet32(pCell, &aPCell[iPg].nK);
    aPCell[iPg].pK = pCell;
  }

  assert( nIn==1 && nOut==2 );
  rc = btSetChildPgno(pDb, pPar, iSib+nIn-1, sqlite4BtPagePgno(apPg[nOut-1]));


  if( rc!=SQLITE4_OK ) goto rebalance_out;

  pCsr->nPg--;
  rc = btModifyPage(pCsr, nIn-1, nOut-1, aPCell);

  if( rc!=SQLITE4_OK ) goto rebalance_out;










 rebalance_out:
  for(iPg=0; iPg<nIn; iPg++){
    sqlite4BtPageRelease(apPg[iPg]);
  }
  return rc;
}

static int btExtendTree(bt_cursor *pCsr){
  bt_db * const pDb = pCsr->pDb;
  const int pgsz = sqlite4BtPagerPagesize(pDb->pPager);
................................................................................
**       deleted from the page.
**
**     * nKV entries are inserted in their place.
**
** The tree balancing routine is called if this causes the page to
** become either overfull or to contain no entries at all.
*/
static int btModifyPage(
  bt_cursor *pCsr,                /* Cursor identifying page to modify */
  int nDel,                       /* Number of entries to delete from page */
  int nKV,                        /* Number of entries in apKV */
  KeyValue *apKV                  /* New cells to insert into the page */
){
  int rc = SQLITE4_OK;
  const int pgsz = sqlite4BtPagerPagesize(pCsr->pDb->pPager);
  u8 *aData;                      /* Page buffer */
  int nCell;                      /* Number of cells on this page already */
  int nFree;                      /* Contiguous free space on this page */
  int nReq;                       /* Space required for type (a) cell */
  int iCell;                      /* Position to insert new key */
  int iWrite;                     /* Byte offset at which to write new cell */

  BtPage *pLeaf;
  KeyValue *pKV;

  assert( nDel==0 && nKV==1 );
  pKV = apKV;

  /* Bytes of space required on the current page. */

  nReq = btKVCellSize(pKV, pgsz) + 2;


  iCell = pCsr->aiCell[pCsr->nPg-1];
  assert( pCsr->nPg>0 );
  pLeaf = pCsr->apPage[pCsr->nPg-1];
  aData = (u8*)sqlite4BtPageData(pLeaf);

  nCell = btCellCount(aData, pgsz);
................................................................................
    }

    iWrite = btFreeOffset(aData, pgsz);
    nFree = btFreeContiguous(aData, pgsz);
  }

  if( nFree>=nReq ){
    /* The new entry will fit on the leaf page. So in this case all there
    ** is to do is update this single page. The easy case. */
    rc = sqlite4BtPageWrite(pLeaf);
    if( rc==SQLITE4_OK ){
      aData = sqlite4BtPageData(pLeaf);

      /* Update the cell pointer array */
      if( iCell!=nCell ){
        u8 *aFrom = btCellPtrFind(aData, pgsz, nCell-1);
        u8 *aTo = btCellPtrFind(aData, pgsz, nCell);
        memmove(aTo, aFrom, (nCell-iCell) * 2);
      }
      btPutU16(btCellPtrFind(aData, pgsz, iCell), iWrite);


      /* Increase cell count */
      btPutU16(&aData[pgsz-2], nCell+1);
      
      /* Write the cell itself */
      iWrite += btKVCellWrite(pKV, pgsz, &aData[iWrite]);


      /* Set the new total free space */
      if( nCell==0 ){
        btPutU16(&aData[pgsz-4], nFree - nReq);
      }else{
        btPutU16(&aData[pgsz-4], btFreeSpace(aData, pgsz) - nReq);
      }




      /* Set the offset to the block of empty space */
      btPutU16(&aData[pgsz-6], iWrite);
    }

  }else{
    /* The new entry will not fit on the leaf page. Entries will have
    ** to be shuffled between existing leaves and new leaves may need
    ** to be added to make space for it. */
    if( pCsr->nPg==1 ){
      rc = btExtendTree(pCsr);
    }
    if( rc==SQLITE4_OK ){
      rc = btInsertAndRebalance(pCsr, pKV);
    }
  }

  return rc;
}

static int btRemoveFromLeaf(bt_cursor *pCsr){
  const int pgsz = sqlite4BtPagerPagesize(pCsr->pDb->pPager);
  int rc = SQLITE4_OK;            /* Return code */
  BtPage *pLeaf;                  /* Leaf page */

  pLeaf = pCsr->apPage[pCsr->nPg-1];
  rc = sqlite4BtPageWrite(pLeaf);
  if( rc==SQLITE4_OK ){

    u8 *aData;                    /* Page buffer */
    int nCell;                    /* Number of cells initially on this page */
    int iDel;                     /* Index of cell to delete */
    int nByte;                    /* Size of cell to delete in bytes */


    iDel = pCsr->aiCell[pCsr->nPg-1];
    aData = (u8*)sqlite4BtPageData(pLeaf);
    nCell = btCellCount(aData, pgsz);



    btCellFindSize(aData, pgsz, iDel, &nByte);


    if( iDel<(nCell-1) ){


      u8 *aTo = btCellPtrFind(aData, pgsz, nCell-2);
      u8 *aFrom = btCellPtrFind(aData, pgsz, nCell-1);
      memmove(aTo, aFrom, 2*(nCell-iDel-1));
    }

    /* Decrease cell count */
    btPutU16(&aData[pgsz-2], nCell-1);

    /* Increase total free space */
    btPutU16(&aData[pgsz-4], btFreeSpace(aData, pgsz) + nByte + 2);
  }
  
  return rc;
}

/*
** Insert a new key/value pair or replace an existing one.
................................................................................

  if( rc==SQLITE4_NOTFOUND || rc==SQLITE4_INEXACT ){
    /* Insert the new KV pair into the current leaf. */
    KeyValue kv;
    kv.pgno = 0;
    kv.pK = pK; kv.nK = nK;
    kv.pV = pV; kv.nV = nV;
    rc = btModifyPage(&csr, 0, 1, &kv);
  }

  return rc;
}

int sqlite4BtDelete(bt_cursor *pCsr){
  return btRemoveFromLeaf(pCsr);
}

int sqlite4BtSetCookie(bt_db *db, unsigned int iVal){
  return sqlite4BtPagerSetCookie(db->pPager, iVal);
}

int sqlite4BtGetCookie(bt_db *db, unsigned int *piVal){
  return sqlite4BtPagerGetCookie(db->pPager, piVal);
}








>
>
>






>
>







 







<


>
|
|
>
>
>







 







<







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>







 







|






|

|







 







|
>
|

<
<
>
|
<
<
<
<
|
<
<
>
|
<
<
<
<
<
<
>
|
<
<
>
>
>

>

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







 







>




|







 







>
|
|
>







>
|
>







|




<




<
<

<
<
<








>
>
>
>
>
>

<
<



|

|




|
>
|
|
<
<
<
<




|




|
<
<
<
<

<
<
<
<
<
<
<
<
<
|



|




|

|
|






|
|
|
|
|

|



|




|
|






|
|
|


|
|
|






|
|

|



<
<
<
<
<
<
<
<
<
<
<


<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<

|
|
|


|
|





|
|
|






|
|



|




<
|
>
>
|
<
|
|
>
|
>
|
>
>
>
>
>
>
>
>

|
|







 







|

<








|


>

<

<
<
<

>
|
>







 







|





|





<

>
|
|

|
|
>








>
>
>



>








|






|







>



|
<




>
>
>
|
>
|
<
>
>
|

|



|


|







 







|






|










277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
...
605
606
607
608
609
610
611

612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
...
676
677
678
679
680
681
682

683
684
685
686
687
688
689
...
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
...
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
...
840
841
842
843
844
845
846
847
848
849
850


851
852




853


854
855






856
857


858
859
860
861
862
863





































864
865
866
867
868
869
870
...
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
...
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959

960
961
962
963


964



965
966
967
968
969
970
971
972
973
974
975
976
977
978
979


980
981
982
983
984
985
986
987
988
989
990
991
992
993




994
995
996
997
998
999
1000
1001
1002
1003




1004









1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067











1068
1069



































1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101

1102
1103
1104
1105

1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
....
1167
1168
1169
1170
1171
1172
1173
1174
1175

1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188

1189



1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
....
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235

1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286

1287
1288
1289
1290
1291
1292
1293
1294
1295
1296

1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
....
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
static void printPage(FILE *f, u32 pgno, u8 *aData, int nData){
  int i;
  int nCell = (int)btCellCount(aData, nData);
  fprintf(f, "Page %d: ", pgno);
  fprintf(f, "nCell=%d ", nCell);
  fprintf(f, "iFree=%d ", (int)btFreeOffset(aData, nData));
  fprintf(f, "flags=%d ", (int)btFlags(aData, nData));
  if( btFlags(aData, nData) & BT_PGFLAGS_INTERNAL ){
    fprintf(f, "rchild=%d ", (int)btGetU32(&aData[1]));
  }
  fprintf(f, "cell-offsets=(");
  for(i=0; i<nCell; i++){
    u8 *ptr = btCellPtrFind(aData, nData, i);
    fprintf(f, "%s%d", i==0?"":" ", (int)btGetU16(ptr));
  }
  fprintf(f, ")\n");


}
#endif


/*
** This function compares the key passed via parameters pK and nK to the
** key stored as part of cell iCell on the database page stored in buffer
................................................................................

static u8 *btCellFindSize(u8 *aData, int nData, int iCell, int *pnByte){
  int nKey;
  u8 *pCell;
  u8 *p;

  p = pCell = btCellFind(aData, nData, iCell);

  p += sqlite4BtVarintGet32(p, &nKey);
  p += nKey;
  if( 0==(aData[0] & BT_PGFLAGS_INTERNAL) ){
    p += sqlite4BtVarintGet32(p, &nKey);
    p += nKey;
  }else{
    p += 4;
  }

  *pnByte = (p - pCell);
  return pCell;
}

/*
** Allocate a new page buffer.
................................................................................
  int i;                          /* Used to iterate through cells */
  int bLeaf;                      /* True if pPg is a leaf page */
  int nHdr;                       /* Bytes in header of this page */

  if( btNewBuffer(pDb, &aTmp) ) return SQLITE4_NOMEM;

  aData = sqlite4BtPageData(pPg);

  nCell = btCellCount(aData, pgsz);

  bLeaf = 0==(btFlags(aData, pgsz) & BT_PGFLAGS_INTERNAL);
  nHdr = bLeaf ? 1 : 5;

  /* Set header bytes of new page */
  memcpy(aTmp, aData, nHdr);
................................................................................
    i += 4;
  }

  assert( i==btKVCellSize(pKV, pgsz) );
  return i;
}

typedef struct BalanceCtx BalanceCtx;
struct BalanceCtx {
  int pgsz;                       /* Database page size */
  int bLeaf;                      /* True if we are rebalancing leaf data */
  bt_cursor *pCsr;                /* Cursor identifying where to insert pKV */
  int nKV;                        /* Number of KV pairs */
  KeyValue *apKV;                 /* New KV pairs being inserted */

  /* Populated by btGatherSiblings */
  int nIn;                        /* Number of sibling pages */
  BtPage *apPg[5];                /* Array of sibling pages */

  /* Array populated by btBalanceMeasure */
  int *anCellSz;
  
  int anOut[5];                   /* Cell counts for output pages */

  /* Variables used by btBalanceOutput */
  int nOut;                       /* Number of output pages */
  int iOut;                       /* Current output page */
  u8 *apOut[5];                   /* Buffers to assemble output in */
};

static int btGatherSiblings(BalanceCtx *p){
  bt_cursor *pCsr = p->pCsr;
  bt_db * const pDb = pCsr->pDb; 
  const int pgsz = sqlite4BtPagerPagesize(pDb->pPager);

  int rc = SQLITE4_OK;
  int nCell;                      /* Number of cells in parent page */
  u8 *aParent;                    /* Buffer of parent page */
  int iChild;                     /* Index of child page */
................................................................................
  }else{
    nSib = 3;
  }

  if( iChild==0 ){
    iSib = 0;
  }else if( iChild==nCell ){
    iSib = nCell-(nSib-1);
  }else{
    iSib = iChild-1;
  }

  for(i=0; i<nSib && rc==SQLITE4_OK; i++){
    u32 pgno = btChildPgno(aParent, pgsz, iSib+i);
    rc = sqlite4BtPageGet(pDb->pPager, pgno, &p->apPg[i]);
  }
  p->nIn = nSib;

  pCsr->aiCell[pCsr->nPg-2] = iSib;
  return rc;
}

static int btSetChildPgno(bt_db *pDb, BtPage *pPg, int iChild, u32 pgno){
  const int pgsz = sqlite4BtPagerPagesize(pDb->pPager);
................................................................................
      btPutU32(pCell, pgno);
    }
  }

  return rc;
}

/* Called recursively by btBalance(). todo: Fix this! */
static int btInsertAndBalance(bt_cursor *, int, KeyValue *);
static int btDeleteFromPage(bt_cursor *, int);



static int btBalanceMeasure(
  BalanceCtx *p,                  /* Description of balance operation */




  int iCell,                      /* Cell number in this iteration */


  u8 *pCell, int nByte,           /* Binary cell */
  KeyValue *pKV                   /* Key-value cell */






){
  if( pCell ){


    p->anCellSz[iCell] = nByte;
  }else{
    p->anCellSz[iCell] = btKVCellSize(pKV, p->pgsz);
  }
  return SQLITE4_OK;
}






































static int btBalanceOutput(
  BalanceCtx *p,                  /* Description of balance operation */
  int iCell,                      /* Cell number in this iteration */
  u8 *pCell, int nByte,           /* Binary cell to copy to output */
  KeyValue *pKV                   /* Key-value cell to write to output */
){
................................................................................
  BalanceCtx *p,
  int (*xVisit)(BalanceCtx*, int, u8*, int, KeyValue*)
){
  const int pgsz = sqlite4BtPagerPagesize(p->pCsr->pDb->pPager);
  int rc = SQLITE4_OK;            /* Return code */
  int iPg;                        /* Current page in apPg[] */
  int iCall = 0;
  int i;                          /* Used to iterate through KV pairs */

  BtPage *pIns = p->pCsr->apPage[p->pCsr->nPg-1];
  int iIns = p->pCsr->aiCell[p->pCsr->nPg-1];

  for(iPg=0; iPg<p->nIn && rc==SQLITE4_OK; iPg++){
    BtPage *pPg;                  /* Current page */
    u8 *aData;                    /* Page data */
    int nCell;                    /* Number of cells on page pPg */
    int iCell;                    /* Current cell in pPg */

    pPg = p->apPg[iPg];
    aData = sqlite4BtPageData(pPg);
................................................................................
    nCell = btCellCount(aData, pgsz);

    for(iCell=0; iCell<nCell && rc==SQLITE4_OK; iCell++){
      int nByte;
      u8 *pCell;

      if( pPg==pIns && iCell==iIns ){
        for(i=0; i<p->nKV; i++){
          rc = xVisit(p, iCall++, 0, 0, &p->apKV[i]);
          if( rc!=SQLITE4_OK ) break;
        }
      }

      pCell = btCellFindSize(aData, pgsz, iCell, &nByte);
      rc = xVisit(p, iCall++, pCell, nByte, 0);
    }

    if( pPg==pIns && iCell==nCell && rc==SQLITE4_OK ){
      for(i=0; i<p->nKV; i++){
        rc = xVisit(p, iCall++, 0, 0, &p->apKV[i]);
      }
    }
  }

  return rc;
}


int btBalance(bt_cursor *pCsr, int nKV, KeyValue *apKV){
  bt_db * const pDb = pCsr->pDb; 
  const int pgsz = sqlite4BtPagerPagesize(pDb->pPager);
  const int nSpacePerPage = (pgsz - 1 - 6);


  int iPg;                        /* Used to iterate through pages */
  int iCell;                      /* Used to iterate through cells */
  int nCell = 0;                  /* Total number of cells to redistribute */
  int *anCellSz;                  /* Array containing size in bytes of cells */






  KeyValue aPCell[5];             /* Cells to push into the parent page */
  BtPage *pPar;                   /* Parent page */
  int iSib;                       /* Index of left-most sibling */

  int nTotal;                     /* Total bytes of content to distribute */
  int rc = SQLITE4_OK;            /* Return code */

  BalanceCtx ctx;
  memset(&ctx, 0, sizeof(ctx));
  ctx.pCsr = pCsr;
  ctx.nKV = nKV;
  ctx.apKV = apKV;
  ctx.pgsz = pgsz;
  ctx.bLeaf = 1; /* todo */



  memset(aPCell, 0, sizeof(aPCell));

  /* Gather the sibling pages from which cells will be redistributed into
  ** the ctx.apPg[] array.  */
  assert( pCsr->nPg>1 );
  rc = btGatherSiblings(&ctx);
  if( rc!=SQLITE4_OK ) goto rebalance_out;
  pPar = pCsr->apPage[pCsr->nPg-2];
  iSib = pCsr->aiCell[pCsr->nPg-2];

  /* Count the number of input cells */
  nCell = 1;
  for(iPg=0; iPg<ctx.nIn; iPg++){
    u8 *aData = sqlite4BtPageData(ctx.apPg[iPg]);




    nCell += btCellCount(aData, pgsz);
  }

  /* Allocate and populate the anCellSz[] array */
  anCellSz = ctx.anCellSz = (int*)sqlite4_malloc(pDb->pEnv, sizeof(int)*nCell);
  if( anCellSz==0 ){
    rc = btErrorBkpt(SQLITE4_NOMEM);
    goto rebalance_out;
  }
  rc = btBalanceVisitCells(&ctx, btBalanceMeasure);














  /* Now figure out the number of output pages. Set ctx.nOut to this value. */
  iCell = 0;
  for(iPg=0; iCell<nCell; iPg++){
    int nByte = 0;                /* Number of bytes of content on page */
    assert( iPg<array_size(ctx.anOut) );
    for(/* noop */; iCell<nCell; iCell++){
      nByte += (anCellSz[iCell] + 2);
      if( nByte>nSpacePerPage ) break;
    }
    ctx.anOut[iPg] = iCell;
  }
  ctx.nOut = iPg;
  assert( ctx.anOut[ctx.nOut-1]==nCell );

  /* Calculate the total size of all cells. */
  nTotal = 0;
  for(iCell=0; iCell<nCell; iCell++) nTotal += (anCellSz[iCell] + 2);

  /* The loop in the previous block populated the anOut[] array in such a
  ** way as to make the (ctx.nOut-1) leftmost pages completely full but 
  ** leave the rightmost page partially empty. This block redistributes 
  ** cells a bit more evenly. This block may reduce one or more of the 
  ** values in the anOut[] array, but will not increase any. No values 
  ** are reduced to values lower than 1.  */
  iCell = nCell;
  for(iPg=(ctx.nOut-2); iPg>=0; iPg--){
    int nByte = 0;                /* Number of bytes of content on page */
    int nGoal = nTotal / (iPg + 2);

    for( ; iCell>0 && ((nByte<nGoal) || iCell>ctx.anOut[iPg]); iCell--){
      int nThis = (anCellSz[iCell-1] + 2);
      if( (nThis + nByte)>nSpacePerPage ) break;
      nByte += nThis;
    }
    assert( iCell<=ctx.anOut[iPg] );
    ctx.anOut[iPg] = iCell;
    nTotal = nByte;
  }

#ifndef NDEBUG
  {
    int iDbg;
    fprintf(stderr, "btBalance(): nIn=%d anIn[] = ", ctx.nIn);
    for(iDbg=0; iDbg<ctx.nIn; iDbg++){
      u8 *aData = sqlite4BtPageData(ctx.apPg[iDbg]);
      fprintf(stderr, "%d ", btCellCount(aData, pgsz));
    }
    fprintf(stderr, " ->  nOut=%d anOut[] = ", ctx.nOut);
    for(iDbg=0; iDbg<ctx.nOut; iDbg++){
      fprintf(stderr, "%d ", ctx.anOut[iDbg]);
    }
    fprintf(stderr, "\n");
  }
#endif

  /* Allocate buffers for the output leaves */
  for(iPg=0; iPg<ctx.nOut; iPg++){
    rc = btNewBuffer(pDb, &ctx.apOut[iPg]);
    if( rc!=SQLITE4_OK ) goto rebalance_out;
    memset(ctx.apOut[iPg] + pgsz-6, 0, 6);
  }













  rc = btBalanceVisitCells(&ctx, btBalanceOutput);




































  /* Clobber the old pages with the new buffers */
  for(iPg=0; iPg<ctx.nOut; iPg++){
    if( iPg>=ctx.nIn ){
      rc = sqlite4BtPageAllocate(pDb->pPager, &ctx.apPg[iPg]);
      if( rc!=SQLITE4_OK ) goto rebalance_out;
    }
    btSetBuffer(pDb, ctx.apPg[iPg], ctx.apOut[iPg]);
    ctx.apOut[iPg] = 0;
  }

#ifndef NDEBUG
  {
    int iDbg;
    for(iDbg=0; iDbg<ctx.nOut; iDbg++){
      u8 *aData = sqlite4BtPageData(ctx.apPg[iDbg]);
      printPage(stderr, sqlite4BtPagePgno(ctx.apPg[iDbg]), aData, pgsz);
    }
  }
#endif

  /* The leaves are written. Now gather the keys and page numbers to
  ** push up into the parent page.  */ 
  for(iPg=0; iPg<(ctx.nOut-1); iPg++){
    u8 *aData = sqlite4BtPageData(ctx.apPg[iPg]);
    u8 *pCell;

    pCell = btCellFind(aData, pgsz, btCellCount(aData, pgsz)-1);
    aPCell[iPg].pgno = sqlite4BtPagePgno(ctx.apPg[iPg]);
    pCell += sqlite4BtVarintGet32(pCell, &aPCell[iPg].nK);
    aPCell[iPg].pK = pCell;
  }


  rc = btSetChildPgno(
      pDb, pPar, iSib+ctx.nIn-1, sqlite4BtPagePgno(ctx.apPg[ctx.nOut-1])
  );
  if( rc==SQLITE4_OK ){

    pCsr->nPg--;
    rc = btDeleteFromPage(pCsr, ctx.nIn-1);
  }
  if( rc==SQLITE4_OK ){
    rc = btInsertAndBalance(pCsr, ctx.nOut-1, aPCell);
  }

#ifndef NDEBUG
  {
    u8 *aData = sqlite4BtPageData(pPar);
    printPage(stderr, sqlite4BtPagePgno(pPar), aData, pgsz);
  }
#endif

 rebalance_out:
  for(iPg=0; iPg<ctx.nIn; iPg++){
    sqlite4BtPageRelease(ctx.apPg[iPg]);
  }
  return rc;
}

static int btExtendTree(bt_cursor *pCsr){
  bt_db * const pDb = pCsr->pDb;
  const int pgsz = sqlite4BtPagerPagesize(pDb->pPager);
................................................................................
**       deleted from the page.
**
**     * nKV entries are inserted in their place.
**
** The tree balancing routine is called if this causes the page to
** become either overfull or to contain no entries at all.
*/
static int btInsertAndBalance(
  bt_cursor *pCsr,                /* Cursor identifying page to modify */

  int nKV,                        /* Number of entries in apKV */
  KeyValue *apKV                  /* New cells to insert into the page */
){
  int rc = SQLITE4_OK;
  const int pgsz = sqlite4BtPagerPagesize(pCsr->pDb->pPager);
  u8 *aData;                      /* Page buffer */
  int nCell;                      /* Number of cells on this page already */
  int nFree;                      /* Contiguous free space on this page */
  int nReq = 0;                   /* Space required for type (a) cells */
  int iCell;                      /* Position to insert new key */
  int iWrite;                     /* Byte offset at which to write new cell */
  int i;
  BtPage *pLeaf;





  /* Bytes of space required on the current page. */
  for(i=0; i<nKV; i++){
    nReq += btKVCellSize(&apKV[i], pgsz) + 2;
  }

  iCell = pCsr->aiCell[pCsr->nPg-1];
  assert( pCsr->nPg>0 );
  pLeaf = pCsr->apPage[pCsr->nPg-1];
  aData = (u8*)sqlite4BtPageData(pLeaf);

  nCell = btCellCount(aData, pgsz);
................................................................................
    }

    iWrite = btFreeOffset(aData, pgsz);
    nFree = btFreeContiguous(aData, pgsz);
  }

  if( nFree>=nReq ){
    /* The new entry will fit on the page. So in this case all there
    ** is to do is update this single page. The easy case. */
    rc = sqlite4BtPageWrite(pLeaf);
    if( rc==SQLITE4_OK ){
      aData = sqlite4BtPageData(pLeaf);

      /* Make space within the cell pointer array */
      if( iCell!=nCell ){
        u8 *aFrom = btCellPtrFind(aData, pgsz, nCell-1);
        u8 *aTo = btCellPtrFind(aData, pgsz, nCell);
        memmove(aTo, aFrom, (nCell-iCell) * 2);
      }


      for(i=0; i<nKV; i++){
        /* Write the cell pointer */
        btPutU16(btCellPtrFind(aData, pgsz, iCell+i), iWrite);
      
        /* Write the cell itself */
        iWrite += btKVCellWrite(&apKV[i], pgsz, &aData[iWrite]);
      }

      /* Set the new total free space */
      if( nCell==0 ){
        btPutU16(&aData[pgsz-4], nFree - nReq);
      }else{
        btPutU16(&aData[pgsz-4], btFreeSpace(aData, pgsz) - nReq);
      }

      /* Increase cell count */
      btPutU16(&aData[pgsz-2], nCell+nKV);

      /* Set the offset to the block of empty space */
      btPutU16(&aData[pgsz-6], iWrite);
    }

  }else{
    /* The new entry will not fit on the leaf page. Entries will have
    ** to be shuffled between existing leaves and new leaves may need
    ** to be added to make space for it. */
    if( pCsr->nPg==1 ){
      rc = btExtendTree(pCsr);
    }
    if( rc==SQLITE4_OK ){
      rc = btBalance(pCsr, nKV, apKV);
    }
  }

  return rc;
}

static int btDeleteFromPage(bt_cursor *pCsr, int nDel){
  const int pgsz = sqlite4BtPagerPagesize(pCsr->pDb->pPager);
  int rc = SQLITE4_OK;            /* Return code */
  BtPage *pLeaf;                  /* Leaf page */

  pLeaf = pCsr->apPage[pCsr->nPg-1];
  rc = sqlite4BtPageWrite(pLeaf);
  if( rc==SQLITE4_OK ){
    int i;                        /* Used to iterate through cells to delete */
    u8 *aData;                    /* Page buffer */
    int nCell;                    /* Number of cells initially on this page */
    int iDel;                     /* Index of cell to delete */
    int nFreed = 0;               /* Total bytes of space freed */


    iDel = pCsr->aiCell[pCsr->nPg-1];
    aData = (u8*)sqlite4BtPageData(pLeaf);
    nCell = btCellCount(aData, pgsz);

    for(i=iDel; i<(iDel+nDel); i++){
      int nByte;
      btCellFindSize(aData, pgsz, i, &nByte);
      nFreed += nByte + 2;
    }


    if( (iDel+nDel)<nCell ){
      u8 *aTo = btCellPtrFind(aData, pgsz, nCell-1-nDel);
      u8 *aFrom = btCellPtrFind(aData, pgsz, nCell-1);
      memmove(aTo, aFrom, 2*(nCell-(iDel+nDel)));
    }

    /* Decrease cell count */
    btPutU16(&aData[pgsz-2], nCell-nDel);

    /* Increase total free space */
    btPutU16(&aData[pgsz-4], btFreeSpace(aData, pgsz) + nFreed);
  }
  
  return rc;
}

/*
** Insert a new key/value pair or replace an existing one.
................................................................................

  if( rc==SQLITE4_NOTFOUND || rc==SQLITE4_INEXACT ){
    /* Insert the new KV pair into the current leaf. */
    KeyValue kv;
    kv.pgno = 0;
    kv.pK = pK; kv.nK = nK;
    kv.pV = pV; kv.nV = nV;
    rc = btInsertAndBalance(&csr, 1, &kv);
  }

  return rc;
}

int sqlite4BtDelete(bt_cursor *pCsr){
  return btDeleteFromPage(pCsr, 1);
}

int sqlite4BtSetCookie(bt_db *db, unsigned int iVal){
  return sqlite4BtPagerSetCookie(db->pPager, iVal);
}

int sqlite4BtGetCookie(bt_db *db, unsigned int *piVal){
  return sqlite4BtPagerGetCookie(db->pPager, piVal);
}

Changes to test/simple3.test

83
84
85
86
87
88
89
90
91
92
93





















94
95
96
  SELECT a, length(b) FROM t1 
} {1 200  3 200  4 200  5 200}

do_execsql_test 2.4 {
  INSERT INTO t1 VALUES(6, $val);
}

breakpoint
do_execsql_test 2.5 { 
  SELECT a, length(b) FROM t1 
} {1 200  3 200  4 200  5 200  6 200}






















finish_test








<



>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>



83
84
85
86
87
88
89

90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
  SELECT a, length(b) FROM t1 
} {1 200  3 200  4 200  5 200}

do_execsql_test 2.4 {
  INSERT INTO t1 VALUES(6, $val);
}


do_execsql_test 2.5 { 
  SELECT a, length(b) FROM t1 
} {1 200  3 200  4 200  5 200  6 200}

#--------------------------------------------------------------------------
do_test 3.0 {
  catch { db close }
  forcedelete test.db
  sqlite4 db file:test.db?kv=bt
} {}

do_execsql_test 3.1 {
  CREATE TABLE t1(a PRIMARY KEY, b);
}

for {set i 0} {$i < 100} {incr i} {
if {$i==6} breakpoint
  lappend rows $i
  do_execsql_test 3.2.$i {
    INSERT INTO t1 VALUES($i, randomblob(200));
    SELECT a FROM t1 ORDER BY a;
  } $rows
}


finish_test