/ Check-in [6614cfcb]
Login

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

Overview
Comment:Change to the session module to use user-defined primary keys instead of rowids when collecting changes.
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | sessions
Files: files | file ages | folders
SHA1:6614cfcb9c41da71ddec3c44a3de0d4d849e1cdd
User & Date: dan 2011-03-17 19:20:27
Context
2011-03-18
12:35
Merge all the latest trunk enhancements into the sessions branch. check-in: 94fd5bb6 user: drh tags: sessions
2011-03-17
19:20
Change to the session module to use user-defined primary keys instead of rowids when collecting changes. check-in: 6614cfcb user: dan tags: sessions
2011-03-16
19:59
Add the sqlite3_preupdate_new() API, for retrieving the new.* values from within a pre-update callback. check-in: 526545c4 user: dan tags: sessions
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Changes to ext/session/sqlite3session.c.

4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
..
53
54
55
56
57
58
59


60
61
62
63
64
65
66
...
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
...
260
261
262
263
264
265
266











267
268
269


270























































271




































272










































































273
274
275
276
277
278
279
...
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319




























































































































320
321
322
323
324
325
326
...
332
333
334
335
336
337
338

339



340
341













342
343


































































344









345
346
347
348
349
350
351
...
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405

406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
...
520
521
522
523
524
525
526

527
528
529
530
531
532
533
...
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


885
886
887
888
889


890
891
892
893
894
895
896
897
898
899
900
901


902
903










904
905
906
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
...
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
....
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
#include "sqlite3session.h"
#include <assert.h>
#include <string.h>

#include "sqliteInt.h"
#include "vdbeInt.h"

typedef struct RowChange RowChange;
typedef struct SessionTable SessionTable;
typedef struct SessionChange SessionChange;
typedef struct SessionBuffer SessionBuffer;

/*
** Session handle structure.
*/
................................................................................
** a subset of the initial values that the modified row contained at the
** start of the session. Or no initial values if the row was inserted.
*/
struct SessionTable {
  SessionTable *pNext;
  char *zName;                    /* Local name of table */
  int nCol;                       /* Number of columns in table zName */


  int nEntry;                     /* Total number of entries in hash table */
  int nChange;                    /* Size of apChange[] array */
  SessionChange **apChange;       /* Hash table buckets */
};

/* 
** RECORD FORMAT:
................................................................................
*/

/*
** For each row modified during a session, there exists a single instance of
** this structure stored in a SessionTable.aChange[] hash table.
*/
struct SessionChange {
  sqlite3_int64 iKey;             /* Key value */
  int nRecord;                    /* Number of bytes in buffer aRecord[] */
  u8 *aRecord;                    /* Buffer containing old.* record */
  SessionChange *pNext;           /* For hash-table collisions */
};

/*
** Instances of this structure are used to build strings or binary records.
................................................................................
    }
  }

  *pnWrite += nByte;
  return SQLITE_OK;
}












/*
** Return the hash of iKey, assuming there are nBucket hash buckets in
** the hash table.


*/























































static int sessionKeyhash(int nBucket, sqlite3_int64 iKey){




































  return (iKey % nBucket);










































































}

/*
** If required, grow the hash table used to store changes on table pTab 
** (part of the session pSession). If a fatal OOM error occurs, set the
** session object to failed and return SQLITE_ERROR. Otherwise, return
** SQLITE_OK.
................................................................................
    }
    memset(apNew, 0, sizeof(SessionChange *) * nNew);

    for(i=0; i<pTab->nChange; i++){
      SessionChange *p;
      SessionChange *pNext;
      for(p=pTab->apChange[i]; p; p=pNext){
        int iHash = sessionKeyhash(nNew, p->iKey);
        pNext = p->pNext;
        p->pNext = apNew[iHash];
        apNew[iHash] = p;
      }
    }

    sqlite3_free(pTab->apChange);
    pTab->nChange = nNew;
    pTab->apChange = apNew;
  }

  return SQLITE_OK;
}





























































































































/*
** This function is only called from within a pre-update handler for a
** write to table pTab, part of session pSession. If this is the first
** write to this table, set the SessionTable.nCol variable to the number
** of columns in the table.
**
................................................................................
** was recorded, set the session error-code to SQLITE_SCHEMA and return
** non-zero. Users are not allowed to change the number of columns in a table
** for which changes are being recorded by the session module. If they do so, 
** it is an error.
*/
static int sessionInitTable(sqlite3_session *pSession, SessionTable *pTab){
  if( pTab->nCol==0 ){

    pTab->nCol = sqlite3_preupdate_count(pSession->db);



  }else if( pTab->nCol!=sqlite3_preupdate_count(pSession->db) ){
    pSession->rc = SQLITE_SCHEMA;













    return SQLITE_ERROR;
  }


































































  return SQLITE_OK;









}

/*
** The 'pre-update' hook registered by this module with SQLite databases.
*/
static void xPreUpdate(
  void *pCtx,                     /* Copy of third arg to preupdate_hook() */
................................................................................
  sqlite3_session *pSession;
  int nDb = strlen(zDb);
  int nName = strlen(zDb);
 
  for(pSession=(sqlite3_session *)pCtx; pSession; pSession=pSession->pNext){
    SessionTable *pTab;

    /* If this session is already in the error-state, or if it is attached
    ** to a different database ("main", "temp" etc.), or if it is not 
    ** currently enabled, there is nothing to do. Skip to the next session
    ** object attached to this database. */
    if( pSession->bEnable==0 ) continue;
    if( pSession->rc ) continue;
    if( sqlite3_strnicmp(zDb, pSession->zDb, nDb+1) ) continue;

    for(pTab=pSession->pTable; pTab; pTab=pTab->pNext){
      if( 0==sqlite3_strnicmp(pTab->zName, zName, nName+1) ){
        SessionChange *pChange;
        SessionChange *pC;
        int iHash; 
        int rc = SQLITE_OK;

        /* Load table details if required */
        if( sessionInitTable(pSession, pTab) ) return;

        /* Grow the hash table if required */
        if( sessionGrowHash(pSession, pTab) ) return;

        /* Search the hash table for an existing entry for rowid=iKey2. If
        ** one is found, store a pointer to it in pChange and unlink it from
        ** the hash table. Otherwise, set pChange to NULL.
        */
        iHash = sessionKeyhash(pTab->nChange, iKey2);
        for(pC=pTab->apChange[iHash]; pC; pC=pC->pNext){
          if( pC->iKey==iKey2 ) break;
        }
        if( pC ) continue;

        pTab->nEntry++;

        /* Create a new change object containing all the old values (if
        ** this is an SQLITE_UPDATE or SQLITE_DELETE), or no record at
        ** all (if this is an INSERT). */
        if( op==SQLITE_INSERT ){
          pChange = (SessionChange *)sqlite3_malloc(sizeof(SessionChange));
          if( pChange ){
            memset(pChange, 0, sizeof(SessionChange));

          }
        }else{
          int nByte;              /* Number of bytes to allocate */
          int i;                  /* Used to iterate through columns */

          /* Figure out how large an allocation is required */
          nByte = sizeof(SessionChange);
          for(i=0; i<pTab->nCol && rc==SQLITE_OK; i++){
            sqlite3_value *p;     /* old.* value */
            rc = sqlite3_preupdate_old(pSession->db, i, &p);
            if( rc==SQLITE_OK ){
              rc = sessionSerializeValue(0, p, &nByte);
            }
          }

          /* Allocate the change object */
          pChange = (SessionChange *)sqlite3_malloc(nByte);
          if( !pChange ){
            rc = SQLITE_NOMEM;
          }else{
            memset(pChange, 0, sizeof(SessionChange));
            pChange->aRecord = (u8 *)&pChange[1];
          }

          /* Populate the change object */
          nByte = 0;
          for(i=0; i<pTab->nCol && rc==SQLITE_OK; i++){
            sqlite3_value *p;     /* old.* value */
            rc = sqlite3_preupdate_old(pSession->db, i, &p);
            if( rc==SQLITE_OK ){
              rc = sessionSerializeValue(&pChange->aRecord[nByte], p, &nByte);
            }
          }
          pChange->nRecord = nByte;
        }

        /* If an error has occurred, mark the session object as failed. */
        if( rc!=SQLITE_OK ){
          sqlite3_free(pChange);
          pSession->rc = rc;
          return;
        }

        /* Add the change back to the hash-table */
        pChange->iKey = iKey2;
        pChange->pNext = pTab->apChange[iHash];
        pTab->apChange[iHash] = pChange;
        break;
      }
    }
  }
}

/*
................................................................................
      SessionChange *p;
      SessionChange *pNext;
      for(p=pTab->apChange[i]; p; p=pNext){
        pNext = p->pNext;
        sqlite3_free(p);
      }
    }

    sqlite3_free(pTab->apChange);
    sqlite3_free(pTab);
  }

  /* Free the session object itself. */
  sqlite3_free(pSession);
}
................................................................................
    }else{
      sessionAppendBlob(pBuf, buf2.aBuf, buf2.nBuf, pRc);
      sqlite3_free(buf2.aBuf);
    }
  }
}

/*
** This function queries the database for the names of the columns of table
** zThis, in schema zDb. It is expected that the table has nCol columns. If
** not, SQLITE_SCHEMA is returned and none of the output variables are
** populated.
**
** Otherwise, if it is not NULL, variable *pzTab is set to point to a
** nul-terminated copy of the table name. *pazCol (if not NULL) is set to
** point to an array of pointers to column names. And *pabPK (again, if not
** NULL) is set to point to an array of booleans - true if the corresponding
** column is part of the primary key.
**
** For example, if the table is declared as:
**
**     CREATE TABLE tbl1(w, x, y, z, PRIMARY KEY(w, z));
**
** Then the three output variables are populated as follows:
**
**     *pzTab  = "tbl1"
**     *pazCol = {"w", "x", "y", "z"}
**     *pabPK  = {1, 0, 0, 1}
**
** All returned buffers are part of the same single allocation, which must
** be freed using sqlite3_free() by the caller. If pazCol was not NULL, then
** pointer *pazCol should be freed to release all memory. Otherwise, pointer
** *pabPK. It is illegal for both pazCol and pabPK to be NULL.
*/
static int sessionTableInfo(
  sqlite3 *db,                    /* Database connection */
  const char *zDb,                /* Name of attached database (e.g. "main") */


  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;



  assert( pazCol || pabPK );











  nThis = strlen(zThis);
  zPragma = sqlite3_mprintf("PRAGMA '%q'.table_info('%q')", zDb, 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 successful, populate the output variables. Otherwise, zero them and
  ** free any allocation made. An error code will be returned in this case.
  */
  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.
**
................................................................................
  ** this call will be a no-op.  */
  *pnChangeset = 0;
  *ppChangeset = 0;
  rc = pSession->rc;

  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: */
      if( rc==SQLITE_OK ){
        char *zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q WHERE _rowid_ = ?", 
            pSession->zDb, pTab->zName
        );
        if( !zSql ){
          rc = SQLITE_NOMEM;
        }else{
          rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
        }
        sqlite3_free(zSql);
      }

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

      if( rc==SQLITE_OK ){
        rc = sessionTableInfo(
            db, pSession->zDb, 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(&buf, pStmt, p, abPK, &rc);
            }else{
              sessionAppendByte(&buf, SQLITE_INSERT, &rc);
              for(iCol=0; iCol<pTab->nCol; iCol++){
                sessionAppendCol(&buf, pStmt, iCol, &rc);
              }


            }
            bNoop = 0;
          }else if( p->aRecord ){
            /* A DELETE change */
            sessionAppendByte(&buf, SQLITE_DELETE, &rc);
            sessionAppendBlob(&buf, p->aRecord, p->nRecord, &rc);
            bNoop = 0;
          }
          rc = sqlite3_reset(pStmt);

        }
      }

      sqlite3_finalize(pStmt);
      sqlite3_free(abPK);

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

................................................................................
** pointing to the prepared version of the SQL statement.
*/
static int sessionSelectRow(
  sqlite3 *db,                    /* Database handle */
  const char *zTab,               /* Table name */
  SessionApplyCtx *p              /* Session changeset-apply context */
){
  int rc = SQLITE_OK;
  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<p->nCol; i++){
    if( p->abPK[i] ){
      sessionAppendStr(&buf, zSep, &rc);
      sessionAppendIdent(&buf, p->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, &p->pSelect, 0);
  }
  sqlite3_free(buf.aBuf);
  return rc;
}

/*
** Formulate and prepare an INSERT statement to add a record to table zTab.
** For example:
**
**     INSERT INTO main."zTab" VALUES(?1, ?2, ?3 ...);







<







 







>
>







 







|







 







>
>
>
>
>
>
>
>
>
>
>

<
<
>
>

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







 







|













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







 







>

>
>
>


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







 







<
|
|
|






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







 







>







 







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

<
<
|
<
<
<

<
<
<
<
>
>

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

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

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

<
>







 







>
>




<



|




|
<
<
<
<
<
<
|
<
|
<
|



<
<
<
<
<

|
>

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




<







 







|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







4
5
6
7
8
9
10

11
12
13
14
15
16
17
..
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
...
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
...
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
...
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
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
623
624
625
626
627
...
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
...
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
...
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
....
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
1201
1202
1203
1204
1205




1206

1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
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
....
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
....
1910
1911
1912
1913
1914
1915
1916
1917





















1918
1919
1920
1921
1922
1923
1924
#include "sqlite3session.h"
#include <assert.h>
#include <string.h>

#include "sqliteInt.h"
#include "vdbeInt.h"


typedef struct SessionTable SessionTable;
typedef struct SessionChange SessionChange;
typedef struct SessionBuffer SessionBuffer;

/*
** Session handle structure.
*/
................................................................................
** a subset of the initial values that the modified row contained at the
** start of the session. Or no initial values if the row was inserted.
*/
struct SessionTable {
  SessionTable *pNext;
  char *zName;                    /* Local name of table */
  int nCol;                       /* Number of columns in table zName */
  const char **azCol;             /* Column names */
  u8 *abPK;                       /* Array of primary key flags */
  int nEntry;                     /* Total number of entries in hash table */
  int nChange;                    /* Size of apChange[] array */
  SessionChange **apChange;       /* Hash table buckets */
};

/* 
** RECORD FORMAT:
................................................................................
*/

/*
** For each row modified during a session, there exists a single instance of
** this structure stored in a SessionTable.aChange[] hash table.
*/
struct SessionChange {
  int bInsert;                    /* True if row was inserted this session */
  int nRecord;                    /* Number of bytes in buffer aRecord[] */
  u8 *aRecord;                    /* Buffer containing old.* record */
  SessionChange *pNext;           /* For hash-table collisions */
};

/*
** Instances of this structure are used to build strings or binary records.
................................................................................
    }
  }

  *pnWrite += nByte;
  return SQLITE_OK;
}

#define HASH_APPEND(hash, add) ((hash) << 3) ^ (hash) ^ (int)(add)
static int sessionHashAppendI64(int h, i64 i){
  h = HASH_APPEND(h, i & 0xFFFFFFFF);
  return HASH_APPEND(h, (i>>32)&0xFFFFFFFF);
}
static int sessionHashAppendBlob(int h, int n, const u8 *z){
  int i;
  for(i=0; i<n; i++) h = HASH_APPEND(h, z[i]);
  return h;
}

/*


** This function calculates a hash based on the primary key values of
** the old.* or new.* row currently available.
*/
static int sessionPreupdateHash(
  sqlite3 *db,                    /* Database handle */
  SessionTable *pTab,             /* Session table handle */
  int bNew,                       /* True to hash the new.* PK */
  int *piHash                     /* OUT: Hash value */
){
  int h = 0;
  int i;

  assert( pTab->nCol==sqlite3_preupdate_count(db) );
  for(i=0; i<pTab->nCol; i++){
    if( pTab->abPK[i] ){
      int rc;
      int eType;
      sqlite3_value *pVal;

      if( bNew ){
        rc = sqlite3_preupdate_new(db, i, &pVal);
      }else{
        rc = sqlite3_preupdate_old(db, i, &pVal);
      }

      eType = sqlite3_value_type(pVal);
      h = HASH_APPEND(h, eType);
      switch( eType ){
        case SQLITE_INTEGER: 
        case SQLITE_FLOAT: {
          i64 iVal;
          if( eType==SQLITE_INTEGER ){
            iVal = sqlite3_value_int64(pVal);
          }else{
            double rVal = sqlite3_value_double(pVal);
            assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
            memcpy(&iVal, &rVal, 8);
          }
          h = sessionHashAppendI64(h, iVal);
          break;
        }

        case SQLITE_TEXT: 
        case SQLITE_BLOB: {
          int n = sqlite3_value_bytes(pVal);
          const u8 *z = eType==SQLITE_TEXT ?
            sqlite3_value_text(pVal) : sqlite3_value_blob(pVal);
          h = sessionHashAppendBlob(h, n, z);
          break;
        }
      }
    }
  }

  *piHash = (h % pTab->nChange);
  return SQLITE_OK;
}

static int sessionChangeHash(
  sqlite3 *db,
  SessionTable *pTab,
  SessionChange *pChange,
  int nBucket
){
  int h = 0;
  int i;
  u8 *a = pChange->aRecord;

  for(i=0; i<pTab->nCol; i++){
    int eType = *a++;
    int isPK = pTab->abPK[i];

    if( isPK ) h = HASH_APPEND(h, eType);
    switch( eType ){
      case SQLITE_INTEGER:
      case SQLITE_FLOAT: {
        if( isPK ){
          i64 iVal = sessionGetI64(a);
          h = sessionHashAppendI64(h, iVal);
        }
        a += 8;
        break;
      }
      case SQLITE_TEXT:
      case SQLITE_BLOB: {
        int n;
        a += sessionVarintGet(a, &n);
        if( isPK ){
          h = sessionHashAppendBlob(h, n, a);
        }
        a += n;
        break;
      }
    }
  }
  return (h % nBucket);
}

static int sessionPreupdateEqual(
  sqlite3 *db,
  SessionTable *pTab,
  SessionChange *pChange,
  int bNew,
  int *pbEqual
){
  int i;
  u8 *a = pChange->aRecord;

  *pbEqual = 0;

  for(i=0; i<pTab->nCol; i++){
    int eType = *a++;
    if( !pTab->abPK[i] ){
      switch( eType ){
        case SQLITE_INTEGER: 
        case SQLITE_FLOAT:
          a += 8;
          break;

        case SQLITE_TEXT: 
        case SQLITE_BLOB: {
          int n;
          a += sessionVarintGet(a, &n);
          a += n;
          break;
        }
      }
    }else{
      sqlite3_value *pVal;
      int rc;
      if( bNew ){
        rc = sqlite3_preupdate_new(db, i, &pVal);
      }else{
        rc = sqlite3_preupdate_old(db, i, &pVal);
      }
      if( rc!=SQLITE_OK || sqlite3_value_type(pVal)!=eType ) return rc;

      switch( eType ){
        case SQLITE_INTEGER:
        case SQLITE_FLOAT: {
          i64 iVal = sessionGetI64(a);
          a += 8;
          if( eType==SQLITE_INTEGER ){
            if( sqlite3_value_int64(pVal)!=iVal ) return SQLITE_OK;
          }else{
            double rVal;
            assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
            memcpy(&rVal, &iVal, 8);
            if( sqlite3_value_double(pVal)!=rVal ) return SQLITE_OK;
          }
          break;
        }
        case SQLITE_TEXT:
        case SQLITE_BLOB: {
          int n;
          const u8 *z;
          a += sessionVarintGet(a, &n);
          if( sqlite3_value_bytes(pVal)!=n ) return SQLITE_OK;
          z = eType==SQLITE_TEXT ? 
            sqlite3_value_text(pVal) : sqlite3_value_blob(pVal);
          if( memcmp(a, z, n) ) return SQLITE_OK;
          a += n;
          break;
        }
      }
    }
  }

  *pbEqual = 1;
  return SQLITE_OK;
}

/*
** If required, grow the hash table used to store changes on table pTab 
** (part of the session pSession). If a fatal OOM error occurs, set the
** session object to failed and return SQLITE_ERROR. Otherwise, return
** SQLITE_OK.
................................................................................
    }
    memset(apNew, 0, sizeof(SessionChange *) * nNew);

    for(i=0; i<pTab->nChange; i++){
      SessionChange *p;
      SessionChange *pNext;
      for(p=pTab->apChange[i]; p; p=pNext){
        int iHash = sessionChangeHash(pSession->db, pTab, p, nNew);
        pNext = p->pNext;
        p->pNext = apNew[iHash];
        apNew[iHash] = p;
      }
    }

    sqlite3_free(pTab->apChange);
    pTab->nChange = nNew;
    pTab->apChange = apNew;
  }

  return SQLITE_OK;
}

/*
** This function queries the database for the names of the columns of table
** zThis, in schema zDb. It is expected that the table has nCol columns. If
** not, SQLITE_SCHEMA is returned and none of the output variables are
** populated.
**
** Otherwise, if it is not NULL, variable *pzTab is set to point to a
** nul-terminated copy of the table name. *pazCol (if not NULL) is set to
** point to an array of pointers to column names. And *pabPK (again, if not
** NULL) is set to point to an array of booleans - true if the corresponding
** column is part of the primary key.
**
** For example, if the table is declared as:
**
**     CREATE TABLE tbl1(w, x, y, z, PRIMARY KEY(w, z));
**
** Then the three output variables are populated as follows:
**
**     *pzTab  = "tbl1"
**     *pazCol = {"w", "x", "y", "z"}
**     *pabPK  = {1, 0, 0, 1}
**
** All returned buffers are part of the same single allocation, which must
** be freed using sqlite3_free() by the caller. If pazCol was not NULL, then
** pointer *pazCol should be freed to release all memory. Otherwise, pointer
** *pabPK. It is illegal for both pazCol and pabPK to be NULL.
*/
static int sessionTableInfo(
  sqlite3 *db,                    /* Database connection */
  const char *zDb,                /* Name of attached database (e.g. "main") */
  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;

  assert( pazCol || pabPK );

  nThis = strlen(zThis);
  zPragma = sqlite3_mprintf("PRAGMA '%q'.table_info('%q')", zDb, 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 successful, populate the output variables. Otherwise, zero them and
  ** free any allocation made. An error code will be returned in this case.
  */
  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;
}

/*
** This function is only called from within a pre-update handler for a
** write to table pTab, part of session pSession. If this is the first
** write to this table, set the SessionTable.nCol variable to the number
** of columns in the table.
**
................................................................................
** was recorded, set the session error-code to SQLITE_SCHEMA and return
** non-zero. Users are not allowed to change the number of columns in a table
** for which changes are being recorded by the session module. If they do so, 
** it is an error.
*/
static int sessionInitTable(sqlite3_session *pSession, SessionTable *pTab){
  if( pTab->nCol==0 ){
    assert( pTab->azCol==0 || pTab->abPK==0 );
    pTab->nCol = sqlite3_preupdate_count(pSession->db);
    pSession->rc = sessionTableInfo(pSession->db, pSession->zDb, 
        pTab->zName, pTab->nCol, 0, &pTab->azCol, &pTab->abPK
    );
  }else if( pTab->nCol!=sqlite3_preupdate_count(pSession->db) ){
    pSession->rc = SQLITE_SCHEMA;
  }
  return pSession->rc;
}

static void sessionPreupdateOneChange(
  int op,
  sqlite3_session *pSession,
  SessionTable *pTab
){
  sqlite3 *db = pSession->db;
  SessionChange *pChange;
  SessionChange *pC;
  int iHash; 
  int rc = SQLITE_OK;

  if( pSession->rc ) return;

  /* Load table details if required */
  if( sessionInitTable(pSession, pTab) ) return;

  /* Grow the hash table if required */
  if( sessionGrowHash(pSession, pTab) ) return;

  /* Search the hash table for an existing entry for rowid=iKey2. If
   ** one is found, store a pointer to it in pChange and unlink it from
   ** the hash table. Otherwise, set pChange to NULL.
   */
  rc = sessionPreupdateHash(db, pTab, op==SQLITE_INSERT, &iHash);
  for(pC=pTab->apChange[iHash]; rc==SQLITE_OK && pC; pC=pC->pNext){
    int bEqual;
    rc = sessionPreupdateEqual(db, pTab, pC, op==SQLITE_INSERT, &bEqual);
    if( bEqual ) break;
  }
  if( pC==0 ){
    /* Create a new change object containing all the old values (if
     ** this is an SQLITE_UPDATE or SQLITE_DELETE), or just the PK
     ** values (if this is an INSERT). */
    int nByte;              /* Number of bytes to allocate */
    int i;                  /* Used to iterate through columns */

    pTab->nEntry++;

    /* Figure out how large an allocation is required */
    nByte = sizeof(SessionChange);
    for(i=0; i<pTab->nCol && rc==SQLITE_OK; i++){
      sqlite3_value *p = 0;
      if( op!=SQLITE_INSERT ){
        rc = sqlite3_preupdate_old(pSession->db, i, &p);
      }else if( 1 || pTab->abPK[i] ){
        rc = sqlite3_preupdate_new(pSession->db, i, &p);
      }
      if( p && rc==SQLITE_OK ){
        rc = sessionSerializeValue(0, p, &nByte);
      }
    }

    /* Allocate the change object */
    pChange = (SessionChange *)sqlite3_malloc(nByte);
    if( !pChange ){
      rc = SQLITE_NOMEM;
    }else{
      memset(pChange, 0, sizeof(SessionChange));
      pChange->aRecord = (u8 *)&pChange[1];
    }

    /* Populate the change object */
    nByte = 0;
    for(i=0; i<pTab->nCol && rc==SQLITE_OK; i++){
      sqlite3_value *p = 0;
      if( op!=SQLITE_INSERT ){
        rc = sqlite3_preupdate_old(pSession->db, i, &p);
      }else if( 1 || pTab->abPK[i] ){
        rc = sqlite3_preupdate_new(pSession->db, i, &p);
      }
      if( p && rc==SQLITE_OK ){
        rc = sessionSerializeValue(&pChange->aRecord[nByte], p, &nByte);
      }
    }
    pChange->nRecord = nByte;

    /* If an error has occurred, mark the session object as failed. */
    if( rc!=SQLITE_OK ){
      sqlite3_free(pChange);
      pSession->rc = rc;
    }else{
      /* Add the change back to the hash-table */
      pChange->bInsert = (op==SQLITE_INSERT);
      pChange->pNext = pTab->apChange[iHash];
      pTab->apChange[iHash] = pChange;
    }
  }
}

/*
** The 'pre-update' hook registered by this module with SQLite databases.
*/
static void xPreUpdate(
  void *pCtx,                     /* Copy of third arg to preupdate_hook() */
................................................................................
  sqlite3_session *pSession;
  int nDb = strlen(zDb);
  int nName = strlen(zDb);
 
  for(pSession=(sqlite3_session *)pCtx; pSession; pSession=pSession->pNext){
    SessionTable *pTab;


    /* If this session is attached to a different database ("main", "temp" 
    ** etc.), or if it is not currently enabled, there is nothing to do. Skip 
    ** to the next session object attached to this database. */
    if( pSession->bEnable==0 ) continue;
    if( pSession->rc ) continue;
    if( sqlite3_strnicmp(zDb, pSession->zDb, nDb+1) ) continue;

    for(pTab=pSession->pTable; pTab; pTab=pTab->pNext){
      if( 0==sqlite3_strnicmp(pTab->zName, zName, nName+1) ){
        sessionPreupdateOneChange(op, pSession, pTab);

























        if( op==SQLITE_UPDATE ){



          sessionPreupdateOneChange(SQLITE_INSERT, pSession, pTab);
        }














































        break;
      }
    }
  }
}

/*
................................................................................
      SessionChange *p;
      SessionChange *pNext;
      for(p=pTab->apChange[i]; p; p=pNext){
        pNext = p->pNext;
        sqlite3_free(p);
      }
    }
    sqlite3_free(pTab->azCol);
    sqlite3_free(pTab->apChange);
    sqlite3_free(pTab);
  }

  /* Free the session object itself. */
  sqlite3_free(pSession);
}
................................................................................
    }else{
      sessionAppendBlob(pBuf, buf2.aBuf, buf2.nBuf, pRc);
      sqlite3_free(buf2.aBuf);
    }
  }
}




























static int sessionSelectStmt(
  sqlite3 *db,                    /* Database handle */

  const char *zTab,               /* Table name */
  int nCol,
  const char **azCol,




  u8 *abPK,
  sqlite3_stmt **ppStmt
){


  int rc = SQLITE_OK;



  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;
}






static int sessionSelectBind(
  sqlite3_stmt *pSelect,
  int nCol,
  u8 *abPK,
  u8 *aRecord,
  int nRecord
){
  int i;
  int rc = SQLITE_OK;
  u8 *a = aRecord;


  for(i=0; i<nCol && rc==SQLITE_OK; i++){
    int eType = *a++;

    switch( eType ){
      case SQLITE_NULL:
        if( abPK[i] ) rc = sqlite3_bind_null(pSelect, i+1);
        break;





      case SQLITE_INTEGER: {
        if( abPK[i] ){
          i64 iVal = sessionGetI64(a);
          rc = sqlite3_bind_int64(pSelect, i+1, iVal);
        }
        a += 8;
        break;
      }









      case SQLITE_FLOAT: {
        if( abPK[i] ){
          double rVal;
          i64 iVal = sessionGetI64(a);
          memcpy(&rVal, &iVal, 8);
          rc = sqlite3_bind_int64(pSelect, i+1, rVal);
        }




        a += 8;
        break;
      }





      case SQLITE_TEXT: {
        int n;
        a += sessionVarintGet(a, &n);
        if( abPK[i] ){
          rc = sqlite3_bind_text(pSelect, i+1, (char *)a, n, SQLITE_TRANSIENT);
        }
        a += n;
        break;




      }




      case SQLITE_BLOB: {
        int n;
        a += sessionVarintGet(a, &n);
        if( abPK[i] ){
          rc = sqlite3_bind_blob(pSelect, i+1, a, n, SQLITE_TRANSIENT);
        }
        a += n;
        break;
      }
    }











  }


  return rc;
}

/*
** Obtain a changeset object containing all changes recorded by the 
** session object passed as the first argument.
**
................................................................................
  ** this call will be a no-op.  */
  *pnChangeset = 0;
  *ppChangeset = 0;
  rc = pSession->rc;

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


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

      /* Build and compile a statement to execute: */
      if( rc==SQLITE_OK ){
        rc = sessionSelectStmt(db, pTab->zName, nCol, pTab->azCol, abPK,&pStmt);






      }



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






      for(i=0; i<pTab->nChange; i++){
        SessionChange *p;         /* Used to iterate through changes */

        for(p=pTab->apChange[i]; rc==SQLITE_OK && p; p=p->pNext){

          rc = sessionSelectBind(pStmt, nCol, abPK, p->aRecord, p->nRecord);
          if( rc==SQLITE_OK ){
            if( sqlite3_step(pStmt)==SQLITE_ROW ){
              int iCol;
              if( p->bInsert ){


                sessionAppendByte(&buf, SQLITE_INSERT, &rc);
                for(iCol=0; iCol<nCol; iCol++){
                  sessionAppendCol(&buf, pStmt, iCol, &rc);
                }
              }else{
                sessionAppendUpdate(&buf, pStmt, p, abPK, &rc);
              }
              bNoop = 0;
            }else if( !p->bInsert ){
              /* A DELETE change */
              sessionAppendByte(&buf, SQLITE_DELETE, &rc);
              sessionAppendBlob(&buf, p->aRecord, p->nRecord, &rc);
              bNoop = 0;
            }
            rc = sqlite3_reset(pStmt);
          }
        }
      }

      sqlite3_finalize(pStmt);


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

................................................................................
** pointing to the prepared version of the SQL statement.
*/
static int sessionSelectRow(
  sqlite3 *db,                    /* Database handle */
  const char *zTab,               /* Table name */
  SessionApplyCtx *p              /* Session changeset-apply context */
){
  return sessionSelectStmt(db, zTab, p->nCol, p->azCol, p->abPK, &p->pSelect);





















}

/*
** Formulate and prepare an INSERT statement to add a record to table zTab.
** For example:
**
**     INSERT INTO main."zTab" VALUES(?1, ?2, ?3 ...);

Changes to test/session1.test.

33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
...
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
137
138
139
140
141
142
143
...
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
...
278
279
280
281
282
283
284

285
286
287
288
289
290
291
292
293
294
...
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
...
329
330
331
332
333
334
335

336
337
338
339
340
341
342
343
344
    set changeset [sqlite3changeset_invert [$session changeset]]
    sqlite3session_foreach c [set changeset] { lappend x [set c] }
    set x
  }]] [list $r]
}

do_execsql_test 1.0 {
  CREATE TABLE t1(x, y);
  INSERT INTO t1 VALUES('abc', 'def');
}

#-------------------------------------------------------------------------
# Test creating, attaching tables to and deleting session objects.
#
do_test 1.1 { sqlite3session S db main } {S}
................................................................................
  {INSERT t1 {} {i 1 t Sukhothai}}
  {INSERT t1 {} {i 2 t Ayutthaya}}
  {INSERT t1 {} {i 3 t Thonburi}}
}
do_test 2.2.4 { S delete } {}

do_test 2.3.1 {

  sqlite3session S db main
  execsql { INSERT INTO t1 VALUES(1, 'Sukhothai') }
  execsql { INSERT INTO t1 VALUES(2, 'Ayutthaya') }
  execsql { INSERT INTO t1 VALUES(3, 'Thonburi') }
  S attach t1
  execsql { 
    UPDATE t1 SET x = 10 WHERE x = 1;
    UPDATE t1 SET y = 'Surin' WHERE x = 2;
    UPDATE t1 SET x = 20, y = 'Thapae' WHERE x = 3;
  }
} {}

do_changeset_test 2.3.2 S {
  {UPDATE t1 {i 1 {} {}} {i 10 {} {}}} 

  {UPDATE t1 {{} {} t Ayutthaya} {{} {} t Surin}} 
  {UPDATE t1 {i 3 t Thonburi} {i 20 t Thapae}}

}

do_changeset_invert_test 2.3.3 S {
  {UPDATE t1 {i 10 {} {}} {i 1 {} {}}} 


  {UPDATE t1 {{} {} t Surin} {{} {} t Ayutthaya}} 

  {UPDATE t1 {i 20 t Thapae} {i 3 t Thonburi}}
}
do_test 2.3.4 { S delete } {}

do_test 2.4.1 {
  sqlite3session S db main
  S attach t1
  execsql { INSERT INTO t1 VALUES(100, 'Bangkok') }
................................................................................
  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;
................................................................................
}
do_conflict_test 3.3.3 -tables t4 -sql {
  UPDATE t4 SET a = -1 WHERE b = 2;
  UPDATE t4 SET a = -1 WHERE b = 5;
  UPDATE t4 SET a = NULL WHERE c = 9;
  UPDATE t4 SET a = 'x' WHERE b = 11;
} -conflicts {

  {UPDATE t4 DATA {i 1 i 2 i 3} {i -1 {} {} {} {}} {i 0 i 2 i 3}}
  {UPDATE t4 NOTFOUND {i 4 i 5 i 6} {i -1 {} {} {} {}}}
  {UPDATE t4 CONSTRAINT {i 7 i 8 i 9} {n {} {} {} {} {}}}
}
do_db2_test     3.3.4 { SELECT * FROM t4 } {0 2 3 4 5 7 7 8 9 x 11 12}
do_execsql_test 3.3.5 { SELECT * FROM t4 } {-1 2 3 -1 5 6 {} 8 9 x 11 12}

#-------------------------------------------------------------------------
# This next block of tests verifies that values returned by the conflict
# handler are intepreted correctly.
................................................................................

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

foreach {tn conflict_return after} {
  1 OMIT      {1 2 value1   4 5 7       7 8 9   10 x x}
  2 REPLACE   {1 2 value1   4 5 value2          10 8 9}
} {
  test_reset

  do_test 4.$tn.1 {
    foreach db {db db2} {
      execsql { 
        CREATE TABLE t1(a, b, c, PRIMARY KEY(a));
................................................................................
  } {}

  do_conflict_test 4.$tn.2 -tables t1 -sql {
    UPDATE t1 SET c = 'value1' WHERE a = 1;       -- no conflict
    UPDATE t1 SET c = 'value2' WHERE a = 4;       -- DATA conflict
    UPDATE t1 SET a = 10 WHERE a = 7;             -- CONFLICT conflict
  } -conflicts {

    {UPDATE t1 DATA {i 4 {} {} i 6} {{} {} {} {} t value2} {i 4 i 5 i 7}}
    {UPDATE t1 CONFLICT {i 7 {} {} {} {}} {i 10 {} {} {} {}} {i 10 t x t x}}
  }

  do_db2_test 4.$tn.3 "SELECT * FROM t1 ORDER BY a" $after
}

foreach {tn conflict_return} {
  1 OMIT







|







 







>













|
>
|
|
>

>

<
>
>
|
>
|







 







|







<

>

>
|


|







 







>


<







 







|
|







 







>

<







33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
...
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
137

138
139
140
141
142
143
144
145
146
147
148
149
...
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
...
285
286
287
288
289
290
291
292
293
294

295
296
297
298
299
300
301
...
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
...
336
337
338
339
340
341
342
343
344

345
346
347
348
349
350
351
    set changeset [sqlite3changeset_invert [$session changeset]]
    sqlite3session_foreach c [set changeset] { lappend x [set c] }
    set x
  }]] [list $r]
}

do_execsql_test 1.0 {
  CREATE TABLE t1(x PRIMARY KEY, y);
  INSERT INTO t1 VALUES('abc', 'def');
}

#-------------------------------------------------------------------------
# Test creating, attaching tables to and deleting session objects.
#
do_test 1.1 { sqlite3session S db main } {S}
................................................................................
  {INSERT t1 {} {i 1 t Sukhothai}}
  {INSERT t1 {} {i 2 t Ayutthaya}}
  {INSERT t1 {} {i 3 t Thonburi}}
}
do_test 2.2.4 { S delete } {}

do_test 2.3.1 {
  execsql { DELETE FROM t1 }
  sqlite3session S db main
  execsql { INSERT INTO t1 VALUES(1, 'Sukhothai') }
  execsql { INSERT INTO t1 VALUES(2, 'Ayutthaya') }
  execsql { INSERT INTO t1 VALUES(3, 'Thonburi') }
  S attach t1
  execsql { 
    UPDATE t1 SET x = 10 WHERE x = 1;
    UPDATE t1 SET y = 'Surin' WHERE x = 2;
    UPDATE t1 SET x = 20, y = 'Thapae' WHERE x = 3;
  }
} {}

do_changeset_test 2.3.2 S {
  {INSERT t1 {} {i 10 t Sukhothai}} 
  {DELETE t1 {i 1 t Sukhothai} {}} 
  {UPDATE t1 {i 2 t Ayutthaya} {{} {} t Surin}} 
  {DELETE t1 {i 3 t Thonburi} {}} 
  {INSERT t1 {} {i 20 t Thapae}} 
}

do_changeset_invert_test 2.3.3 S {

  {DELETE t1 {i 10 t Sukhothai} {}} 
  {INSERT t1 {} {i 1 t Sukhothai}} 
  {UPDATE t1 {{} {} t Surin} {i 2 t Ayutthaya}} 
  {INSERT t1 {} {i 3 t Thonburi}} 
  {DELETE t1 {i 20 t Thapae} {}}
}
do_test 2.3.4 { S delete } {}

do_test 2.4.1 {
  sqlite3session S db main
  S attach t1
  execsql { INSERT INTO t1 VALUES(100, 'Bangkok') }
................................................................................
  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.1.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 CONSTRAINT {i 8 n {}}}
  {INSERT t1 CONFLICT {i 6 t six} {i 6 t VI}}
}

do_db2_test 3.1.3 "SELECT * FROM t1" {
  6 VI 3 three 4 four 5 five 7 seven
}
do_execsql_test 3.1.4 "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;
................................................................................
}
do_conflict_test 3.3.3 -tables t4 -sql {
  UPDATE t4 SET a = -1 WHERE b = 2;
  UPDATE t4 SET a = -1 WHERE b = 5;
  UPDATE t4 SET a = NULL WHERE c = 9;
  UPDATE t4 SET a = 'x' WHERE b = 11;
} -conflicts {
  {UPDATE t4 CONSTRAINT {i 7 i 8 i 9} {n {} {} {} {} {}}}
  {UPDATE t4 DATA {i 1 i 2 i 3} {i -1 {} {} {} {}} {i 0 i 2 i 3}}
  {UPDATE t4 NOTFOUND {i 4 i 5 i 6} {i -1 {} {} {} {}}}

}
do_db2_test     3.3.4 { SELECT * FROM t4 } {0 2 3 4 5 7 7 8 9 x 11 12}
do_execsql_test 3.3.5 { SELECT * FROM t4 } {-1 2 3 -1 5 6 {} 8 9 x 11 12}

#-------------------------------------------------------------------------
# This next block of tests verifies that values returned by the conflict
# handler are intepreted correctly.
................................................................................

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

foreach {tn conflict_return after} {
  1 OMIT      {1 2 value1   4 5 7       10 x x}
  2 REPLACE   {1 2 value1   4 5 value2  10 8 9}
} {
  test_reset

  do_test 4.$tn.1 {
    foreach db {db db2} {
      execsql { 
        CREATE TABLE t1(a, b, c, PRIMARY KEY(a));
................................................................................
  } {}

  do_conflict_test 4.$tn.2 -tables t1 -sql {
    UPDATE t1 SET c = 'value1' WHERE a = 1;       -- no conflict
    UPDATE t1 SET c = 'value2' WHERE a = 4;       -- DATA conflict
    UPDATE t1 SET a = 10 WHERE a = 7;             -- CONFLICT conflict
  } -conflicts {
    {INSERT t1 CONFLICT {i 10 i 8 i 9} {i 10 t x t x}}
    {UPDATE t1 DATA {i 4 {} {} i 6} {{} {} {} {} t value2} {i 4 i 5 i 7}}

  }

  do_db2_test 4.$tn.3 "SELECT * FROM t1 ORDER BY a" $after
}

foreach {tn conflict_return} {
  1 OMIT