/ Check-in [2b19be7b]
Login

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

Overview
Comment:Add the sqlite3changeset_apply() function. Does not yet handle all cases.
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | sessions
Files: files | file ages | folders
SHA1:2b19be7bf753c7dd12e1c3b384981a3ea1bc8145
User & Date: dan 2011-03-11 19:05:52
Context
2011-03-12
17:22
Fix some issues with UPDATE changes in the session module. check-in: 57862efe user: dan tags: sessions
2011-03-11
19:05
Add the sqlite3changeset_apply() function. Does not yet handle all cases. check-in: 2b19be7b user: dan tags: sessions
2011-03-09
11:17
Add a function to the session extension invert a changeset. check-in: 75d5dff7 user: dan tags: sessions
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Changes to ext/session/sqlite3session.c.

568
569
570
571
572
573
574









































575
576
577
578
579
580
581
...
612
613
614
615
616
617
618

619
620
621
622
623
624
625
...
663
664
665
666
667
668
669



670
671
672
673
674
675
676
...
682
683
684
685
686
687
688
689
690


























































































691
692
693
694
695
696
697
...
713
714
715
716
717
718
719

720
721
722
723
724
725
726
...
735
736
737
738
739
740
741




742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
...
762
763
764
765
766
767
768

769
770
771
772
773
774
775
...
793
794
795
796
797
798
799

800
801
802
803
804
805
806
...
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
....
1069
1070
1071
1072
1073
1074
1075










1076





































































































































































































































































































































































































































1077
  int *pRc
){
  if( *pRc==SQLITE_OK && 0==sessionBufferGrow(p, nBlob, pRc) ){
    memcpy(&p->aBuf[p->nBuf], aBlob, nBlob);
    p->nBuf += nBlob;
  }
}










































static void sessionAppendCol(
  SessionBuffer *p, 
  sqlite3_stmt *pStmt, 
  int iCol,
  int *pRc
){
................................................................................
  }
}

static void sessionAppendUpdate(
  sqlite3_stmt *pStmt, 
  SessionBuffer *pBuf,
  SessionChange *p,

  int *pRc
){
  if( *pRc==SQLITE_OK ){
    SessionBuffer buf2 = {0, 0, 0};
    int bNoop = 1;
    int i;
    u8 *pCsr = p->aRecord;
................................................................................
           && 0==memcmp(&pCsr[nHdr], sqlite3_column_blob(pStmt, i), nByte)
          ){
            break;
          }
          nCopy = nAdvance;
        }
      }




      if( nCopy==0 ){
        sessionAppendByte(pBuf, 0, pRc);
        sessionAppendByte(&buf2, 0, pRc);
      }else{
        sessionAppendBlob(pBuf, pCsr, nCopy, pRc);
        sessionAppendCol(&buf2, pStmt, i, pRc);
................................................................................
    if( bNoop ){
      pBuf->nBuf -= (1 + sqlite3_column_count(pStmt));
    }else{
      sessionAppendBlob(pBuf, buf2.aBuf, buf2.nBuf, pRc);
      sqlite3_free(buf2.aBuf);
    }
  }




























































































}

/*
** Obtain a changeset object containing all changes recorded by the 
** session object passed as the first argument.
**
** It is the responsibility of the caller to eventually free the buffer 
................................................................................

  for(pTab=pSession->pTable; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
    if( pTab->nEntry ){
      int i;
      sqlite3_stmt *pStmt = 0;
      int bNoop = 1;
      int nRewind = buf.nBuf;


      /* Write a table header */
      sessionAppendByte(&buf, 'T', &rc);
      sessionAppendVarint(&buf, pTab->nCol, &rc);
      sessionAppendBlob(&buf, (u8 *)pTab->zName, strlen(pTab->zName)+1, &rc);

      /* Build and compile a statement to execute: */
................................................................................
        }
        sqlite3_free(zSql);
      }

      if( rc==SQLITE_OK && pTab->nCol!=sqlite3_column_count(pStmt) ){
        rc = SQLITE_SCHEMA;
      }





      for(i=0; i<pTab->nChange; i++){
        SessionChange *p;
        for(p=pTab->apChange[i]; rc==SQLITE_OK && p; p=p->pNext){
          sqlite3_bind_int64(pStmt, 1, p->iKey);
          if( sqlite3_step(pStmt)==SQLITE_ROW ){
            int iCol;
            if( p->aRecord ){
              sessionAppendUpdate(pStmt, &buf, p, &rc);
            }else{
              sessionAppendByte(&buf, SQLITE_INSERT, &rc);
              for(iCol=0; iCol<pTab->nCol; iCol++){
                sessionAppendCol(&buf, pStmt, iCol, &rc);
              }
            }
            bNoop = 0;
................................................................................
            bNoop = 0;
          }
          rc = sqlite3_reset(pStmt);
        }
      }

      sqlite3_finalize(pStmt);


      if( bNoop ){
        buf.nBuf = nRewind;
      }
    }
  }

................................................................................

struct sqlite3_changeset_iter {
  u8 *aChangeset;                 /* Pointer to buffer containing changeset */
  int nChangeset;                 /* Number of bytes in aChangeset */
  u8 *pNext;                      /* Pointer to next change within aChangeset */
  int rc;


  char *zTab;                     /* Current table */
  int nCol;                       /* Number of columns in zTab */
  int op;                         /* Current operation */
  sqlite3_value **apValue;        /* old.* and new.* values */
};

/*
................................................................................
/*
** The following three functions extract information on the current change
** from a changeset iterator. They may only be called after changeset_next()
** has returned SQLITE_ROW.
*/
int sqlite3changeset_op(
  sqlite3_changeset_iter *pIter,
  const char **pzTab,                 /* OUT: Pointer to table name */
  int *pnCol,                         /* OUT: Number of columns in table */
  int *pOp                            /* OUT: SQLITE_INSERT, DELETE or UPDATE */
){
  *pOp = pIter->op;
  *pnCol = pIter->nCol;
  *pzTab = pIter->zTab;
  return SQLITE_OK;
}

int sqlite3changeset_old(
  sqlite3_changeset_iter *pIter,
  int iVal,
  sqlite3_value **ppValue             /* OUT: Old value (or NULL pointer) */
){



  if( iVal<0 || iVal>=pIter->nCol ){
    return SQLITE_RANGE;
  }
  *ppValue = pIter->apValue[iVal];
  return SQLITE_OK;
}

int sqlite3changeset_new(
  sqlite3_changeset_iter *pIter,
  int iVal,
  sqlite3_value **ppValue             /* OUT: New value (or NULL pointer) */
){



  if( iVal<0 || iVal>=pIter->nCol ){
    return SQLITE_RANGE;
  }
  *ppValue = pIter->apValue[pIter->nCol+iVal];
  return SQLITE_OK;
}
















/*
** Finalize an iterator allocated with sqlite3changeset_start().
**
** This function may not be called on iterators passed to a conflict handler
** callback by changeset_apply().
*/
................................................................................
  }

  *pnInverted = nChangeset;
  *ppInverted = (void *)aOut;
  return SQLITE_OK;
}

















































































































































































































































































































































































































































#endif        /* #ifdef SQLITE_ENABLE_SESSION */







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







 







>







 







>
>
>







 







|

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







 







>







 







>
>
>
>








|







 







>







 







>







 







|
|
|










|

>
>
>










|

>
>
>






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







 







>
>
>
>
>
>
>
>
>
>

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

568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
...
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
...
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
...
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
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
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
...
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
...
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
...
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
...
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
....
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
....
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
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
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
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
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
  int *pRc
){
  if( *pRc==SQLITE_OK && 0==sessionBufferGrow(p, nBlob, pRc) ){
    memcpy(&p->aBuf[p->nBuf], aBlob, nBlob);
    p->nBuf += nBlob;
  }
}

static void sessionAppendStr(
  SessionBuffer *p, 
  const char *zStr, 
  int *pRc
){
  int nStr = strlen(zStr);
  if( *pRc==SQLITE_OK && 0==sessionBufferGrow(p, nStr, pRc) ){
    memcpy(&p->aBuf[p->nBuf], zStr, nStr);
    p->nBuf += nStr;
  }
}

static void sessionAppendInteger(
  SessionBuffer *p, 
  int iVal,
  int *pRc
){
  char aBuf[24];
  sqlite3_snprintf(sizeof(aBuf)-1, aBuf, "%d", iVal);
  sessionAppendStr(p, aBuf, pRc);
}

static void sessionAppendIdent(
  SessionBuffer *p, 
  const char *zStr, 
  int *pRc
){
  int nStr = strlen(zStr)*2 + 2 + 1;
  if( *pRc==SQLITE_OK && 0==sessionBufferGrow(p, nStr, pRc) ){
    char *zOut = (char *)&p->aBuf[p->nBuf];
    const char *zIn = zStr;
    *zOut++ = '"';
    while( *zIn ){
      if( *zIn=='"' ) *zOut++ = '"';
      *zOut++ = *(zIn++);
    }
    *zOut++ = '"';
    p->nBuf = ((u8 *)zOut - p->aBuf);
  }
}

static void sessionAppendCol(
  SessionBuffer *p, 
  sqlite3_stmt *pStmt, 
  int iCol,
  int *pRc
){
................................................................................
  }
}

static void sessionAppendUpdate(
  sqlite3_stmt *pStmt, 
  SessionBuffer *pBuf,
  SessionChange *p,
  u8 *abPK,
  int *pRc
){
  if( *pRc==SQLITE_OK ){
    SessionBuffer buf2 = {0, 0, 0};
    int bNoop = 1;
    int i;
    u8 *pCsr = p->aRecord;
................................................................................
           && 0==memcmp(&pCsr[nHdr], sqlite3_column_blob(pStmt, i), nByte)
          ){
            break;
          }
          nCopy = nAdvance;
        }
      }
      if( abPK[i] ){
        nCopy = nAdvance;
      }

      if( nCopy==0 ){
        sessionAppendByte(pBuf, 0, pRc);
        sessionAppendByte(&buf2, 0, pRc);
      }else{
        sessionAppendBlob(pBuf, pCsr, nCopy, pRc);
        sessionAppendCol(&buf2, pStmt, i, pRc);
................................................................................
    if( bNoop ){
      pBuf->nBuf -= (1 + sqlite3_column_count(pStmt));
    }else{
      sessionAppendBlob(pBuf, buf2.aBuf, buf2.nBuf, pRc);
      sqlite3_free(buf2.aBuf);
    }
  }
}

static int sessionTableInfo(
  sqlite3 *db,                    /* Database connection */
  const char *zThis,              /* Table name */
  int nCol,                       /* Expected number of columns */
  const char **pzTab,             /* OUT: Copy of zThis */
  const char ***pazCol,           /* OUT: Array of column names for table */
  u8 **pabPK                      /* OUT: Array of booleans - true for PK col */
){
  char *zPragma;
  sqlite3_stmt *pStmt;
  int rc;
  int nByte;
  int nDbCol = 0;
  int nThis;
  int i;
  u8 *pAlloc;
  u8 *pFree = 0;

  char **azCol;
  u8 *abPK;

  nThis = strlen(zThis);
  zPragma = sqlite3_mprintf("PRAGMA main.table_info('%q')", zThis);
  if( !zPragma ) return SQLITE_NOMEM;

  rc = sqlite3_prepare_v2(db, zPragma, -1, &pStmt, 0);
  sqlite3_free(zPragma);
  if( rc!=SQLITE_OK ) return rc;

  nByte = nThis + 1;
  while( SQLITE_ROW==sqlite3_step(pStmt) ){
    nByte += sqlite3_column_bytes(pStmt, 1);
    nDbCol++;
  }
  rc = sqlite3_reset(pStmt);

  if( nDbCol!=nCol ){
    rc = SQLITE_SCHEMA;
  }
  if( rc==SQLITE_OK ){
    nByte += nDbCol * (sizeof(const char *) + sizeof(u8) + 1);
    pAlloc = sqlite3_malloc(nByte);
    if( pAlloc==0 ){
      rc = SQLITE_NOMEM;
    }
  }
  if( rc==SQLITE_OK ){
    pFree = pAlloc;
    if( pazCol ){
      azCol = (char **)pAlloc;
      pAlloc = (u8 *)&azCol[nCol];
    }
    if( pabPK ){
      abPK = (u8 *)pAlloc;
      pAlloc = &abPK[nCol];
    }
    if( pzTab ){
      memcpy(pAlloc, zThis, nThis+1);
      *pzTab = (char *)pAlloc;
      pAlloc += nThis+1;
    }
  
    i = 0;
    while( SQLITE_ROW==sqlite3_step(pStmt) ){
      int nName = sqlite3_column_bytes(pStmt, 1);
      const unsigned char *zName = sqlite3_column_text(pStmt, 1);
      if( zName==0 ) break;
      if( pazCol ){
        memcpy(pAlloc, zName, nName+1);
        azCol[i] = (char *)pAlloc;
        pAlloc += nName+1;
      }
      if( pabPK ) abPK[i] = sqlite3_column_int(pStmt, 5);
      i++;
    }
    rc = sqlite3_reset(pStmt);
  
  }
  if( rc==SQLITE_OK ){
    if( pazCol ) *pazCol = (const char **)azCol;
    if( pabPK ) *pabPK = abPK;
  }else{
    if( pazCol ) *pazCol = 0;
    if( pabPK ) *pabPK = 0;
    if( pzTab ) *pzTab = 0;
    sqlite3_free(pFree);
  }

  sqlite3_finalize(pStmt);
  return rc;
}

/*
** Obtain a changeset object containing all changes recorded by the 
** session object passed as the first argument.
**
** It is the responsibility of the caller to eventually free the buffer 
................................................................................

  for(pTab=pSession->pTable; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
    if( pTab->nEntry ){
      int i;
      sqlite3_stmt *pStmt = 0;
      int bNoop = 1;
      int nRewind = buf.nBuf;
      u8 *abPK = 0;

      /* Write a table header */
      sessionAppendByte(&buf, 'T', &rc);
      sessionAppendVarint(&buf, pTab->nCol, &rc);
      sessionAppendBlob(&buf, (u8 *)pTab->zName, strlen(pTab->zName)+1, &rc);

      /* Build and compile a statement to execute: */
................................................................................
        }
        sqlite3_free(zSql);
      }

      if( rc==SQLITE_OK && pTab->nCol!=sqlite3_column_count(pStmt) ){
        rc = SQLITE_SCHEMA;
      }

      if( rc==SQLITE_OK ){
        rc = sessionTableInfo(db, pTab->zName, pTab->nCol, 0, 0, &abPK);
      }

      for(i=0; i<pTab->nChange; i++){
        SessionChange *p;
        for(p=pTab->apChange[i]; rc==SQLITE_OK && p; p=p->pNext){
          sqlite3_bind_int64(pStmt, 1, p->iKey);
          if( sqlite3_step(pStmt)==SQLITE_ROW ){
            int iCol;
            if( p->aRecord ){
              sessionAppendUpdate(pStmt, &buf, p, abPK, &rc);
            }else{
              sessionAppendByte(&buf, SQLITE_INSERT, &rc);
              for(iCol=0; iCol<pTab->nCol; iCol++){
                sessionAppendCol(&buf, pStmt, iCol, &rc);
              }
            }
            bNoop = 0;
................................................................................
            bNoop = 0;
          }
          rc = sqlite3_reset(pStmt);
        }
      }

      sqlite3_finalize(pStmt);
      sqlite3_free(abPK);

      if( bNoop ){
        buf.nBuf = nRewind;
      }
    }
  }

................................................................................

struct sqlite3_changeset_iter {
  u8 *aChangeset;                 /* Pointer to buffer containing changeset */
  int nChangeset;                 /* Number of bytes in aChangeset */
  u8 *pNext;                      /* Pointer to next change within aChangeset */
  int rc;

  sqlite3_stmt *pConflict;        /* Conflicting row, if any */
  char *zTab;                     /* Current table */
  int nCol;                       /* Number of columns in zTab */
  int op;                         /* Current operation */
  sqlite3_value **apValue;        /* old.* and new.* values */
};

/*
................................................................................
/*
** The following three functions extract information on the current change
** from a changeset iterator. They may only be called after changeset_next()
** has returned SQLITE_ROW.
*/
int sqlite3changeset_op(
  sqlite3_changeset_iter *pIter,
  const char **pzTab,             /* OUT: Pointer to table name */
  int *pnCol,                     /* OUT: Number of columns in table */
  int *pOp                        /* OUT: SQLITE_INSERT, DELETE or UPDATE */
){
  *pOp = pIter->op;
  *pnCol = pIter->nCol;
  *pzTab = pIter->zTab;
  return SQLITE_OK;
}

int sqlite3changeset_old(
  sqlite3_changeset_iter *pIter,
  int iVal,
  sqlite3_value **ppValue         /* OUT: Old value (or NULL pointer) */
){
  if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_DELETE ){
    return SQLITE_MISUSE;
  }
  if( iVal<0 || iVal>=pIter->nCol ){
    return SQLITE_RANGE;
  }
  *ppValue = pIter->apValue[iVal];
  return SQLITE_OK;
}

int sqlite3changeset_new(
  sqlite3_changeset_iter *pIter,
  int iVal,
  sqlite3_value **ppValue         /* OUT: New value (or NULL pointer) */
){
  if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_INSERT ){
    return SQLITE_MISUSE;
  }
  if( iVal<0 || iVal>=pIter->nCol ){
    return SQLITE_RANGE;
  }
  *ppValue = pIter->apValue[pIter->nCol+iVal];
  return SQLITE_OK;
}

int sqlite3changeset_conflict(
  sqlite3_changeset_iter *pIter,
  int iVal,
  sqlite3_value **ppValue         /* OUT: Value from conflicting row */
){
  if( !pIter->pConflict ){
    return SQLITE_MISUSE;
  }
  if( iVal<0 || iVal>=sqlite3_column_count(pIter->pConflict) ){
    return SQLITE_RANGE;
  }
  *ppValue = sqlite3_column_value(pIter->pConflict, iVal);
  return SQLITE_OK;
}

/*
** Finalize an iterator allocated with sqlite3changeset_start().
**
** This function may not be called on iterators passed to a conflict handler
** callback by changeset_apply().
*/
................................................................................
  }

  *pnInverted = nChangeset;
  *ppInverted = (void *)aOut;
  return SQLITE_OK;
}

static void sessionUpdateDeleteWhere(
  SessionBuffer *pBuf,            /* Buffer to append to */
  int nCol,                       /* Number of entries in azCol and abPK */
  const char **azCol,             /* Column names */
  u8 *abPK,                       /* True for PK columns */ 
  int *pRc                        /* IN/OUT: Error code */
){
  if( *pRc==SQLITE_OK ){
    int i;
    const char *zSep = "";

    sessionAppendStr(pBuf, " WHERE ", pRc);

    for(i=0; i<nCol; i++){
      if( abPK[i] ){
        sessionAppendStr(pBuf, zSep, pRc);
        sessionAppendIdent(pBuf, azCol[i], pRc);
        sessionAppendStr(pBuf, " = ?", pRc);
        sessionAppendInteger(pBuf, i+1, pRc);
        zSep = "AND ";
      }
    }

    sessionAppendStr(pBuf, " AND (?", pRc);
    sessionAppendInteger(pBuf, nCol+1, pRc);
    sessionAppendStr(pBuf, " OR ", pRc);

    zSep = "";
    for(i=0; i<nCol; i++){
      if( !abPK[i] ){
        sessionAppendStr(pBuf, zSep, pRc);
        sessionAppendIdent(pBuf, azCol[i], pRc);
        sessionAppendStr(pBuf, " IS ?", pRc);
        sessionAppendInteger(pBuf, i+1, pRc);
        zSep = "AND ";
      }
    }
    sessionAppendStr(pBuf, ")", pRc);
  }
}

/*
** Formulate a statement to DELETE a row from database db. Assuming a table
** structure like this:
**
**     CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
**
** The DELETE statement looks like this:
**
**     DELETE FROM x WHERE a = :1 AND c = :3 AND :5 OR (b IS :2 AND d IS :4)
**
** Variable :5 (nCol+1) is a boolean. It should be set to 0 if we require
** matching b and d values, or 1 otherwise. The second case comes up if the
** conflict handler is invoked with NOTFOUND and returns CHANGESET_REPLACE.
*/
static int sessionDeleteRow(
  sqlite3 *db,                    /* Database handle */
  const char *zTab,               /* Table name */
  int nCol,                       /* Number of entries in azCol and abPK */
  const char **azCol,             /* Column names */
  u8 *abPK,                       /* True for PK columns */ 
  sqlite3_stmt **ppStmt           /* OUT: Compiled SELECT statement. */
){
  int rc = SQLITE_OK;
  if( *ppStmt==0 ){
    SessionBuffer buf = {0, 0, 0};

    sessionAppendStr(&buf, "DELETE FROM ", &rc);
    sessionAppendIdent(&buf, zTab, &rc);

    sessionUpdateDeleteWhere(&buf, nCol, azCol, abPK, &rc);

    if( rc==SQLITE_OK ){
      rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, ppStmt, 0);
    }
    sqlite3_free(buf.aBuf);
  }

  return rc;
}

/*
** Formulate and prepare a statement to UPDATE a row from database db. 
** Assuming a table structure like this:
**
**     CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
**
** The UPDATE statement looks like this:
**
**     UPDATE x SET
**     a = CASE WHEN ?2  THEN ?3  ELSE a END,
**     b = CASE WHEN ?5  THEN ?6  ELSE a END,
**     c = CASE WHEN ?8  THEN ?9  ELSE a END,
**     d = CASE WHEN ?11 THEN ?12 ELSE a END
**     WHERE a = ?1 AND c = ?7 AND (?13 OR 
**       (?5==0 OR b IS ?4) AND (?11==0 OR b IS ?10) AND
**     )
**
** For each column in the table, there are three variables to bind:
**
**     ?(i*3+1)    The old.* value of the column, if any.
**     ?(i*3+2)    A boolean flag indicating that the value is being modified.
**     ?(i*3+3)    The new.* value of the column, if any.
**
** Also, a boolean flag that, if set to true, causes the statement to update
** a row even if the non-PK values do not match. This is required if the
** conflict-handler is invoked with CHANGESET_DATA and returns
** CHANGESET_REPLACE. This is variable "?(nCol*3+1)".
**
*/
static int sessionUpdateRow(
  sqlite3 *db,                    /* Database handle */
  const char *zTab,               /* Table name */
  int nCol,                       /* Number of entries in azCol and abPK */
  const char **azCol,             /* Column names */
  u8 *abPK,                       /* True for PK columns */ 
  sqlite3_stmt **ppStmt           /* OUT: Compiled SELECT statement. */
){
  int rc = SQLITE_OK;
  if( *ppStmt==0 ){
    int i;
    const char *zSep = "";
    SessionBuffer buf = {0, 0, 0};

    /* Append "UPDATE tbl SET " */
    sessionAppendStr(&buf, "UPDATE ", &rc);
    sessionAppendIdent(&buf, zTab, &rc);
    sessionAppendStr(&buf, " SET ", &rc);

    /* Append the assignments */
    for(i=0; i<nCol; i++){
      sessionAppendStr(&buf, zSep, &rc);
      sessionAppendIdent(&buf, azCol[i], &rc);
      sessionAppendStr(&buf, " = CASE WHEN ?", &rc);
      sessionAppendInteger(&buf, i*3+2, &rc);
      sessionAppendStr(&buf, " THEN ?", &rc);
      sessionAppendInteger(&buf, i*3+3, &rc);
      sessionAppendStr(&buf, " ELSE ", &rc);
      sessionAppendIdent(&buf, azCol[i], &rc);
      sessionAppendStr(&buf, " END", &rc);
      zSep = ", ";
    }

    /* Append the PK part of the WHERE clause */
    sessionAppendStr(&buf, " WHERE ", &rc);
    for(i=0; i<nCol; i++){
      if( abPK[i] ){
        sessionAppendIdent(&buf, azCol[i], &rc);
        sessionAppendStr(&buf, " = ?", &rc);
        sessionAppendInteger(&buf, i*3+1, &rc);
        sessionAppendStr(&buf, " AND ", &rc);
      }
    }

    /* Append the non-PK part of the WHERE clause */
    sessionAppendStr(&buf, " (?", &rc);
    sessionAppendInteger(&buf, nCol*3+1, &rc);
    sessionAppendStr(&buf, " OR 1", &rc);
    for(i=0; i<nCol; i++){
      if( !abPK[i] ){
        sessionAppendStr(&buf, " AND (?", &rc);
        sessionAppendInteger(&buf, i*3+2, &rc);
        sessionAppendStr(&buf, "=0 OR ", &rc);
        sessionAppendIdent(&buf, azCol[i], &rc);
        sessionAppendStr(&buf, " IS ?", &rc);
        sessionAppendInteger(&buf, i*3+1, &rc);
        sessionAppendStr(&buf, ")", &rc);
      }
    }
    sessionAppendStr(&buf, ")", &rc);

    if( rc==SQLITE_OK ){
      rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, ppStmt, 0);
    }
    sqlite3_free(buf.aBuf);
  }

  return rc;
}

static int sessionSelectRow(
  sqlite3 *db,                    /* Database handle */
  const char *zTab,               /* Table name */
  int nCol,                       /* Number of entries in azCol and abPK */
  const char **azCol,             /* Column names */
  u8 *abPK,                       /* True for PK columns */ 
  sqlite3_stmt **ppStmt           /* OUT: Compiled SELECT statement. */
){
  int rc = SQLITE_OK;
  if( *ppStmt==0 ){
    int i;
    const char *zSep = "";
    SessionBuffer buf = {0, 0, 0};
  
    sessionAppendStr(&buf, "SELECT * FROM ", &rc);
    sessionAppendIdent(&buf, zTab, &rc);
    sessionAppendStr(&buf, " WHERE ", &rc);
  
    for(i=0; i<nCol; i++){
      if( abPK[i] ){
        sessionAppendStr(&buf, zSep, &rc);
        sessionAppendIdent(&buf, azCol[i], &rc);
        sessionAppendStr(&buf, " = ?", &rc);
        sessionAppendInteger(&buf, i+1, &rc);
        zSep = " AND ";
      }
    }
  
    if( rc==SQLITE_OK ){
      rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, ppStmt, 0);
    }
    sqlite3_free(buf.aBuf);
  }
  return rc;
}

int sqlite3changeset_apply(
  sqlite3 *db,
  int nChangeset,
  void *pChangeset,
  int(*xConflict)(
    void *pCtx,                   /* Copy of fifth arg to _apply() */
    int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
    sqlite3_changeset_iter *p     /* Handle describing change and conflict */
  ),
  void *pCtx
){
  sqlite3_changeset_iter *pIter;
  int rc;
  int rc2;

  const char *zTab = 0;           /* Name of current table */
  int nTab = 0;                   /* Result of strlen(zTab) */
  int nCol = 0;                   /* Number of columns in table zTab */
  const char **azCol = 0;         /* Array of column names */
  u8 *abPK = 0;                   /* Boolean array - true if column is in PK */

  sqlite3_stmt *pDelete = 0;      /* DELETE statement */
  sqlite3_stmt *pUpdate = 0;      /* DELETE statement */
  sqlite3_stmt *pInsert = 0;      /* INSERT statement */
  sqlite3_stmt *pSelect = 0;      /* SELECT statement */

  rc = sqlite3_exec(db, "SAVEPOINT changeset_apply", 0, 0, 0);
  sqlite3changeset_start(&pIter, nChangeset, pChangeset);
  while( SQLITE_ROW==sqlite3changeset_next(pIter) ){
    int op;
    const char *zThis;
    sqlite3changeset_op(pIter, &zThis, &nCol, &op);
    if( zTab==0 || sqlite3_strnicmp(zThis, zTab, nTab+1) ){
      sqlite3_free(azCol);
      rc = sessionTableInfo(db, zThis, nCol, &zTab, &azCol, &abPK);
      nTab = strlen(zTab);

      sqlite3_finalize(pDelete);
      sqlite3_finalize(pUpdate);
      sqlite3_finalize(pInsert);
      sqlite3_finalize(pSelect);
      pSelect = pUpdate = pInsert = pDelete = 0;
    }

    if( op==SQLITE_DELETE ){
      int res;
      int i;
      rc = sessionDeleteRow(db, zTab, nCol, azCol, abPK, &pDelete);
      for(i=0; rc==SQLITE_OK && i<nCol; i++){
        sqlite3_value *pVal;
        rc = sqlite3changeset_old(pIter, i, &pVal);
        if( rc==SQLITE_OK ){
          rc = sqlite3_bind_value(pDelete, i+1, pVal);
        }
      }
      if( rc==SQLITE_OK ) rc = sqlite3_bind_int(pDelete, nCol+1, 0);
      if( rc!=SQLITE_OK ) break;

      sqlite3_step(pDelete);
      rc = sqlite3_reset(pDelete);
      if( rc==SQLITE_OK && sqlite3_changes(db)==0 ){

        /* A NOTFOUND or DATA error. Search the table to see if it contains
        ** a row with a matching primary key. If so, this is a DATA conflict.
        ** Otherwise, if there is no primary key match, it is a NOTFOUND. */
        rc = sessionSelectRow(db, zTab, nCol, azCol, abPK, &pSelect);
        for(i=0; rc==SQLITE_OK && i<nCol; i++){
          if( abPK[i] ){
            sqlite3_value *pVal;
            rc = sqlite3changeset_old(pIter, i, &pVal);
            if( rc==SQLITE_OK ) sqlite3_bind_value(pSelect, i+1, pVal);
          }
        }
        if( rc!=SQLITE_OK ) break;
        if( SQLITE_ROW==sqlite3_step(pSelect) ){
          pIter->pConflict = pSelect;
          res = xConflict(pCtx, SQLITE_CHANGESET_DATA, pIter);
          pIter->pConflict = 0;
          sqlite3_reset(pSelect);
        }else{
          rc = sqlite3_reset(pSelect);
          if( rc==SQLITE_OK ){
            res = xConflict(pCtx, SQLITE_CHANGESET_NOTFOUND, pIter);
          }
        }

      }else if( rc==SQLITE_CONSTRAINT ){
        res = xConflict(pCtx, SQLITE_CHANGESET_CONSTRAINT, pIter);
        rc = SQLITE_OK;
      }

      if( rc!=SQLITE_OK ) break;

    }else if( op==SQLITE_UPDATE ){
      int i;
      int res;
      rc = sessionUpdateRow(db, zTab, nCol, azCol, abPK, &pUpdate);
      for(i=0; rc==SQLITE_OK && i<nCol; i++){
        sqlite3_value *pOld = 0;
        sqlite3_value *pNew = 0;
        rc = sqlite3changeset_old(pIter, i, &pOld);
        if( rc==SQLITE_OK ){
          rc = sqlite3changeset_new(pIter, i, &pNew);
        }
        if( rc==SQLITE_OK ){
          if( pOld ) sqlite3_bind_value(pUpdate, i*3+1, pOld);
          sqlite3_bind_int(pUpdate, i*3+2, !!pNew);
          if( pNew ) sqlite3_bind_value(pUpdate, i*3+3, pOld);
        }
      }
      if( rc==SQLITE_OK ) rc = sqlite3_bind_int(pUpdate, nCol*3+1, 0);
      if( rc!=SQLITE_OK ) break;

      sqlite3_step(pUpdate);
      rc = sqlite3_reset(pUpdate);
      if( rc==SQLITE_OK && sqlite3_changes(db)==0 ){
        /* A NOTFOUND or DATA error. Search the table to see if it contains
        ** a row with a matching primary key. If so, this is a DATA conflict.
        ** Otherwise, if there is no primary key match, it is a NOTFOUND. */
        rc = sessionSelectRow(db, zTab, nCol, azCol, abPK, &pSelect);
        for(i=0; rc==SQLITE_OK && i<nCol; i++){
          if( abPK[i] ){
            sqlite3_value *pVal;
            rc = sqlite3changeset_old(pIter, i, &pVal);
            if( rc==SQLITE_OK ) sqlite3_bind_value(pSelect, i+1, pVal);
          }
        }
        if( rc!=SQLITE_OK ) break;
        if( SQLITE_ROW==sqlite3_step(pSelect) ){
          pIter->pConflict = pSelect;
          res = xConflict(pCtx, SQLITE_CHANGESET_DATA, pIter);
          pIter->pConflict = 0;
          sqlite3_reset(pSelect);
        }else{
          rc = sqlite3_reset(pSelect);
          if( rc==SQLITE_OK ){
            res = xConflict(pCtx, SQLITE_CHANGESET_NOTFOUND, pIter);
          }
        }
      }else if( rc==SQLITE_CONSTRAINT ){
        assert(0);
      }

    }else{
      int i;
      assert( op==SQLITE_INSERT );
      if( pInsert==0 ){
        SessionBuffer buf = {0, 0, 0};
        sessionAppendStr(&buf, "INSERT INTO main.", &rc);
        sessionAppendIdent(&buf, zTab, &rc);
        sessionAppendStr(&buf, " VALUES(?", &rc);
        for(i=1; i<nCol; i++) sessionAppendStr(&buf, ", ?", &rc);
        sessionAppendStr(&buf, ")", &rc);

        if( rc==SQLITE_OK ){
          rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &pInsert, 0);
        }
        sqlite3_free(buf.aBuf);
      }

      for(i=0; rc==SQLITE_OK && i<nCol; i++){
        sqlite3_value *pVal;
        rc = sqlite3changeset_new(pIter, i, &pVal);
        if( rc==SQLITE_OK ){
          rc = sqlite3_bind_value(pInsert, i+1, pVal);
        }
      }
      if( rc!=SQLITE_OK ) break;

      sqlite3_step(pInsert);
      rc = sqlite3_reset(pInsert);
      if( rc==SQLITE_CONSTRAINT && xConflict ){
        int res;

        /* Figure out if this is a primary key or other constraint. */
        rc = sessionSelectRow(db, zTab, nCol, azCol, abPK, &pSelect);
        for(i=0; rc==SQLITE_OK && i<nCol; i++){
          if( abPK[i] ){
            sqlite3_value *pVal;
            rc = sqlite3changeset_new(pIter, i, &pVal);
            if( rc==SQLITE_OK ) sqlite3_bind_value(pSelect, i+1, pVal);
          }
        }
        if( rc!=SQLITE_OK ) break;
        if( SQLITE_ROW==sqlite3_step(pSelect) ){
          pIter->pConflict = pSelect;
          res = xConflict(pCtx, SQLITE_CHANGESET_CONFLICT, pIter);
          pIter->pConflict = 0;
          sqlite3_reset(pSelect);
        }else{
          rc = sqlite3_reset(pSelect);
          if( rc==SQLITE_OK ){
            res = xConflict(pCtx, SQLITE_CHANGESET_CONSTRAINT, pIter);
          }
        }
      }
    }
  }
  rc2 = sqlite3changeset_finalize(pIter);
  if( rc==SQLITE_DONE ) rc = rc2;

  if( rc==SQLITE_OK ){
    rc = sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
  }else{
    sqlite3_exec(db, "ROLLBACK TO changeset_apply", 0, 0, 0);
    sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
  }

  sqlite3_finalize(pInsert);
  sqlite3_finalize(pDelete);
  sqlite3_finalize(pUpdate);
  sqlite3_finalize(pSelect);
  sqlite3_free(azCol);
  return rc;
}

#endif        /* #ifdef SQLITE_ENABLE_SESSION */

Changes to ext/session/sqlite3session.h.

108
109
110
111
112
113
114















115
116
117
118
119
120
121
...
125
126
127
128
129
130
131



















132











133
134
);

int sqlite3changeset_new(
  sqlite3_changeset_iter *pIter,
  int iVal,
  sqlite3_value **ppValue             /* OUT: New value (or NULL pointer) */
);
















/*
** Finalize an iterator allocated with sqlite3changeset_start().
**
** This function may not be called on iterators passed to a conflict handler
** callback by changeset_apply().
*/
................................................................................
** Invert a changeset object.
*/
int sqlite3changeset_invert(
  int nIn, void *pIn,             /* Input changeset */
  int *pnOut, void **ppOut        /* OUT: Inverse of input */
);
































#endif








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







 







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

>
>
>
>
>
>
>
>
>
>
>


108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
...
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
);

int sqlite3changeset_new(
  sqlite3_changeset_iter *pIter,
  int iVal,
  sqlite3_value **ppValue             /* OUT: New value (or NULL pointer) */
);
/*
** This function is only usable with sqlite3_changeset_iter objects passed
** to the xConflict callback by sqlite3changeset_apply(). It cannot be used
** with iterators created using sqlite3changeset_start().
**
** It is used to access the "conflicting row" information available to the
** conflict handler if the second argument is either SQLITE_CHANGESET_DATA
** or SQLITE_CHANGESET_CONFLICT.
*/
int sqlite3changeset_conflict(
  sqlite3_changeset_iter *pIter,
  int iVal,
  sqlite3_value **ppValue         /* OUT: Value from conflicting row */
);


/*
** Finalize an iterator allocated with sqlite3changeset_start().
**
** This function may not be called on iterators passed to a conflict handler
** callback by changeset_apply().
*/
................................................................................
** Invert a changeset object.
*/
int sqlite3changeset_invert(
  int nIn, void *pIn,             /* Input changeset */
  int *pnOut, void **ppOut        /* OUT: Inverse of input */
);

/*
** Apply a changeset to a database.
**
** It is safe to execute SQL statements, including those that write to the
** table that the callback related to, from within the xConflict callback.
** This can be used to further customize the applications conflict
** resolution strategy.
*/
int sqlite3changeset_apply(
  sqlite3 *db,
  int nChangeset,
  void *pChangeset,
  int(*xConflict)(
    void *pCtx,                   /* Copy of fifth arg to _apply() */
    int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
    sqlite3_changeset_iter *p     /* Handle describing change and conflict */
  ),
  void *pCtx
);

/* Values passed as the second argument to a conflict-handler */
#define SQLITE_CHANGESET_DATA       1
#define SQLITE_CHANGESET_NOTFOUND   2
#define SQLITE_CHANGESET_CONFLICT   3
#define SQLITE_CHANGESET_CONSTRAINT 4

/* Valid return values from a conflict-handler */
#define SQLITE_CHANGESET_OMIT       0
#define SQLITE_CHANGESET_REPLACE    1
#define SQLITE_CHANGESET_ABORT      2

#endif

Changes to ext/session/test_session.c.

163
164
165
166
167
168
169





































































































































170
171
172
173
174
175
176
...
181
182
183
184
185
186
187

188
189
190
191
192
193
194
...
279
280
281
282
283
284
285



286
287
288
289
290
            sqlite3_value_bytes(pVal)
        );
        break;
    }
    Tcl_ListObjAppendElement(0, pList, pObj);
  }
}






































































































































/*
** sqlite3changeset_invert CHANGESET
*/
static int test_sqlite3changeset_invert(
  void * clientData,
  Tcl_Interp *interp,
................................................................................
  void *aChangeset;               /* Input changeset */
  int nChangeSet;                 /* Size of buffer aChangeset in bytes */
  void *aOut;                     /* Output changeset */
  int nOut;                       /* Size of buffer aOut in bytes */

  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "CHANGESET");

  }
  aChangeset = (void *)Tcl_GetByteArrayFromObj(objv[1], &nChangeSet);

  rc = sqlite3changeset_invert(nChangeSet, aChangeset, &nOut, &aOut);
  if( rc!=SQLITE_OK ){
    return test_session_error(interp, rc);
  }
................................................................................
  Tcl_CreateObjCommand(interp, "sqlite3session", test_sqlite3session, 0, 0);
  Tcl_CreateObjCommand(
      interp, "sqlite3session_foreach", test_sqlite3session_foreach, 0, 0
  );
  Tcl_CreateObjCommand(
      interp, "sqlite3changeset_invert", test_sqlite3changeset_invert, 0, 0
  );



  return TCL_OK;
}

#endif








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







 







>







 







>
>
>





163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
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
302
303
304
305
306
307
308
309
...
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
...
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
            sqlite3_value_bytes(pVal)
        );
        break;
    }
    Tcl_ListObjAppendElement(0, pList, pObj);
  }
}

typedef struct TestConflictHandler TestConflictHandler;
struct TestConflictHandler {
  Tcl_Interp *interp;
  Tcl_Obj *pScript;
};

static int test_conflict_handler(
  void *pCtx,                     /* Pointer to TestConflictHandler structure */
  int eConf,                      /* DATA, MISSING, CONFLICT, CONSTRAINT */
  sqlite3_changeset_iter *pIter   /* Handle describing change and conflict */
){
  TestConflictHandler *p = (TestConflictHandler *)pCtx;
  Tcl_Obj *pEval;
  Tcl_Interp *interp = p->interp;

  int op;                         /* SQLITE_UPDATE, DELETE or INSERT */
  const char *zTab;               /* Name of table conflict is on */
  int nCol;                       /* Number of columns in table zTab */

  pEval = Tcl_DuplicateObj(p->pScript);
  Tcl_IncrRefCount(pEval);

  sqlite3changeset_op(pIter, &zTab, &nCol, &op);

  /* Append the operation type. */
  Tcl_ListObjAppendElement(0, pEval, Tcl_NewStringObj(
      op==SQLITE_INSERT ? "INSERT" :
      op==SQLITE_UPDATE ? "UPDATE" : 
      "DELETE", -1
  ));

  /* Append the table name. */
  Tcl_ListObjAppendElement(0, pEval, Tcl_NewStringObj(zTab, -1));

  /* Append the conflict type. */
  switch( eConf ){
    case SQLITE_CHANGESET_DATA:
      Tcl_ListObjAppendElement(interp, pEval,Tcl_NewStringObj("DATA",-1));
      break;
    case SQLITE_CHANGESET_NOTFOUND:
      Tcl_ListObjAppendElement(interp, pEval,Tcl_NewStringObj("NOTFOUND",-1));
      break;
    case SQLITE_CHANGESET_CONFLICT:
      Tcl_ListObjAppendElement(interp, pEval,Tcl_NewStringObj("CONFLICT",-1));
      break;
    case SQLITE_CHANGESET_CONSTRAINT:
      Tcl_ListObjAppendElement(interp, pEval,Tcl_NewStringObj("CONSTRAINT",-1));
      break;
  }

  /* If this is not an INSERT, append the old row */
  if( op!=SQLITE_INSERT ){
    int i;
    Tcl_Obj *pOld = Tcl_NewObj();
    for(i=0; i<nCol; i++){
      sqlite3_value *pVal;
      sqlite3changeset_old(pIter, i, &pVal);
      test_append_value(pOld, pVal);
    }
    Tcl_ListObjAppendElement(0, pEval, pOld);
  }

  /* If this is not a DELETE, append the new row */
  if( op!=SQLITE_DELETE ){
    int i;
    Tcl_Obj *pNew = Tcl_NewObj();
    for(i=0; i<nCol; i++){
      sqlite3_value *pVal;
      sqlite3changeset_new(pIter, i, &pVal);
      test_append_value(pNew, pVal);
    }
    Tcl_ListObjAppendElement(0, pEval, pNew);
  }

  /* If this is a CHANGESET_DATA or CHANGESET_CONFLICT conflict, append
  ** the conflicting row. */
  if( eConf==SQLITE_CHANGESET_DATA || eConf==SQLITE_CHANGESET_CONFLICT ){
    int i;
    Tcl_Obj *pConflict = Tcl_NewObj();
    for(i=0; i<nCol; i++){
      sqlite3_value *pVal;
      sqlite3changeset_conflict(pIter, i, &pVal);
      test_append_value(pConflict, pVal);
    }
    Tcl_ListObjAppendElement(0, pEval, pConflict);
  }

  if( TCL_OK!=Tcl_EvalObjEx(interp, pEval, TCL_EVAL_GLOBAL) ){
    Tcl_BackgroundError(interp);
  }
  Tcl_DecrRefCount(pEval);
  return SQLITE_CHANGESET_OMIT;
}

/*
** sqlite3changeset_apply DB CHANGESET SCRIPT
*/
static int test_sqlite3changeset_apply(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  sqlite3 *db;                    /* Database handle */
  Tcl_CmdInfo info;               /* Database Tcl command (objv[1]) info */
  int rc;                         /* Return code from changeset_invert() */
  void *pChangeset;               /* Buffer containing changeset */
  int nChangeset;                 /* Size of buffer aChangeset in bytes */
  TestConflictHandler ctx;

  if( objc!=4 ){
    Tcl_WrongNumArgs(interp, 1, objv, "DB CHANGESET SCRIPT");
    return TCL_ERROR;
  }
  if( 0==Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &info) ){
    Tcl_AppendResult(interp, "no such handle: ", Tcl_GetString(objv[2]), 0);
    return TCL_ERROR;
  }
  db = *(sqlite3 **)info.objClientData;
  pChangeset = (void *)Tcl_GetByteArrayFromObj(objv[2], &nChangeset);
  ctx.pScript = objv[3];
  ctx.interp = interp;

  rc = sqlite3changeset_apply(
      db, nChangeset, pChangeset, test_conflict_handler, (void *)&ctx
  );
  if( rc!=SQLITE_OK ){
    return test_session_error(interp, rc);
  }
  Tcl_ResetResult(interp);
  return TCL_OK;
}

/*
** sqlite3changeset_invert CHANGESET
*/
static int test_sqlite3changeset_invert(
  void * clientData,
  Tcl_Interp *interp,
................................................................................
  void *aChangeset;               /* Input changeset */
  int nChangeSet;                 /* Size of buffer aChangeset in bytes */
  void *aOut;                     /* Output changeset */
  int nOut;                       /* Size of buffer aOut in bytes */

  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "CHANGESET");
    return TCL_ERROR;
  }
  aChangeset = (void *)Tcl_GetByteArrayFromObj(objv[1], &nChangeSet);

  rc = sqlite3changeset_invert(nChangeSet, aChangeset, &nOut, &aOut);
  if( rc!=SQLITE_OK ){
    return test_session_error(interp, rc);
  }
................................................................................
  Tcl_CreateObjCommand(interp, "sqlite3session", test_sqlite3session, 0, 0);
  Tcl_CreateObjCommand(
      interp, "sqlite3session_foreach", test_sqlite3session_foreach, 0, 0
  );
  Tcl_CreateObjCommand(
      interp, "sqlite3changeset_invert", test_sqlite3changeset_invert, 0, 0
  );
  Tcl_CreateObjCommand(
      interp, "sqlite3changeset_apply", test_sqlite3changeset_apply, 0, 0
  );
  return TCL_OK;
}

#endif

Changes to test/session1.test.

143
144
145
146
147
148
149



































































































































150

  execsql { INSERT INTO t1 VALUES(100, 'Bangkok') }
  execsql { DELETE FROM t1 WHERE x = 100 }
} {}
do_changeset_test 2.4.2 S {}
do_changeset_invert_test 2.4.3 S {}
do_test 2.4.4 { S delete } {}




































































































































finish_test








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

>
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
  execsql { INSERT INTO t1 VALUES(100, 'Bangkok') }
  execsql { DELETE FROM t1 WHERE x = 100 }
} {}
do_changeset_test 2.4.2 S {}
do_changeset_invert_test 2.4.3 S {}
do_test 2.4.4 { S delete } {}

#-------------------------------------------------------------------------
# Test the application of simple changesets.
#
db close
forcedelete test.db test.db2
sqlite3 db test.db
sqlite3 db2 test.db2

proc xConflict {args} { 
  lappend ::xConflict $args
  return "" 
}

proc do_conflict_test {tn args} {
  set O(-tables)    [list]
  set O(-sql)       [list]
  set O(-conflicts) [list]

  array set V $args
  foreach key [array names V] {
    if {![info exists O($key)]} {error "no such option: $key"}
  }
  array set O $args

  sqlite3session S db main
  foreach t $O(-tables) { S attach $t }
  execsql $O(-sql)

  set ::xConflict [list]
  sqlite3changeset_apply db2 [S changeset] xConflict

  set conflicts [list]
  foreach c $O(-conflicts) {
    lappend conflicts $c
  }

  uplevel do_test $tn [list { set ::xConflict }] [list $conflicts]
  S delete
}

proc do_db2_test {testname sql {result {}}} {
  uplevel do_test $testname [list "execsql {$sql} db2"] [list [list {*}$result]]
}

# Test INSERT changesets.
#
do_test 3.1.0 {
  execsql { CREATE TABLE t1(a PRIMARY KEY, b NOT NULL) } db2
  execsql { 
    CREATE TABLE t1(a PRIMARY KEY, b);
    INSERT INTO t1 VALUES(1, 'one');
    INSERT INTO t1 VALUES(2, 'two');
  } db 
} {}
do_db2_test 3.1.1 "INSERT INTO t1 VALUES(6, 'VI')"
do_conflict_test 3.2.2 -tables t1 -sql {
  INSERT INTO t1 VALUES(3, 'three');
  INSERT INTO t1 VALUES(4, 'four');
  INSERT INTO t1 VALUES(5, 'five');
  INSERT INTO t1 VALUES(6, 'six');
  INSERT INTO t1 VALUES(7, 'seven');
  INSERT INTO t1 VALUES(8, NULL);
} -conflicts {
  {INSERT t1 CONFLICT {i 6 t six} {i 6 t VI}}
  {INSERT t1 CONSTRAINT {i 8 n {}}}
}
do_db2_test 3.1.2 "SELECT * FROM t1" {
  6 VI 3 three 4 four 5 five 7 seven
}
do_execsql_test 3.1.3 "SELECT * FROM t1" {
  1 one 2 two 3 three 4 four 5 five 6 six 7 seven 8 {}
}

# Test DELETE changesets.
#
do_execsql_test 3.2.1 {
  PRAGMA foreign_keys = on;
  CREATE TABLE t2(a PRIMARY KEY, b);
  CREATE TABLE t3(c, d REFERENCES t2);
  INSERT INTO t2 VALUES(1, 'one');
  INSERT INTO t2 VALUES(2, 'two');
  INSERT INTO t2 VALUES(3, 'three');
  INSERT INTO t2 VALUES(4, 'four');
}
do_db2_test 3.2.2 {
  PRAGMA foreign_keys = on;
  CREATE TABLE t2(a PRIMARY KEY, b);
  CREATE TABLE t3(c, d REFERENCES t2);
  INSERT INTO t2 VALUES(1, 'one');
  INSERT INTO t2 VALUES(2, 'two');
  INSERT INTO t2 VALUES(4, 'five');
  INSERT INTO t3 VALUES('i', 1);
}
do_conflict_test 3.2.3 -tables t2 -sql {
  DELETE FROM t2 WHERE a = 1;
  DELETE FROM t2 WHERE a = 2;
  DELETE FROM t2 WHERE a = 3;
  DELETE FROM t2 WHERE a = 4;
} -conflicts {
  {DELETE t2 CONSTRAINT {i 1 t one}}
  {DELETE t2 NOTFOUND {i 3 t three}}
  {DELETE t2 DATA {i 4 t four} {i 4 t five}}
}
do_execsql_test 3.2.4 "SELECT * FROM t2" {}
do_db2_test     3.2.5 "SELECT * FROM t2" {1 one 4 five}

# Test UPDATE changesets.
#
do_execsql_test 3.3.1 {
  CREATE TABLE t4(a, b, c, PRIMARY KEY(b, c));
  INSERT INTO t4 VALUES(1, 2, 3);
  INSERT INTO t4 VALUES(4, 5, 6);
}
do_db2_test 3.3.2 {
  CREATE TABLE t4(a, b, c, PRIMARY KEY(b, c));
  INSERT INTO t4 VALUES(0, 2, 3);
  INSERT INTO t4 VALUES(4, 5, 7);
}

do_conflict_test 3.2.3 -tables t4 -sql {
  UPDATE t4 SET a = -1 WHERE b = 2;
} -conflicts {
  {UPDATE t4 DATA {i 1 i 2 i 3} {i -1 i 2 i 3} {i 0 i 2 i 3}}
}

do_db2_test 3.3.4 {
  SELECT * FROM t4
} {0 2 3 4 5 7}


catch { db2 close }
finish_test