1 
2 #if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
3 #include "sqlite3session.h"
4 #include <assert.h>
5 #include <string.h>
6 
7 #ifndef SQLITE_AMALGAMATION
8 # include "sqliteInt.h"
9 # include "vdbeInt.h"
10 #endif
11 
12 typedef struct SessionTable SessionTable;
13 typedef struct SessionChange SessionChange;
14 typedef struct SessionBuffer SessionBuffer;
15 typedef struct SessionInput SessionInput;
16 
17 /*
18 ** Minimum chunk size used by streaming versions of functions.
19 */
20 #ifndef SESSIONS_STRM_CHUNK_SIZE
21 # ifdef SQLITE_TEST
22 #   define SESSIONS_STRM_CHUNK_SIZE 64
23 # else
24 #   define SESSIONS_STRM_CHUNK_SIZE 1024
25 # endif
26 #endif
27 
28 static int sessions_strm_chunk_size = SESSIONS_STRM_CHUNK_SIZE;
29 
30 typedef struct SessionHook SessionHook;
31 struct SessionHook {
32   void *pCtx;
33   int (*xOld)(void*,int,sqlite3_value**);
34   int (*xNew)(void*,int,sqlite3_value**);
35   int (*xCount)(void*);
36   int (*xDepth)(void*);
37 };
38 
39 /*
40 ** Session handle structure.
41 */
42 struct sqlite3_session {
43   sqlite3 *db;                    /* Database handle session is attached to */
44   char *zDb;                      /* Name of database session is attached to */
45   int bEnable;                    /* True if currently recording */
46   int bIndirect;                  /* True if all changes are indirect */
47   int bAutoAttach;                /* True to auto-attach tables */
48   int rc;                         /* Non-zero if an error has occurred */
49   void *pFilterCtx;               /* First argument to pass to xTableFilter */
50   int (*xTableFilter)(void *pCtx, const char *zTab);
51   sqlite3_value *pZeroBlob;       /* Value containing X'' */
52   sqlite3_session *pNext;         /* Next session object on same db. */
53   SessionTable *pTable;           /* List of attached tables */
54   SessionHook hook;               /* APIs to grab new and old data with */
55 };
56 
57 /*
58 ** Instances of this structure are used to build strings or binary records.
59 */
60 struct SessionBuffer {
61   u8 *aBuf;                       /* Pointer to changeset buffer */
62   int nBuf;                       /* Size of buffer aBuf */
63   int nAlloc;                     /* Size of allocation containing aBuf */
64 };
65 
66 /*
67 ** An object of this type is used internally as an abstraction for
68 ** input data. Input data may be supplied either as a single large buffer
69 ** (e.g. sqlite3changeset_start()) or using a stream function (e.g.
70 **  sqlite3changeset_start_strm()).
71 */
72 struct SessionInput {
73   int bNoDiscard;                 /* If true, do not discard in InputBuffer() */
74   int iCurrent;                   /* Offset in aData[] of current change */
75   int iNext;                      /* Offset in aData[] of next change */
76   u8 *aData;                      /* Pointer to buffer containing changeset */
77   int nData;                      /* Number of bytes in aData */
78 
79   SessionBuffer buf;              /* Current read buffer */
80   int (*xInput)(void*, void*, int*);        /* Input stream call (or NULL) */
81   void *pIn;                                /* First argument to xInput */
82   int bEof;                       /* Set to true after xInput finished */
83 };
84 
85 /*
86 ** Structure for changeset iterators.
87 */
88 struct sqlite3_changeset_iter {
89   SessionInput in;                /* Input buffer or stream */
90   SessionBuffer tblhdr;           /* Buffer to hold apValue/zTab/abPK/ */
91   int bPatchset;                  /* True if this is a patchset */
92   int bInvert;                    /* True to invert changeset */
93   int rc;                         /* Iterator error code */
94   sqlite3_stmt *pConflict;        /* Points to conflicting row, if any */
95   char *zTab;                     /* Current table */
96   int nCol;                       /* Number of columns in zTab */
97   int op;                         /* Current operation */
98   int bIndirect;                  /* True if current change was indirect */
99   u8 *abPK;                       /* Primary key array */
100   sqlite3_value **apValue;        /* old.* and new.* values */
101 };
102 
103 /*
104 ** Each session object maintains a set of the following structures, one
105 ** for each table the session object is monitoring. The structures are
106 ** stored in a linked list starting at sqlite3_session.pTable.
107 **
108 ** The keys of the SessionTable.aChange[] hash table are all rows that have
109 ** been modified in any way since the session object was attached to the
110 ** table.
111 **
112 ** The data associated with each hash-table entry is a structure containing
113 ** a subset of the initial values that the modified row contained at the
114 ** start of the session. Or no initial values if the row was inserted.
115 */
116 struct SessionTable {
117   SessionTable *pNext;
118   char *zName;                    /* Local name of table */
119   int nCol;                       /* Number of columns in table zName */
120   int bStat1;                     /* True if this is sqlite_stat1 */
121   const char **azCol;             /* Column names */
122   u8 *abPK;                       /* Array of primary key flags */
123   int nEntry;                     /* Total number of entries in hash table */
124   int nChange;                    /* Size of apChange[] array */
125   SessionChange **apChange;       /* Hash table buckets */
126 };
127 
128 /*
129 ** RECORD FORMAT:
130 **
131 ** The following record format is similar to (but not compatible with) that
132 ** used in SQLite database files. This format is used as part of the
133 ** change-set binary format, and so must be architecture independent.
134 **
135 ** Unlike the SQLite database record format, each field is self-contained -
136 ** there is no separation of header and data. Each field begins with a
137 ** single byte describing its type, as follows:
138 **
139 **       0x00: Undefined value.
140 **       0x01: Integer value.
141 **       0x02: Real value.
142 **       0x03: Text value.
143 **       0x04: Blob value.
144 **       0x05: SQL NULL value.
145 **
146 ** Note that the above match the definitions of SQLITE_INTEGER, SQLITE_TEXT
147 ** and so on in sqlite3.h. For undefined and NULL values, the field consists
148 ** only of the single type byte. For other types of values, the type byte
149 ** is followed by:
150 **
151 **   Text values:
152 **     A varint containing the number of bytes in the value (encoded using
153 **     UTF-8). Followed by a buffer containing the UTF-8 representation
154 **     of the text value. There is no nul terminator.
155 **
156 **   Blob values:
157 **     A varint containing the number of bytes in the value, followed by
158 **     a buffer containing the value itself.
159 **
160 **   Integer values:
161 **     An 8-byte big-endian integer value.
162 **
163 **   Real values:
164 **     An 8-byte big-endian IEEE 754-2008 real value.
165 **
166 ** Varint values are encoded in the same way as varints in the SQLite
167 ** record format.
168 **
169 ** CHANGESET FORMAT:
170 **
171 ** A changeset is a collection of DELETE, UPDATE and INSERT operations on
172 ** one or more tables. Operations on a single table are grouped together,
173 ** but may occur in any order (i.e. deletes, updates and inserts are all
174 ** mixed together).
175 **
176 ** Each group of changes begins with a table header:
177 **
178 **   1 byte: Constant 0x54 (capital 'T')
179 **   Varint: Number of columns in the table.
180 **   nCol bytes: 0x01 for PK columns, 0x00 otherwise.
181 **   N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
182 **
183 ** Followed by one or more changes to the table.
184 **
185 **   1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
186 **   1 byte: The "indirect-change" flag.
187 **   old.* record: (delete and update only)
188 **   new.* record: (insert and update only)
189 **
190 ** The "old.*" and "new.*" records, if present, are N field records in the
191 ** format described above under "RECORD FORMAT", where N is the number of
192 ** columns in the table. The i'th field of each record is associated with
193 ** the i'th column of the table, counting from left to right in the order
194 ** in which columns were declared in the CREATE TABLE statement.
195 **
196 ** The new.* record that is part of each INSERT change contains the values
197 ** that make up the new row. Similarly, the old.* record that is part of each
198 ** DELETE change contains the values that made up the row that was deleted
199 ** from the database. In the changeset format, the records that are part
200 ** of INSERT or DELETE changes never contain any undefined (type byte 0x00)
201 ** fields.
202 **
203 ** Within the old.* record associated with an UPDATE change, all fields
204 ** associated with table columns that are not PRIMARY KEY columns and are
205 ** not modified by the UPDATE change are set to "undefined". Other fields
206 ** are set to the values that made up the row before the UPDATE that the
207 ** change records took place. Within the new.* record, fields associated
208 ** with table columns modified by the UPDATE change contain the new
209 ** values. Fields associated with table columns that are not modified
210 ** are set to "undefined".
211 **
212 ** PATCHSET FORMAT:
213 **
214 ** A patchset is also a collection of changes. It is similar to a changeset,
215 ** but leaves undefined those fields that are not useful if no conflict
216 ** resolution is required when applying the changeset.
217 **
218 ** Each group of changes begins with a table header:
219 **
220 **   1 byte: Constant 0x50 (capital 'P')
221 **   Varint: Number of columns in the table.
222 **   nCol bytes: 0x01 for PK columns, 0x00 otherwise.
223 **   N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
224 **
225 ** Followed by one or more changes to the table.
226 **
227 **   1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
228 **   1 byte: The "indirect-change" flag.
229 **   single record: (PK fields for DELETE, PK and modified fields for UPDATE,
230 **                   full record for INSERT).
231 **
232 ** As in the changeset format, each field of the single record that is part
233 ** of a patchset change is associated with the correspondingly positioned
234 ** table column, counting from left to right within the CREATE TABLE
235 ** statement.
236 **
237 ** For a DELETE change, all fields within the record except those associated
238 ** with PRIMARY KEY columns are omitted. The PRIMARY KEY fields contain the
239 ** values identifying the row to delete.
240 **
241 ** For an UPDATE change, all fields except those associated with PRIMARY KEY
242 ** columns and columns that are modified by the UPDATE are set to "undefined".
243 ** PRIMARY KEY fields contain the values identifying the table row to update,
244 ** and fields associated with modified columns contain the new column values.
245 **
246 ** The records associated with INSERT changes are in the same format as for
247 ** changesets. It is not possible for a record associated with an INSERT
248 ** change to contain a field set to "undefined".
249 **
250 ** REBASE BLOB FORMAT:
251 **
252 ** A rebase blob may be output by sqlite3changeset_apply_v2() and its
253 ** streaming equivalent for use with the sqlite3_rebaser APIs to rebase
254 ** existing changesets. A rebase blob contains one entry for each conflict
255 ** resolved using either the OMIT or REPLACE strategies within the apply_v2()
256 ** call.
257 **
258 ** The format used for a rebase blob is very similar to that used for
259 ** changesets. All entries related to a single table are grouped together.
260 **
261 ** Each group of entries begins with a table header in changeset format:
262 **
263 **   1 byte: Constant 0x54 (capital 'T')
264 **   Varint: Number of columns in the table.
265 **   nCol bytes: 0x01 for PK columns, 0x00 otherwise.
266 **   N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
267 **
268 ** Followed by one or more entries associated with the table.
269 **
270 **   1 byte: Either SQLITE_INSERT (0x12), DELETE (0x09).
271 **   1 byte: Flag. 0x01 for REPLACE, 0x00 for OMIT.
272 **   record: (in the record format defined above).
273 **
274 ** In a rebase blob, the first field is set to SQLITE_INSERT if the change
275 ** that caused the conflict was an INSERT or UPDATE, or to SQLITE_DELETE if
276 ** it was a DELETE. The second field is set to 0x01 if the conflict
277 ** resolution strategy was REPLACE, or 0x00 if it was OMIT.
278 **
279 ** If the change that caused the conflict was a DELETE, then the single
280 ** record is a copy of the old.* record from the original changeset. If it
281 ** was an INSERT, then the single record is a copy of the new.* record. If
282 ** the conflicting change was an UPDATE, then the single record is a copy
283 ** of the new.* record with the PK fields filled in based on the original
284 ** old.* record.
285 */
286 
287 /*
288 ** For each row modified during a session, there exists a single instance of
289 ** this structure stored in a SessionTable.aChange[] hash table.
290 */
291 struct SessionChange {
292   int op;                         /* One of UPDATE, DELETE, INSERT */
293   int bIndirect;                  /* True if this change is "indirect" */
294   int nRecord;                    /* Number of bytes in buffer aRecord[] */
295   u8 *aRecord;                    /* Buffer containing old.* record */
296   SessionChange *pNext;           /* For hash-table collisions */
297 };
298 
299 /*
300 ** Write a varint with value iVal into the buffer at aBuf. Return the
301 ** number of bytes written.
302 */
303 static int sessionVarintPut(u8 *aBuf, int iVal){
304   return putVarint32(aBuf, iVal);
305 }
306 
307 /*
308 ** Return the number of bytes required to store value iVal as a varint.
309 */
310 static int sessionVarintLen(int iVal){
311   return sqlite3VarintLen(iVal);
312 }
313 
314 /*
315 ** Read a varint value from aBuf[] into *piVal. Return the number of
316 ** bytes read.
317 */
318 static int sessionVarintGet(u8 *aBuf, int *piVal){
319   return getVarint32(aBuf, *piVal);
320 }
321 
322 /* Load an unaligned and unsigned 32-bit integer */
323 #define SESSION_UINT32(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
324 
325 /*
326 ** Read a 64-bit big-endian integer value from buffer aRec[]. Return
327 ** the value read.
328 */
329 static sqlite3_int64 sessionGetI64(u8 *aRec){
330   u64 x = SESSION_UINT32(aRec);
331   u32 y = SESSION_UINT32(aRec+4);
332   x = (x<<32) + y;
333   return (sqlite3_int64)x;
334 }
335 
336 /*
337 ** Write a 64-bit big-endian integer value to the buffer aBuf[].
338 */
339 static void sessionPutI64(u8 *aBuf, sqlite3_int64 i){
340   aBuf[0] = (i>>56) & 0xFF;
341   aBuf[1] = (i>>48) & 0xFF;
342   aBuf[2] = (i>>40) & 0xFF;
343   aBuf[3] = (i>>32) & 0xFF;
344   aBuf[4] = (i>>24) & 0xFF;
345   aBuf[5] = (i>>16) & 0xFF;
346   aBuf[6] = (i>> 8) & 0xFF;
347   aBuf[7] = (i>> 0) & 0xFF;
348 }
349 
350 /*
351 ** This function is used to serialize the contents of value pValue (see
352 ** comment titled "RECORD FORMAT" above).
353 **
354 ** If it is non-NULL, the serialized form of the value is written to
355 ** buffer aBuf. *pnWrite is set to the number of bytes written before
356 ** returning. Or, if aBuf is NULL, the only thing this function does is
357 ** set *pnWrite.
358 **
359 ** If no error occurs, SQLITE_OK is returned. Or, if an OOM error occurs
360 ** within a call to sqlite3_value_text() (may fail if the db is utf-16))
361 ** SQLITE_NOMEM is returned.
362 */
363 static int sessionSerializeValue(
364   u8 *aBuf,                       /* If non-NULL, write serialized value here */
365   sqlite3_value *pValue,          /* Value to serialize */
366   int *pnWrite                    /* IN/OUT: Increment by bytes written */
367 ){
368   int nByte;                      /* Size of serialized value in bytes */
369 
370   if( pValue ){
371     int eType;                    /* Value type (SQLITE_NULL, TEXT etc.) */
372 
373     eType = sqlite3_value_type(pValue);
374     if( aBuf ) aBuf[0] = eType;
375 
376     switch( eType ){
377       case SQLITE_NULL:
378         nByte = 1;
379         break;
380 
381       case SQLITE_INTEGER:
382       case SQLITE_FLOAT:
383         if( aBuf ){
384           /* TODO: SQLite does something special to deal with mixed-endian
385           ** floating point values (e.g. ARM7). This code probably should
386           ** too.  */
387           u64 i;
388           if( eType==SQLITE_INTEGER ){
389             i = (u64)sqlite3_value_int64(pValue);
390           }else{
391             double r;
392             assert( sizeof(double)==8 && sizeof(u64)==8 );
393             r = sqlite3_value_double(pValue);
394             memcpy(&i, &r, 8);
395           }
396           sessionPutI64(&aBuf[1], i);
397         }
398         nByte = 9;
399         break;
400 
401       default: {
402         u8 *z;
403         int n;
404         int nVarint;
405 
406         assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
407         if( eType==SQLITE_TEXT ){
408           z = (u8 *)sqlite3_value_text(pValue);
409         }else{
410           z = (u8 *)sqlite3_value_blob(pValue);
411         }
412         n = sqlite3_value_bytes(pValue);
413         if( z==0 && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
414         nVarint = sessionVarintLen(n);
415 
416         if( aBuf ){
417           sessionVarintPut(&aBuf[1], n);
418           if( n ) memcpy(&aBuf[nVarint + 1], z, n);
419         }
420 
421         nByte = 1 + nVarint + n;
422         break;
423       }
424     }
425   }else{
426     nByte = 1;
427     if( aBuf ) aBuf[0] = '\0';
428   }
429 
430   if( pnWrite ) *pnWrite += nByte;
431   return SQLITE_OK;
432 }
433 
434 
435 /*
436 ** This macro is used to calculate hash key values for data structures. In
437 ** order to use this macro, the entire data structure must be represented
438 ** as a series of unsigned integers. In order to calculate a hash-key value
439 ** for a data structure represented as three such integers, the macro may
440 ** then be used as follows:
441 **
442 **    int hash_key_value;
443 **    hash_key_value = HASH_APPEND(0, <value 1>);
444 **    hash_key_value = HASH_APPEND(hash_key_value, <value 2>);
445 **    hash_key_value = HASH_APPEND(hash_key_value, <value 3>);
446 **
447 ** In practice, the data structures this macro is used for are the primary
448 ** key values of modified rows.
449 */
450 #define HASH_APPEND(hash, add) ((hash) << 3) ^ (hash) ^ (unsigned int)(add)
451 
452 /*
453 ** Append the hash of the 64-bit integer passed as the second argument to the
454 ** hash-key value passed as the first. Return the new hash-key value.
455 */
456 static unsigned int sessionHashAppendI64(unsigned int h, i64 i){
457   h = HASH_APPEND(h, i & 0xFFFFFFFF);
458   return HASH_APPEND(h, (i>>32)&0xFFFFFFFF);
459 }
460 
461 /*
462 ** Append the hash of the blob passed via the second and third arguments to
463 ** the hash-key value passed as the first. Return the new hash-key value.
464 */
465 static unsigned int sessionHashAppendBlob(unsigned int h, int n, const u8 *z){
466   int i;
467   for(i=0; i<n; i++) h = HASH_APPEND(h, z[i]);
468   return h;
469 }
470 
471 /*
472 ** Append the hash of the data type passed as the second argument to the
473 ** hash-key value passed as the first. Return the new hash-key value.
474 */
475 static unsigned int sessionHashAppendType(unsigned int h, int eType){
476   return HASH_APPEND(h, eType);
477 }
478 
479 /*
480 ** This function may only be called from within a pre-update callback.
481 ** It calculates a hash based on the primary key values of the old.* or
482 ** new.* row currently available and, assuming no error occurs, writes it to
483 ** *piHash before returning. If the primary key contains one or more NULL
484 ** values, *pbNullPK is set to true before returning.
485 **
486 ** If an error occurs, an SQLite error code is returned and the final values
487 ** of *piHash asn *pbNullPK are undefined. Otherwise, SQLITE_OK is returned
488 ** and the output variables are set as described above.
489 */
490 static int sessionPreupdateHash(
491   sqlite3_session *pSession,      /* Session object that owns pTab */
492   SessionTable *pTab,             /* Session table handle */
493   int bNew,                       /* True to hash the new.* PK */
494   int *piHash,                    /* OUT: Hash value */
495   int *pbNullPK                   /* OUT: True if there are NULL values in PK */
496 ){
497   unsigned int h = 0;             /* Hash value to return */
498   int i;                          /* Used to iterate through columns */
499 
500   assert( *pbNullPK==0 );
501   assert( pTab->nCol==pSession->hook.xCount(pSession->hook.pCtx) );
502   for(i=0; i<pTab->nCol; i++){
503     if( pTab->abPK[i] ){
504       int rc;
505       int eType;
506       sqlite3_value *pVal;
507 
508       if( bNew ){
509         rc = pSession->hook.xNew(pSession->hook.pCtx, i, &pVal);
510       }else{
511         rc = pSession->hook.xOld(pSession->hook.pCtx, i, &pVal);
512       }
513       if( rc!=SQLITE_OK ) return rc;
514 
515       eType = sqlite3_value_type(pVal);
516       h = sessionHashAppendType(h, eType);
517       if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
518         i64 iVal;
519         if( eType==SQLITE_INTEGER ){
520           iVal = sqlite3_value_int64(pVal);
521         }else{
522           double rVal = sqlite3_value_double(pVal);
523           assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
524           memcpy(&iVal, &rVal, 8);
525         }
526         h = sessionHashAppendI64(h, iVal);
527       }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
528         const u8 *z;
529         int n;
530         if( eType==SQLITE_TEXT ){
531           z = (const u8 *)sqlite3_value_text(pVal);
532         }else{
533           z = (const u8 *)sqlite3_value_blob(pVal);
534         }
535         n = sqlite3_value_bytes(pVal);
536         if( !z && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
537         h = sessionHashAppendBlob(h, n, z);
538       }else{
539         assert( eType==SQLITE_NULL );
540         assert( pTab->bStat1==0 || i!=1 );
541         *pbNullPK = 1;
542       }
543     }
544   }
545 
546   *piHash = (h % pTab->nChange);
547   return SQLITE_OK;
548 }
549 
550 /*
551 ** The buffer that the argument points to contains a serialized SQL value.
552 ** Return the number of bytes of space occupied by the value (including
553 ** the type byte).
554 */
555 static int sessionSerialLen(u8 *a){
556   int e = *a;
557   int n;
558   if( e==0 || e==0xFF ) return 1;
559   if( e==SQLITE_NULL ) return 1;
560   if( e==SQLITE_INTEGER || e==SQLITE_FLOAT ) return 9;
561   return sessionVarintGet(&a[1], &n) + 1 + n;
562 }
563 
564 /*
565 ** Based on the primary key values stored in change aRecord, calculate a
566 ** hash key. Assume the has table has nBucket buckets. The hash keys
567 ** calculated by this function are compatible with those calculated by
568 ** sessionPreupdateHash().
569 **
570 ** The bPkOnly argument is non-zero if the record at aRecord[] is from
571 ** a patchset DELETE. In this case the non-PK fields are omitted entirely.
572 */
573 static unsigned int sessionChangeHash(
574   SessionTable *pTab,             /* Table handle */
575   int bPkOnly,                    /* Record consists of PK fields only */
576   u8 *aRecord,                    /* Change record */
577   int nBucket                     /* Assume this many buckets in hash table */
578 ){
579   unsigned int h = 0;             /* Value to return */
580   int i;                          /* Used to iterate through columns */
581   u8 *a = aRecord;                /* Used to iterate through change record */
582 
583   for(i=0; i<pTab->nCol; i++){
584     int eType = *a;
585     int isPK = pTab->abPK[i];
586     if( bPkOnly && isPK==0 ) continue;
587 
588     /* It is not possible for eType to be SQLITE_NULL here. The session
589     ** module does not record changes for rows with NULL values stored in
590     ** primary key columns. */
591     assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
592          || eType==SQLITE_TEXT || eType==SQLITE_BLOB
593          || eType==SQLITE_NULL || eType==0
594     );
595     assert( !isPK || (eType!=0 && eType!=SQLITE_NULL) );
596 
597     if( isPK ){
598       a++;
599       h = sessionHashAppendType(h, eType);
600       if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
601         h = sessionHashAppendI64(h, sessionGetI64(a));
602         a += 8;
603       }else{
604         int n;
605         a += sessionVarintGet(a, &n);
606         h = sessionHashAppendBlob(h, n, a);
607         a += n;
608       }
609     }else{
610       a += sessionSerialLen(a);
611     }
612   }
613   return (h % nBucket);
614 }
615 
616 /*
617 ** Arguments aLeft and aRight are pointers to change records for table pTab.
618 ** This function returns true if the two records apply to the same row (i.e.
619 ** have the same values stored in the primary key columns), or false
620 ** otherwise.
621 */
622 static int sessionChangeEqual(
623   SessionTable *pTab,             /* Table used for PK definition */
624   int bLeftPkOnly,                /* True if aLeft[] contains PK fields only */
625   u8 *aLeft,                      /* Change record */
626   int bRightPkOnly,               /* True if aRight[] contains PK fields only */
627   u8 *aRight                      /* Change record */
628 ){
629   u8 *a1 = aLeft;                 /* Cursor to iterate through aLeft */
630   u8 *a2 = aRight;                /* Cursor to iterate through aRight */
631   int iCol;                       /* Used to iterate through table columns */
632 
633   for(iCol=0; iCol<pTab->nCol; iCol++){
634     if( pTab->abPK[iCol] ){
635       int n1 = sessionSerialLen(a1);
636       int n2 = sessionSerialLen(a2);
637 
638       if( n1!=n2 || memcmp(a1, a2, n1) ){
639         return 0;
640       }
641       a1 += n1;
642       a2 += n2;
643     }else{
644       if( bLeftPkOnly==0 ) a1 += sessionSerialLen(a1);
645       if( bRightPkOnly==0 ) a2 += sessionSerialLen(a2);
646     }
647   }
648 
649   return 1;
650 }
651 
652 /*
653 ** Arguments aLeft and aRight both point to buffers containing change
654 ** records with nCol columns. This function "merges" the two records into
655 ** a single records which is written to the buffer at *paOut. *paOut is
656 ** then set to point to one byte after the last byte written before
657 ** returning.
658 **
659 ** The merging of records is done as follows: For each column, if the
660 ** aRight record contains a value for the column, copy the value from
661 ** their. Otherwise, if aLeft contains a value, copy it. If neither
662 ** record contains a value for a given column, then neither does the
663 ** output record.
664 */
665 static void sessionMergeRecord(
666   u8 **paOut,
667   int nCol,
668   u8 *aLeft,
669   u8 *aRight
670 ){
671   u8 *a1 = aLeft;                 /* Cursor used to iterate through aLeft */
672   u8 *a2 = aRight;                /* Cursor used to iterate through aRight */
673   u8 *aOut = *paOut;              /* Output cursor */
674   int iCol;                       /* Used to iterate from 0 to nCol */
675 
676   for(iCol=0; iCol<nCol; iCol++){
677     int n1 = sessionSerialLen(a1);
678     int n2 = sessionSerialLen(a2);
679     if( *a2 ){
680       memcpy(aOut, a2, n2);
681       aOut += n2;
682     }else{
683       memcpy(aOut, a1, n1);
684       aOut += n1;
685     }
686     a1 += n1;
687     a2 += n2;
688   }
689 
690   *paOut = aOut;
691 }
692 
693 /*
694 ** This is a helper function used by sessionMergeUpdate().
695 **
696 ** When this function is called, both *paOne and *paTwo point to a value
697 ** within a change record. Before it returns, both have been advanced so
698 ** as to point to the next value in the record.
699 **
700 ** If, when this function is called, *paTwo points to a valid value (i.e.
701 ** *paTwo[0] is not 0x00 - the "no value" placeholder), a copy of the *paTwo
702 ** pointer is returned and *pnVal is set to the number of bytes in the
703 ** serialized value. Otherwise, a copy of *paOne is returned and *pnVal
704 ** set to the number of bytes in the value at *paOne. If *paOne points
705 ** to the "no value" placeholder, *pnVal is set to 1. In other words:
706 **
707 **   if( *paTwo is valid ) return *paTwo;
708 **   return *paOne;
709 **
710 */
711 static u8 *sessionMergeValue(
712   u8 **paOne,                     /* IN/OUT: Left-hand buffer pointer */
713   u8 **paTwo,                     /* IN/OUT: Right-hand buffer pointer */
714   int *pnVal                      /* OUT: Bytes in returned value */
715 ){
716   u8 *a1 = *paOne;
717   u8 *a2 = *paTwo;
718   u8 *pRet = 0;
719   int n1;
720 
721   assert( a1 );
722   if( a2 ){
723     int n2 = sessionSerialLen(a2);
724     if( *a2 ){
725       *pnVal = n2;
726       pRet = a2;
727     }
728     *paTwo = &a2[n2];
729   }
730 
731   n1 = sessionSerialLen(a1);
732   if( pRet==0 ){
733     *pnVal = n1;
734     pRet = a1;
735   }
736   *paOne = &a1[n1];
737 
738   return pRet;
739 }
740 
741 /*
742 ** This function is used by changeset_concat() to merge two UPDATE changes
743 ** on the same row.
744 */
745 static int sessionMergeUpdate(
746   u8 **paOut,                     /* IN/OUT: Pointer to output buffer */
747   SessionTable *pTab,             /* Table change pertains to */
748   int bPatchset,                  /* True if records are patchset records */
749   u8 *aOldRecord1,                /* old.* record for first change */
750   u8 *aOldRecord2,                /* old.* record for second change */
751   u8 *aNewRecord1,                /* new.* record for first change */
752   u8 *aNewRecord2                 /* new.* record for second change */
753 ){
754   u8 *aOld1 = aOldRecord1;
755   u8 *aOld2 = aOldRecord2;
756   u8 *aNew1 = aNewRecord1;
757   u8 *aNew2 = aNewRecord2;
758 
759   u8 *aOut = *paOut;
760   int i;
761 
762   if( bPatchset==0 ){
763     int bRequired = 0;
764 
765     assert( aOldRecord1 && aNewRecord1 );
766 
767     /* Write the old.* vector first. */
768     for(i=0; i<pTab->nCol; i++){
769       int nOld;
770       u8 *aOld;
771       int nNew;
772       u8 *aNew;
773 
774       aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
775       aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
776       if( pTab->abPK[i] || nOld!=nNew || memcmp(aOld, aNew, nNew) ){
777         if( pTab->abPK[i]==0 ) bRequired = 1;
778         memcpy(aOut, aOld, nOld);
779         aOut += nOld;
780       }else{
781         *(aOut++) = '\0';
782       }
783     }
784 
785     if( !bRequired ) return 0;
786   }
787 
788   /* Write the new.* vector */
789   aOld1 = aOldRecord1;
790   aOld2 = aOldRecord2;
791   aNew1 = aNewRecord1;
792   aNew2 = aNewRecord2;
793   for(i=0; i<pTab->nCol; i++){
794     int nOld;
795     u8 *aOld;
796     int nNew;
797     u8 *aNew;
798 
799     aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
800     aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
801     if( bPatchset==0
802      && (pTab->abPK[i] || (nOld==nNew && 0==memcmp(aOld, aNew, nNew)))
803     ){
804       *(aOut++) = '\0';
805     }else{
806       memcpy(aOut, aNew, nNew);
807       aOut += nNew;
808     }
809   }
810 
811   *paOut = aOut;
812   return 1;
813 }
814 
815 /*
816 ** This function is only called from within a pre-update-hook callback.
817 ** It determines if the current pre-update-hook change affects the same row
818 ** as the change stored in argument pChange. If so, it returns true. Otherwise
819 ** if the pre-update-hook does not affect the same row as pChange, it returns
820 ** false.
821 */
822 static int sessionPreupdateEqual(
823   sqlite3_session *pSession,      /* Session object that owns SessionTable */
824   SessionTable *pTab,             /* Table associated with change */
825   SessionChange *pChange,         /* Change to compare to */
826   int op                          /* Current pre-update operation */
827 ){
828   int iCol;                       /* Used to iterate through columns */
829   u8 *a = pChange->aRecord;       /* Cursor used to scan change record */
830 
831   assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
832   for(iCol=0; iCol<pTab->nCol; iCol++){
833     if( !pTab->abPK[iCol] ){
834       a += sessionSerialLen(a);
835     }else{
836       sqlite3_value *pVal;        /* Value returned by preupdate_new/old */
837       int rc;                     /* Error code from preupdate_new/old */
838       int eType = *a++;           /* Type of value from change record */
839 
840       /* The following calls to preupdate_new() and preupdate_old() can not
841       ** fail. This is because they cache their return values, and by the
842       ** time control flows to here they have already been called once from
843       ** within sessionPreupdateHash(). The first two asserts below verify
844       ** this (that the method has already been called). */
845       if( op==SQLITE_INSERT ){
846         /* assert( db->pPreUpdate->pNewUnpacked || db->pPreUpdate->aNew ); */
847         rc = pSession->hook.xNew(pSession->hook.pCtx, iCol, &pVal);
848       }else{
849         /* assert( db->pPreUpdate->pUnpacked ); */
850         rc = pSession->hook.xOld(pSession->hook.pCtx, iCol, &pVal);
851       }
852       assert( rc==SQLITE_OK );
853       if( sqlite3_value_type(pVal)!=eType ) return 0;
854 
855       /* A SessionChange object never has a NULL value in a PK column */
856       assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
857            || eType==SQLITE_BLOB    || eType==SQLITE_TEXT
858       );
859 
860       if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
861         i64 iVal = sessionGetI64(a);
862         a += 8;
863         if( eType==SQLITE_INTEGER ){
864           if( sqlite3_value_int64(pVal)!=iVal ) return 0;
865         }else{
866           double rVal;
867           assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
868           memcpy(&rVal, &iVal, 8);
869           if( sqlite3_value_double(pVal)!=rVal ) return 0;
870         }
871       }else{
872         int n;
873         const u8 *z;
874         a += sessionVarintGet(a, &n);
875         if( sqlite3_value_bytes(pVal)!=n ) return 0;
876         if( eType==SQLITE_TEXT ){
877           z = sqlite3_value_text(pVal);
878         }else{
879           z = sqlite3_value_blob(pVal);
880         }
881         if( n>0 && memcmp(a, z, n) ) return 0;
882         a += n;
883       }
884     }
885   }
886 
887   return 1;
888 }
889 
890 /*
891 ** If required, grow the hash table used to store changes on table pTab
892 ** (part of the session pSession). If a fatal OOM error occurs, set the
893 ** session object to failed and return SQLITE_ERROR. Otherwise, return
894 ** SQLITE_OK.
895 **
896 ** It is possible that a non-fatal OOM error occurs in this function. In
897 ** that case the hash-table does not grow, but SQLITE_OK is returned anyway.
898 ** Growing the hash table in this case is a performance optimization only,
899 ** it is not required for correct operation.
900 */
901 static int sessionGrowHash(int bPatchset, SessionTable *pTab){
902   if( pTab->nChange==0 || pTab->nEntry>=(pTab->nChange/2) ){
903     int i;
904     SessionChange **apNew;
905     int nNew = (pTab->nChange ? pTab->nChange : 128) * 2;
906 
907     apNew = (SessionChange **)sqlite3_malloc(sizeof(SessionChange *) * nNew);
908     if( apNew==0 ){
909       if( pTab->nChange==0 ){
910         return SQLITE_ERROR;
911       }
912       return SQLITE_OK;
913     }
914     memset(apNew, 0, sizeof(SessionChange *) * nNew);
915 
916     for(i=0; i<pTab->nChange; i++){
917       SessionChange *p;
918       SessionChange *pNext;
919       for(p=pTab->apChange[i]; p; p=pNext){
920         int bPkOnly = (p->op==SQLITE_DELETE && bPatchset);
921         int iHash = sessionChangeHash(pTab, bPkOnly, p->aRecord, nNew);
922         pNext = p->pNext;
923         p->pNext = apNew[iHash];
924         apNew[iHash] = p;
925       }
926     }
927 
928     sqlite3_free(pTab->apChange);
929     pTab->nChange = nNew;
930     pTab->apChange = apNew;
931   }
932 
933   return SQLITE_OK;
934 }
935 
936 /*
937 ** This function queries the database for the names of the columns of table
938 ** zThis, in schema zDb.
939 **
940 ** Otherwise, if they are not NULL, variable *pnCol is set to the number
941 ** of columns in the database table and variable *pzTab is set to point to a
942 ** nul-terminated copy of the table name. *pazCol (if not NULL) is set to
943 ** point to an array of pointers to column names. And *pabPK (again, if not
944 ** NULL) is set to point to an array of booleans - true if the corresponding
945 ** column is part of the primary key.
946 **
947 ** For example, if the table is declared as:
948 **
949 **     CREATE TABLE tbl1(w, x, y, z, PRIMARY KEY(w, z));
950 **
951 ** Then the four output variables are populated as follows:
952 **
953 **     *pnCol  = 4
954 **     *pzTab  = "tbl1"
955 **     *pazCol = {"w", "x", "y", "z"}
956 **     *pabPK  = {1, 0, 0, 1}
957 **
958 ** All returned buffers are part of the same single allocation, which must
959 ** be freed using sqlite3_free() by the caller
960 */
961 static int sessionTableInfo(
962   sqlite3 *db,                    /* Database connection */
963   const char *zDb,                /* Name of attached database (e.g. "main") */
964   const char *zThis,              /* Table name */
965   int *pnCol,                     /* OUT: number of columns */
966   const char **pzTab,             /* OUT: Copy of zThis */
967   const char ***pazCol,           /* OUT: Array of column names for table */
968   u8 **pabPK                      /* OUT: Array of booleans - true for PK col */
969 ){
970   char *zPragma;
971   sqlite3_stmt *pStmt;
972   int rc;
973   int nByte;
974   int nDbCol = 0;
975   int nThis;
976   int i;
977   u8 *pAlloc = 0;
978   char **azCol = 0;
979   u8 *abPK = 0;
980 
981   assert( pazCol && pabPK );
982 
983   nThis = sqlite3Strlen30(zThis);
984   if( nThis==12 && 0==sqlite3_stricmp("sqlite_stat1", zThis) ){
985     rc = sqlite3_table_column_metadata(db, zDb, zThis, 0, 0, 0, 0, 0, 0);
986     if( rc==SQLITE_OK ){
987       /* For sqlite_stat1, pretend that (tbl,idx) is the PRIMARY KEY. */
988       zPragma = sqlite3_mprintf(
989           "SELECT 0, 'tbl',  '', 0, '', 1     UNION ALL "
990           "SELECT 1, 'idx',  '', 0, '', 2     UNION ALL "
991           "SELECT 2, 'stat', '', 0, '', 0"
992       );
993     }else if( rc==SQLITE_ERROR ){
994       zPragma = sqlite3_mprintf("");
995     }else{
996       return rc;
997     }
998   }else{
999     zPragma = sqlite3_mprintf("PRAGMA '%q'.table_info('%q')", zDb, zThis);
1000   }
1001   if( !zPragma ) return SQLITE_NOMEM;
1002 
1003   rc = sqlite3_prepare_v2(db, zPragma, -1, &pStmt, 0);
1004   sqlite3_free(zPragma);
1005   if( rc!=SQLITE_OK ) return rc;
1006 
1007   nByte = nThis + 1;
1008   while( SQLITE_ROW==sqlite3_step(pStmt) ){
1009     nByte += sqlite3_column_bytes(pStmt, 1);
1010     nDbCol++;
1011   }
1012   rc = sqlite3_reset(pStmt);
1013 
1014   if( rc==SQLITE_OK ){
1015     nByte += nDbCol * (sizeof(const char *) + sizeof(u8) + 1);
1016     pAlloc = sqlite3_malloc(nByte);
1017     if( pAlloc==0 ){
1018       rc = SQLITE_NOMEM;
1019     }
1020   }
1021   if( rc==SQLITE_OK ){
1022     azCol = (char **)pAlloc;
1023     pAlloc = (u8 *)&azCol[nDbCol];
1024     abPK = (u8 *)pAlloc;
1025     pAlloc = &abPK[nDbCol];
1026     if( pzTab ){
1027       memcpy(pAlloc, zThis, nThis+1);
1028       *pzTab = (char *)pAlloc;
1029       pAlloc += nThis+1;
1030     }
1031 
1032     i = 0;
1033     while( SQLITE_ROW==sqlite3_step(pStmt) ){
1034       int nName = sqlite3_column_bytes(pStmt, 1);
1035       const unsigned char *zName = sqlite3_column_text(pStmt, 1);
1036       if( zName==0 ) break;
1037       memcpy(pAlloc, zName, nName+1);
1038       azCol[i] = (char *)pAlloc;
1039       pAlloc += nName+1;
1040       abPK[i] = sqlite3_column_int(pStmt, 5);
1041       i++;
1042     }
1043     rc = sqlite3_reset(pStmt);
1044 
1045   }
1046 
1047   /* If successful, populate the output variables. Otherwise, zero them and
1048   ** free any allocation made. An error code will be returned in this case.
1049   */
1050   if( rc==SQLITE_OK ){
1051     *pazCol = (const char **)azCol;
1052     *pabPK = abPK;
1053     *pnCol = nDbCol;
1054   }else{
1055     *pazCol = 0;
1056     *pabPK = 0;
1057     *pnCol = 0;
1058     if( pzTab ) *pzTab = 0;
1059     sqlite3_free(azCol);
1060   }
1061   sqlite3_finalize(pStmt);
1062   return rc;
1063 }
1064 
1065 /*
1066 ** This function is only called from within a pre-update handler for a
1067 ** write to table pTab, part of session pSession. If this is the first
1068 ** write to this table, initalize the SessionTable.nCol, azCol[] and
1069 ** abPK[] arrays accordingly.
1070 **
1071 ** If an error occurs, an error code is stored in sqlite3_session.rc and
1072 ** non-zero returned. Or, if no error occurs but the table has no primary
1073 ** key, sqlite3_session.rc is left set to SQLITE_OK and non-zero returned to
1074 ** indicate that updates on this table should be ignored. SessionTable.abPK
1075 ** is set to NULL in this case.
1076 */
1077 static int sessionInitTable(sqlite3_session *pSession, SessionTable *pTab){
1078   if( pTab->nCol==0 ){
1079     u8 *abPK;
1080     assert( pTab->azCol==0 || pTab->abPK==0 );
1081     pSession->rc = sessionTableInfo(pSession->db, pSession->zDb,
1082         pTab->zName, &pTab->nCol, 0, &pTab->azCol, &abPK
1083     );
1084     if( pSession->rc==SQLITE_OK ){
1085       int i;
1086       for(i=0; i<pTab->nCol; i++){
1087         if( abPK[i] ){
1088           pTab->abPK = abPK;
1089           break;
1090         }
1091       }
1092       if( 0==sqlite3_stricmp("sqlite_stat1", pTab->zName) ){
1093         pTab->bStat1 = 1;
1094       }
1095     }
1096   }
1097   return (pSession->rc || pTab->abPK==0);
1098 }
1099 
1100 /*
1101 ** Versions of the four methods in object SessionHook for use with the
1102 ** sqlite_stat1 table. The purpose of this is to substitute a zero-length
1103 ** blob each time a NULL value is read from the "idx" column of the
1104 ** sqlite_stat1 table.
1105 */
1106 typedef struct SessionStat1Ctx SessionStat1Ctx;
1107 struct SessionStat1Ctx {
1108   SessionHook hook;
1109   sqlite3_session *pSession;
1110 };
1111 static int sessionStat1Old(void *pCtx, int iCol, sqlite3_value **ppVal){
1112   SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
1113   sqlite3_value *pVal = 0;
1114   int rc = p->hook.xOld(p->hook.pCtx, iCol, &pVal);
1115   if( rc==SQLITE_OK && iCol==1 && sqlite3_value_type(pVal)==SQLITE_NULL ){
1116     pVal = p->pSession->pZeroBlob;
1117   }
1118   *ppVal = pVal;
1119   return rc;
1120 }
1121 static int sessionStat1New(void *pCtx, int iCol, sqlite3_value **ppVal){
1122   SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
1123   sqlite3_value *pVal = 0;
1124   int rc = p->hook.xNew(p->hook.pCtx, iCol, &pVal);
1125   if( rc==SQLITE_OK && iCol==1 && sqlite3_value_type(pVal)==SQLITE_NULL ){
1126     pVal = p->pSession->pZeroBlob;
1127   }
1128   *ppVal = pVal;
1129   return rc;
1130 }
1131 static int sessionStat1Count(void *pCtx){
1132   SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
1133   return p->hook.xCount(p->hook.pCtx);
1134 }
1135 static int sessionStat1Depth(void *pCtx){
1136   SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
1137   return p->hook.xDepth(p->hook.pCtx);
1138 }
1139 
1140 
1141 /*
1142 ** This function is only called from with a pre-update-hook reporting a
1143 ** change on table pTab (attached to session pSession). The type of change
1144 ** (UPDATE, INSERT, DELETE) is specified by the first argument.
1145 **
1146 ** Unless one is already present or an error occurs, an entry is added
1147 ** to the changed-rows hash table associated with table pTab.
1148 */
1149 static void sessionPreupdateOneChange(
1150   int op,                         /* One of SQLITE_UPDATE, INSERT, DELETE */
1151   sqlite3_session *pSession,      /* Session object pTab is attached to */
1152   SessionTable *pTab              /* Table that change applies to */
1153 ){
1154   int iHash;
1155   int bNull = 0;
1156   int rc = SQLITE_OK;
1157   SessionStat1Ctx stat1 = {{0,0,0,0,0},0};
1158 
1159   if( pSession->rc ) return;
1160 
1161   /* Load table details if required */
1162   if( sessionInitTable(pSession, pTab) ) return;
1163 
1164   /* Check the number of columns in this xPreUpdate call matches the
1165   ** number of columns in the table.  */
1166   if( pTab->nCol!=pSession->hook.xCount(pSession->hook.pCtx) ){
1167     pSession->rc = SQLITE_SCHEMA;
1168     return;
1169   }
1170 
1171   /* Grow the hash table if required */
1172   if( sessionGrowHash(0, pTab) ){
1173     pSession->rc = SQLITE_NOMEM;
1174     return;
1175   }
1176 
1177   if( pTab->bStat1 ){
1178     stat1.hook = pSession->hook;
1179     stat1.pSession = pSession;
1180     pSession->hook.pCtx = (void*)&stat1;
1181     pSession->hook.xNew = sessionStat1New;
1182     pSession->hook.xOld = sessionStat1Old;
1183     pSession->hook.xCount = sessionStat1Count;
1184     pSession->hook.xDepth = sessionStat1Depth;
1185     if( pSession->pZeroBlob==0 ){
1186       sqlite3_value *p = sqlite3ValueNew(0);
1187       if( p==0 ){
1188         rc = SQLITE_NOMEM;
1189         goto error_out;
1190       }
1191       sqlite3ValueSetStr(p, 0, "", 0, SQLITE_STATIC);
1192       pSession->pZeroBlob = p;
1193     }
1194   }
1195 
1196   /* Calculate the hash-key for this change. If the primary key of the row
1197   ** includes a NULL value, exit early. Such changes are ignored by the
1198   ** session module. */
1199   rc = sessionPreupdateHash(pSession, pTab, op==SQLITE_INSERT, &iHash, &bNull);
1200   if( rc!=SQLITE_OK ) goto error_out;
1201 
1202   if( bNull==0 ){
1203     /* Search the hash table for an existing record for this row. */
1204     SessionChange *pC;
1205     for(pC=pTab->apChange[iHash]; pC; pC=pC->pNext){
1206       if( sessionPreupdateEqual(pSession, pTab, pC, op) ) break;
1207     }
1208 
1209     if( pC==0 ){
1210       /* Create a new change object containing all the old values (if
1211       ** this is an SQLITE_UPDATE or SQLITE_DELETE), or just the PK
1212       ** values (if this is an INSERT). */
1213       SessionChange *pChange; /* New change object */
1214       int nByte;              /* Number of bytes to allocate */
1215       int i;                  /* Used to iterate through columns */
1216 
1217       assert( rc==SQLITE_OK );
1218       pTab->nEntry++;
1219 
1220       /* Figure out how large an allocation is required */
1221       nByte = sizeof(SessionChange);
1222       for(i=0; i<pTab->nCol; i++){
1223         sqlite3_value *p = 0;
1224         if( op!=SQLITE_INSERT ){
1225           TESTONLY(int trc = ) pSession->hook.xOld(pSession->hook.pCtx, i, &p);
1226           assert( trc==SQLITE_OK );
1227         }else if( pTab->abPK[i] ){
1228           TESTONLY(int trc = ) pSession->hook.xNew(pSession->hook.pCtx, i, &p);
1229           assert( trc==SQLITE_OK );
1230         }
1231 
1232         /* This may fail if SQLite value p contains a utf-16 string that must
1233         ** be converted to utf-8 and an OOM error occurs while doing so. */
1234         rc = sessionSerializeValue(0, p, &nByte);
1235         if( rc!=SQLITE_OK ) goto error_out;
1236       }
1237 
1238       /* Allocate the change object */
1239       pChange = (SessionChange *)sqlite3_malloc(nByte);
1240       if( !pChange ){
1241         rc = SQLITE_NOMEM;
1242         goto error_out;
1243       }else{
1244         memset(pChange, 0, sizeof(SessionChange));
1245         pChange->aRecord = (u8 *)&pChange[1];
1246       }
1247 
1248       /* Populate the change object. None of the preupdate_old(),
1249       ** preupdate_new() or SerializeValue() calls below may fail as all
1250       ** required values and encodings have already been cached in memory.
1251       ** It is not possible for an OOM to occur in this block. */
1252       nByte = 0;
1253       for(i=0; i<pTab->nCol; i++){
1254         sqlite3_value *p = 0;
1255         if( op!=SQLITE_INSERT ){
1256           pSession->hook.xOld(pSession->hook.pCtx, i, &p);
1257         }else if( pTab->abPK[i] ){
1258           pSession->hook.xNew(pSession->hook.pCtx, i, &p);
1259         }
1260         sessionSerializeValue(&pChange->aRecord[nByte], p, &nByte);
1261       }
1262 
1263       /* Add the change to the hash-table */
1264       if( pSession->bIndirect || pSession->hook.xDepth(pSession->hook.pCtx) ){
1265         pChange->bIndirect = 1;
1266       }
1267       pChange->nRecord = nByte;
1268       pChange->op = op;
1269       pChange->pNext = pTab->apChange[iHash];
1270       pTab->apChange[iHash] = pChange;
1271 
1272     }else if( pC->bIndirect ){
1273       /* If the existing change is considered "indirect", but this current
1274       ** change is "direct", mark the change object as direct. */
1275       if( pSession->hook.xDepth(pSession->hook.pCtx)==0
1276        && pSession->bIndirect==0
1277       ){
1278         pC->bIndirect = 0;
1279       }
1280     }
1281   }
1282 
1283   /* If an error has occurred, mark the session object as failed. */
1284  error_out:
1285   if( pTab->bStat1 ){
1286     pSession->hook = stat1.hook;
1287   }
1288   if( rc!=SQLITE_OK ){
1289     pSession->rc = rc;
1290   }
1291 }
1292 
1293 static int sessionFindTable(
1294   sqlite3_session *pSession,
1295   const char *zName,
1296   SessionTable **ppTab
1297 ){
1298   int rc = SQLITE_OK;
1299   int nName = sqlite3Strlen30(zName);
1300   SessionTable *pRet;
1301 
1302   /* Search for an existing table */
1303   for(pRet=pSession->pTable; pRet; pRet=pRet->pNext){
1304     if( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) ) break;
1305   }
1306 
1307   if( pRet==0 && pSession->bAutoAttach ){
1308     /* If there is a table-filter configured, invoke it. If it returns 0,
1309     ** do not automatically add the new table. */
1310     if( pSession->xTableFilter==0
1311      || pSession->xTableFilter(pSession->pFilterCtx, zName)
1312     ){
1313       rc = sqlite3session_attach(pSession, zName);
1314       if( rc==SQLITE_OK ){
1315         for(pRet=pSession->pTable; pRet->pNext; pRet=pRet->pNext);
1316         assert( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) );
1317       }
1318     }
1319   }
1320 
1321   assert( rc==SQLITE_OK || pRet==0 );
1322   *ppTab = pRet;
1323   return rc;
1324 }
1325 
1326 /*
1327 ** The 'pre-update' hook registered by this module with SQLite databases.
1328 */
1329 static void xPreUpdate(
1330   void *pCtx,                     /* Copy of third arg to preupdate_hook() */
1331   sqlite3 *db,                    /* Database handle */
1332   int op,                         /* SQLITE_UPDATE, DELETE or INSERT */
1333   char const *zDb,                /* Database name */
1334   char const *zName,              /* Table name */
1335   sqlite3_int64 iKey1,            /* Rowid of row about to be deleted/updated */
1336   sqlite3_int64 iKey2             /* New rowid value (for a rowid UPDATE) */
1337 ){
1338   sqlite3_session *pSession;
1339   int nDb = sqlite3Strlen30(zDb);
1340 
1341   assert( sqlite3_mutex_held(db->mutex) );
1342 
1343   for(pSession=(sqlite3_session *)pCtx; pSession; pSession=pSession->pNext){
1344     SessionTable *pTab;
1345 
1346     /* If this session is attached to a different database ("main", "temp"
1347     ** etc.), or if it is not currently enabled, there is nothing to do. Skip
1348     ** to the next session object attached to this database. */
1349     if( pSession->bEnable==0 ) continue;
1350     if( pSession->rc ) continue;
1351     if( sqlite3_strnicmp(zDb, pSession->zDb, nDb+1) ) continue;
1352 
1353     pSession->rc = sessionFindTable(pSession, zName, &pTab);
1354     if( pTab ){
1355       assert( pSession->rc==SQLITE_OK );
1356       sessionPreupdateOneChange(op, pSession, pTab);
1357       if( op==SQLITE_UPDATE ){
1358         sessionPreupdateOneChange(SQLITE_INSERT, pSession, pTab);
1359       }
1360     }
1361   }
1362 }
1363 
1364 /*
1365 ** The pre-update hook implementations.
1366 */
1367 static int sessionPreupdateOld(void *pCtx, int iVal, sqlite3_value **ppVal){
1368   return sqlite3_preupdate_old((sqlite3*)pCtx, iVal, ppVal);
1369 }
1370 static int sessionPreupdateNew(void *pCtx, int iVal, sqlite3_value **ppVal){
1371   return sqlite3_preupdate_new((sqlite3*)pCtx, iVal, ppVal);
1372 }
1373 static int sessionPreupdateCount(void *pCtx){
1374   return sqlite3_preupdate_count((sqlite3*)pCtx);
1375 }
1376 static int sessionPreupdateDepth(void *pCtx){
1377   return sqlite3_preupdate_depth((sqlite3*)pCtx);
1378 }
1379 
1380 /*
1381 ** Install the pre-update hooks on the session object passed as the only
1382 ** argument.
1383 */
1384 static void sessionPreupdateHooks(
1385   sqlite3_session *pSession
1386 ){
1387   pSession->hook.pCtx = (void*)pSession->db;
1388   pSession->hook.xOld = sessionPreupdateOld;
1389   pSession->hook.xNew = sessionPreupdateNew;
1390   pSession->hook.xCount = sessionPreupdateCount;
1391   pSession->hook.xDepth = sessionPreupdateDepth;
1392 }
1393 
1394 typedef struct SessionDiffCtx SessionDiffCtx;
1395 struct SessionDiffCtx {
1396   sqlite3_stmt *pStmt;
1397   int nOldOff;
1398 };
1399 
1400 /*
1401 ** The diff hook implementations.
1402 */
1403 static int sessionDiffOld(void *pCtx, int iVal, sqlite3_value **ppVal){
1404   SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
1405   *ppVal = sqlite3_column_value(p->pStmt, iVal+p->nOldOff);
1406   return SQLITE_OK;
1407 }
1408 static int sessionDiffNew(void *pCtx, int iVal, sqlite3_value **ppVal){
1409   SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
1410   *ppVal = sqlite3_column_value(p->pStmt, iVal);
1411    return SQLITE_OK;
1412 }
1413 static int sessionDiffCount(void *pCtx){
1414   SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
1415   return p->nOldOff ? p->nOldOff : sqlite3_column_count(p->pStmt);
1416 }
1417 static int sessionDiffDepth(void *pCtx){
1418   return 0;
1419 }
1420 
1421 /*
1422 ** Install the diff hooks on the session object passed as the only
1423 ** argument.
1424 */
1425 static void sessionDiffHooks(
1426   sqlite3_session *pSession,
1427   SessionDiffCtx *pDiffCtx
1428 ){
1429   pSession->hook.pCtx = (void*)pDiffCtx;
1430   pSession->hook.xOld = sessionDiffOld;
1431   pSession->hook.xNew = sessionDiffNew;
1432   pSession->hook.xCount = sessionDiffCount;
1433   pSession->hook.xDepth = sessionDiffDepth;
1434 }
1435 
1436 static char *sessionExprComparePK(
1437   int nCol,
1438   const char *zDb1, const char *zDb2,
1439   const char *zTab,
1440   const char **azCol, u8 *abPK
1441 ){
1442   int i;
1443   const char *zSep = "";
1444   char *zRet = 0;
1445 
1446   for(i=0; i<nCol; i++){
1447     if( abPK[i] ){
1448       zRet = sqlite3_mprintf("%z%s\"%w\".\"%w\".\"%w\"=\"%w\".\"%w\".\"%w\"",
1449           zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
1450       );
1451       zSep = " AND ";
1452       if( zRet==0 ) break;
1453     }
1454   }
1455 
1456   return zRet;
1457 }
1458 
1459 static char *sessionExprCompareOther(
1460   int nCol,
1461   const char *zDb1, const char *zDb2,
1462   const char *zTab,
1463   const char **azCol, u8 *abPK
1464 ){
1465   int i;
1466   const char *zSep = "";
1467   char *zRet = 0;
1468   int bHave = 0;
1469 
1470   for(i=0; i<nCol; i++){
1471     if( abPK[i]==0 ){
1472       bHave = 1;
1473       zRet = sqlite3_mprintf(
1474           "%z%s\"%w\".\"%w\".\"%w\" IS NOT \"%w\".\"%w\".\"%w\"",
1475           zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
1476       );
1477       zSep = " OR ";
1478       if( zRet==0 ) break;
1479     }
1480   }
1481 
1482   if( bHave==0 ){
1483     assert( zRet==0 );
1484     zRet = sqlite3_mprintf("0");
1485   }
1486 
1487   return zRet;
1488 }
1489 
1490 static char *sessionSelectFindNew(
1491   int nCol,
1492   const char *zDb1,      /* Pick rows in this db only */
1493   const char *zDb2,      /* But not in this one */
1494   const char *zTbl,      /* Table name */
1495   const char *zExpr
1496 ){
1497   char *zRet = sqlite3_mprintf(
1498       "SELECT * FROM \"%w\".\"%w\" WHERE NOT EXISTS ("
1499       "  SELECT 1 FROM \"%w\".\"%w\" WHERE %s"
1500       ")",
1501       zDb1, zTbl, zDb2, zTbl, zExpr
1502   );
1503   return zRet;
1504 }
1505 
1506 static int sessionDiffFindNew(
1507   int op,
1508   sqlite3_session *pSession,
1509   SessionTable *pTab,
1510   const char *zDb1,
1511   const char *zDb2,
1512   char *zExpr
1513 ){
1514   int rc = SQLITE_OK;
1515   char *zStmt = sessionSelectFindNew(pTab->nCol, zDb1, zDb2, pTab->zName,zExpr);
1516 
1517   if( zStmt==0 ){
1518     rc = SQLITE_NOMEM;
1519   }else{
1520     sqlite3_stmt *pStmt;
1521     rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
1522     if( rc==SQLITE_OK ){
1523       SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
1524       pDiffCtx->pStmt = pStmt;
1525       pDiffCtx->nOldOff = 0;
1526       while( SQLITE_ROW==sqlite3_step(pStmt) ){
1527         sessionPreupdateOneChange(op, pSession, pTab);
1528       }
1529       rc = sqlite3_finalize(pStmt);
1530     }
1531     sqlite3_free(zStmt);
1532   }
1533 
1534   return rc;
1535 }
1536 
1537 static int sessionDiffFindModified(
1538   sqlite3_session *pSession,
1539   SessionTable *pTab,
1540   const char *zFrom,
1541   const char *zExpr
1542 ){
1543   int rc = SQLITE_OK;
1544 
1545   char *zExpr2 = sessionExprCompareOther(pTab->nCol,
1546       pSession->zDb, zFrom, pTab->zName, pTab->azCol, pTab->abPK
1547   );
1548   if( zExpr2==0 ){
1549     rc = SQLITE_NOMEM;
1550   }else{
1551     char *zStmt = sqlite3_mprintf(
1552         "SELECT * FROM \"%w\".\"%w\", \"%w\".\"%w\" WHERE %s AND (%z)",
1553         pSession->zDb, pTab->zName, zFrom, pTab->zName, zExpr, zExpr2
1554     );
1555     if( zStmt==0 ){
1556       rc = SQLITE_NOMEM;
1557     }else{
1558       sqlite3_stmt *pStmt;
1559       rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
1560 
1561       if( rc==SQLITE_OK ){
1562         SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
1563         pDiffCtx->pStmt = pStmt;
1564         pDiffCtx->nOldOff = pTab->nCol;
1565         while( SQLITE_ROW==sqlite3_step(pStmt) ){
1566           sessionPreupdateOneChange(SQLITE_UPDATE, pSession, pTab);
1567         }
1568         rc = sqlite3_finalize(pStmt);
1569       }
1570       sqlite3_free(zStmt);
1571     }
1572   }
1573 
1574   return rc;
1575 }
1576 
1577 int sqlite3session_diff(
1578   sqlite3_session *pSession,
1579   const char *zFrom,
1580   const char *zTbl,
1581   char **pzErrMsg
1582 ){
1583   const char *zDb = pSession->zDb;
1584   int rc = pSession->rc;
1585   SessionDiffCtx d;
1586 
1587   memset(&d, 0, sizeof(d));
1588   sessionDiffHooks(pSession, &d);
1589 
1590   sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
1591   if( pzErrMsg ) *pzErrMsg = 0;
1592   if( rc==SQLITE_OK ){
1593     char *zExpr = 0;
1594     sqlite3 *db = pSession->db;
1595     SessionTable *pTo;            /* Table zTbl */
1596 
1597     /* Locate and if necessary initialize the target table object */
1598     rc = sessionFindTable(pSession, zTbl, &pTo);
1599     if( pTo==0 ) goto diff_out;
1600     if( sessionInitTable(pSession, pTo) ){
1601       rc = pSession->rc;
1602       goto diff_out;
1603     }
1604 
1605     /* Check the table schemas match */
1606     if( rc==SQLITE_OK ){
1607       int bHasPk = 0;
1608       int bMismatch = 0;
1609       int nCol;                   /* Columns in zFrom.zTbl */
1610       u8 *abPK;
1611       const char **azCol = 0;
1612       rc = sessionTableInfo(db, zFrom, zTbl, &nCol, 0, &azCol, &abPK);
1613       if( rc==SQLITE_OK ){
1614         if( pTo->nCol!=nCol ){
1615           bMismatch = 1;
1616         }else{
1617           int i;
1618           for(i=0; i<nCol; i++){
1619             if( pTo->abPK[i]!=abPK[i] ) bMismatch = 1;
1620             if( sqlite3_stricmp(azCol[i], pTo->azCol[i]) ) bMismatch = 1;
1621             if( abPK[i] ) bHasPk = 1;
1622           }
1623         }
1624       }
1625       sqlite3_free((char*)azCol);
1626       if( bMismatch ){
1627         *pzErrMsg = sqlite3_mprintf("table schemas do not match");
1628         rc = SQLITE_SCHEMA;
1629       }
1630       if( bHasPk==0 ){
1631         /* Ignore tables with no primary keys */
1632         goto diff_out;
1633       }
1634     }
1635 
1636     if( rc==SQLITE_OK ){
1637       zExpr = sessionExprComparePK(pTo->nCol,
1638           zDb, zFrom, pTo->zName, pTo->azCol, pTo->abPK
1639       );
1640     }
1641 
1642     /* Find new rows */
1643     if( rc==SQLITE_OK ){
1644       rc = sessionDiffFindNew(SQLITE_INSERT, pSession, pTo, zDb, zFrom, zExpr);
1645     }
1646 
1647     /* Find old rows */
1648     if( rc==SQLITE_OK ){
1649       rc = sessionDiffFindNew(SQLITE_DELETE, pSession, pTo, zFrom, zDb, zExpr);
1650     }
1651 
1652     /* Find modified rows */
1653     if( rc==SQLITE_OK ){
1654       rc = sessionDiffFindModified(pSession, pTo, zFrom, zExpr);
1655     }
1656 
1657     sqlite3_free(zExpr);
1658   }
1659 
1660  diff_out:
1661   sessionPreupdateHooks(pSession);
1662   sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
1663   return rc;
1664 }
1665 
1666 /*
1667 ** Create a session object. This session object will record changes to
1668 ** database zDb attached to connection db.
1669 */
1670 int sqlite3session_create(
1671   sqlite3 *db,                    /* Database handle */
1672   const char *zDb,                /* Name of db (e.g. "main") */
1673   sqlite3_session **ppSession     /* OUT: New session object */
1674 ){
1675   sqlite3_session *pNew;          /* Newly allocated session object */
1676   sqlite3_session *pOld;          /* Session object already attached to db */
1677   int nDb = sqlite3Strlen30(zDb); /* Length of zDb in bytes */
1678 
1679   /* Zero the output value in case an error occurs. */
1680   *ppSession = 0;
1681 
1682   /* Allocate and populate the new session object. */
1683   pNew = (sqlite3_session *)sqlite3_malloc(sizeof(sqlite3_session) + nDb + 1);
1684   if( !pNew ) return SQLITE_NOMEM;
1685   memset(pNew, 0, sizeof(sqlite3_session));
1686   pNew->db = db;
1687   pNew->zDb = (char *)&pNew[1];
1688   pNew->bEnable = 1;
1689   memcpy(pNew->zDb, zDb, nDb+1);
1690   sessionPreupdateHooks(pNew);
1691 
1692   /* Add the new session object to the linked list of session objects
1693   ** attached to database handle $db. Do this under the cover of the db
1694   ** handle mutex.  */
1695   sqlite3_mutex_enter(sqlite3_db_mutex(db));
1696   pOld = (sqlite3_session*)sqlite3_preupdate_hook(db, xPreUpdate, (void*)pNew);
1697   pNew->pNext = pOld;
1698   sqlite3_mutex_leave(sqlite3_db_mutex(db));
1699 
1700   *ppSession = pNew;
1701   return SQLITE_OK;
1702 }
1703 
1704 /*
1705 ** Free the list of table objects passed as the first argument. The contents
1706 ** of the changed-rows hash tables are also deleted.
1707 */
1708 static void sessionDeleteTable(SessionTable *pList){
1709   SessionTable *pNext;
1710   SessionTable *pTab;
1711 
1712   for(pTab=pList; pTab; pTab=pNext){
1713     int i;
1714     pNext = pTab->pNext;
1715     for(i=0; i<pTab->nChange; i++){
1716       SessionChange *p;
1717       SessionChange *pNextChange;
1718       for(p=pTab->apChange[i]; p; p=pNextChange){
1719         pNextChange = p->pNext;
1720         sqlite3_free(p);
1721       }
1722     }
1723     sqlite3_free((char*)pTab->azCol);  /* cast works around VC++ bug */
1724     sqlite3_free(pTab->apChange);
1725     sqlite3_free(pTab);
1726   }
1727 }
1728 
1729 /*
1730 ** Delete a session object previously allocated using sqlite3session_create().
1731 */
1732 void sqlite3session_delete(sqlite3_session *pSession){
1733   sqlite3 *db = pSession->db;
1734   sqlite3_session *pHead;
1735   sqlite3_session **pp;
1736 
1737   /* Unlink the session from the linked list of sessions attached to the
1738   ** database handle. Hold the db mutex while doing so.  */
1739   sqlite3_mutex_enter(sqlite3_db_mutex(db));
1740   pHead = (sqlite3_session*)sqlite3_preupdate_hook(db, 0, 0);
1741   for(pp=&pHead; ALWAYS((*pp)!=0); pp=&((*pp)->pNext)){
1742     if( (*pp)==pSession ){
1743       *pp = (*pp)->pNext;
1744       if( pHead ) sqlite3_preupdate_hook(db, xPreUpdate, (void*)pHead);
1745       break;
1746     }
1747   }
1748   sqlite3_mutex_leave(sqlite3_db_mutex(db));
1749   sqlite3ValueFree(pSession->pZeroBlob);
1750 
1751   /* Delete all attached table objects. And the contents of their
1752   ** associated hash-tables. */
1753   sessionDeleteTable(pSession->pTable);
1754 
1755   /* Free the session object itself. */
1756   sqlite3_free(pSession);
1757 }
1758 
1759 /*
1760 ** Set a table filter on a Session Object.
1761 */
1762 void sqlite3session_table_filter(
1763   sqlite3_session *pSession,
1764   int(*xFilter)(void*, const char*),
1765   void *pCtx                      /* First argument passed to xFilter */
1766 ){
1767   pSession->bAutoAttach = 1;
1768   pSession->pFilterCtx = pCtx;
1769   pSession->xTableFilter = xFilter;
1770 }
1771 
1772 /*
1773 ** Attach a table to a session. All subsequent changes made to the table
1774 ** while the session object is enabled will be recorded.
1775 **
1776 ** Only tables that have a PRIMARY KEY defined may be attached. It does
1777 ** not matter if the PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias)
1778 ** or not.
1779 */
1780 int sqlite3session_attach(
1781   sqlite3_session *pSession,      /* Session object */
1782   const char *zName               /* Table name */
1783 ){
1784   int rc = SQLITE_OK;
1785   sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
1786 
1787   if( !zName ){
1788     pSession->bAutoAttach = 1;
1789   }else{
1790     SessionTable *pTab;           /* New table object (if required) */
1791     int nName;                    /* Number of bytes in string zName */
1792 
1793     /* First search for an existing entry. If one is found, this call is
1794     ** a no-op. Return early. */
1795     nName = sqlite3Strlen30(zName);
1796     for(pTab=pSession->pTable; pTab; pTab=pTab->pNext){
1797       if( 0==sqlite3_strnicmp(pTab->zName, zName, nName+1) ) break;
1798     }
1799 
1800     if( !pTab ){
1801       /* Allocate new SessionTable object. */
1802       pTab = (SessionTable *)sqlite3_malloc(sizeof(SessionTable) + nName + 1);
1803       if( !pTab ){
1804         rc = SQLITE_NOMEM;
1805       }else{
1806         /* Populate the new SessionTable object and link it into the list.
1807         ** The new object must be linked onto the end of the list, not
1808         ** simply added to the start of it in order to ensure that tables
1809         ** appear in the correct order when a changeset or patchset is
1810         ** eventually generated. */
1811         SessionTable **ppTab;
1812         memset(pTab, 0, sizeof(SessionTable));
1813         pTab->zName = (char *)&pTab[1];
1814         memcpy(pTab->zName, zName, nName+1);
1815         for(ppTab=&pSession->pTable; *ppTab; ppTab=&(*ppTab)->pNext);
1816         *ppTab = pTab;
1817       }
1818     }
1819   }
1820 
1821   sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
1822   return rc;
1823 }
1824 
1825 /*
1826 ** Ensure that there is room in the buffer to append nByte bytes of data.
1827 ** If not, use sqlite3_realloc() to grow the buffer so that there is.
1828 **
1829 ** If successful, return zero. Otherwise, if an OOM condition is encountered,
1830 ** set *pRc to SQLITE_NOMEM and return non-zero.
1831 */
1832 static int sessionBufferGrow(SessionBuffer *p, int nByte, int *pRc){
1833   if( *pRc==SQLITE_OK && p->nAlloc-p->nBuf<nByte ){
1834     u8 *aNew;
1835     i64 nNew = p->nAlloc ? p->nAlloc : 128;
1836     do {
1837       nNew = nNew*2;
1838     }while( (nNew-p->nBuf)<nByte );
1839 
1840     aNew = (u8 *)sqlite3_realloc64(p->aBuf, nNew);
1841     if( 0==aNew ){
1842       *pRc = SQLITE_NOMEM;
1843     }else{
1844       p->aBuf = aNew;
1845       p->nAlloc = nNew;
1846     }
1847   }
1848   return (*pRc!=SQLITE_OK);
1849 }
1850 
1851 /*
1852 ** Append the value passed as the second argument to the buffer passed
1853 ** as the first.
1854 **
1855 ** This function is a no-op if *pRc is non-zero when it is called.
1856 ** Otherwise, if an error occurs, *pRc is set to an SQLite error code
1857 ** before returning.
1858 */
1859 static void sessionAppendValue(SessionBuffer *p, sqlite3_value *pVal, int *pRc){
1860   int rc = *pRc;
1861   if( rc==SQLITE_OK ){
1862     int nByte = 0;
1863     rc = sessionSerializeValue(0, pVal, &nByte);
1864     sessionBufferGrow(p, nByte, &rc);
1865     if( rc==SQLITE_OK ){
1866       rc = sessionSerializeValue(&p->aBuf[p->nBuf], pVal, 0);
1867       p->nBuf += nByte;
1868     }else{
1869       *pRc = rc;
1870     }
1871   }
1872 }
1873 
1874 /*
1875 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
1876 ** called. Otherwise, append a single byte to the buffer.
1877 **
1878 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
1879 ** returning.
1880 */
1881 static void sessionAppendByte(SessionBuffer *p, u8 v, int *pRc){
1882   if( 0==sessionBufferGrow(p, 1, pRc) ){
1883     p->aBuf[p->nBuf++] = v;
1884   }
1885 }
1886 
1887 /*
1888 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
1889 ** called. Otherwise, append a single varint to the buffer.
1890 **
1891 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
1892 ** returning.
1893 */
1894 static void sessionAppendVarint(SessionBuffer *p, int v, int *pRc){
1895   if( 0==sessionBufferGrow(p, 9, pRc) ){
1896     p->nBuf += sessionVarintPut(&p->aBuf[p->nBuf], v);
1897   }
1898 }
1899 
1900 /*
1901 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
1902 ** called. Otherwise, append a blob of data to the buffer.
1903 **
1904 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
1905 ** returning.
1906 */
1907 static void sessionAppendBlob(
1908   SessionBuffer *p,
1909   const u8 *aBlob,
1910   int nBlob,
1911   int *pRc
1912 ){
1913   if( nBlob>0 && 0==sessionBufferGrow(p, nBlob, pRc) ){
1914     memcpy(&p->aBuf[p->nBuf], aBlob, nBlob);
1915     p->nBuf += nBlob;
1916   }
1917 }
1918 
1919 /*
1920 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
1921 ** called. Otherwise, append a string to the buffer. All bytes in the string
1922 ** up to (but not including) the nul-terminator are written to the buffer.
1923 **
1924 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
1925 ** returning.
1926 */
1927 static void sessionAppendStr(
1928   SessionBuffer *p,
1929   const char *zStr,
1930   int *pRc
1931 ){
1932   int nStr = sqlite3Strlen30(zStr);
1933   if( 0==sessionBufferGrow(p, nStr, pRc) ){
1934     memcpy(&p->aBuf[p->nBuf], zStr, nStr);
1935     p->nBuf += nStr;
1936   }
1937 }
1938 
1939 /*
1940 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
1941 ** called. Otherwise, append the string representation of integer iVal
1942 ** to the buffer. No nul-terminator is written.
1943 **
1944 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
1945 ** returning.
1946 */
1947 static void sessionAppendInteger(
1948   SessionBuffer *p,               /* Buffer to append to */
1949   int iVal,                       /* Value to write the string rep. of */
1950   int *pRc                        /* IN/OUT: Error code */
1951 ){
1952   char aBuf[24];
1953   sqlite3_snprintf(sizeof(aBuf)-1, aBuf, "%d", iVal);
1954   sessionAppendStr(p, aBuf, pRc);
1955 }
1956 
1957 /*
1958 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
1959 ** called. Otherwise, append the string zStr enclosed in quotes (") and
1960 ** with any embedded quote characters escaped to the buffer. No
1961 ** nul-terminator byte is written.
1962 **
1963 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
1964 ** returning.
1965 */
1966 static void sessionAppendIdent(
1967   SessionBuffer *p,               /* Buffer to a append to */
1968   const char *zStr,               /* String to quote, escape and append */
1969   int *pRc                        /* IN/OUT: Error code */
1970 ){
1971   int nStr = sqlite3Strlen30(zStr)*2 + 2 + 1;
1972   if( 0==sessionBufferGrow(p, nStr, pRc) ){
1973     char *zOut = (char *)&p->aBuf[p->nBuf];
1974     const char *zIn = zStr;
1975     *zOut++ = '"';
1976     while( *zIn ){
1977       if( *zIn=='"' ) *zOut++ = '"';
1978       *zOut++ = *(zIn++);
1979     }
1980     *zOut++ = '"';
1981     p->nBuf = (int)((u8 *)zOut - p->aBuf);
1982   }
1983 }
1984 
1985 /*
1986 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
1987 ** called. Otherwse, it appends the serialized version of the value stored
1988 ** in column iCol of the row that SQL statement pStmt currently points
1989 ** to to the buffer.
1990 */
1991 static void sessionAppendCol(
1992   SessionBuffer *p,               /* Buffer to append to */
1993   sqlite3_stmt *pStmt,            /* Handle pointing to row containing value */
1994   int iCol,                       /* Column to read value from */
1995   int *pRc                        /* IN/OUT: Error code */
1996 ){
1997   if( *pRc==SQLITE_OK ){
1998     int eType = sqlite3_column_type(pStmt, iCol);
1999     sessionAppendByte(p, (u8)eType, pRc);
2000     if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
2001       sqlite3_int64 i;
2002       u8 aBuf[8];
2003       if( eType==SQLITE_INTEGER ){
2004         i = sqlite3_column_int64(pStmt, iCol);
2005       }else{
2006         double r = sqlite3_column_double(pStmt, iCol);
2007         memcpy(&i, &r, 8);
2008       }
2009       sessionPutI64(aBuf, i);
2010       sessionAppendBlob(p, aBuf, 8, pRc);
2011     }
2012     if( eType==SQLITE_BLOB || eType==SQLITE_TEXT ){
2013       u8 *z;
2014       int nByte;
2015       if( eType==SQLITE_BLOB ){
2016         z = (u8 *)sqlite3_column_blob(pStmt, iCol);
2017       }else{
2018         z = (u8 *)sqlite3_column_text(pStmt, iCol);
2019       }
2020       nByte = sqlite3_column_bytes(pStmt, iCol);
2021       if( z || (eType==SQLITE_BLOB && nByte==0) ){
2022         sessionAppendVarint(p, nByte, pRc);
2023         sessionAppendBlob(p, z, nByte, pRc);
2024       }else{
2025         *pRc = SQLITE_NOMEM;
2026       }
2027     }
2028   }
2029 }
2030 
2031 /*
2032 **
2033 ** This function appends an update change to the buffer (see the comments
2034 ** under "CHANGESET FORMAT" at the top of the file). An update change
2035 ** consists of:
2036 **
2037 **   1 byte:  SQLITE_UPDATE (0x17)
2038 **   n bytes: old.* record (see RECORD FORMAT)
2039 **   m bytes: new.* record (see RECORD FORMAT)
2040 **
2041 ** The SessionChange object passed as the third argument contains the
2042 ** values that were stored in the row when the session began (the old.*
2043 ** values). The statement handle passed as the second argument points
2044 ** at the current version of the row (the new.* values).
2045 **
2046 ** If all of the old.* values are equal to their corresponding new.* value
2047 ** (i.e. nothing has changed), then no data at all is appended to the buffer.
2048 **
2049 ** Otherwise, the old.* record contains all primary key values and the
2050 ** original values of any fields that have been modified. The new.* record
2051 ** contains the new values of only those fields that have been modified.
2052 */
2053 static int sessionAppendUpdate(
2054   SessionBuffer *pBuf,            /* Buffer to append to */
2055   int bPatchset,                  /* True for "patchset", 0 for "changeset" */
2056   sqlite3_stmt *pStmt,            /* Statement handle pointing at new row */
2057   SessionChange *p,               /* Object containing old values */
2058   u8 *abPK                        /* Boolean array - true for PK columns */
2059 ){
2060   int rc = SQLITE_OK;
2061   SessionBuffer buf2 = {0,0,0}; /* Buffer to accumulate new.* record in */
2062   int bNoop = 1;                /* Set to zero if any values are modified */
2063   int nRewind = pBuf->nBuf;     /* Set to zero if any values are modified */
2064   int i;                        /* Used to iterate through columns */
2065   u8 *pCsr = p->aRecord;        /* Used to iterate through old.* values */
2066 
2067   sessionAppendByte(pBuf, SQLITE_UPDATE, &rc);
2068   sessionAppendByte(pBuf, p->bIndirect, &rc);
2069   for(i=0; i<sqlite3_column_count(pStmt); i++){
2070     int bChanged = 0;
2071     int nAdvance;
2072     int eType = *pCsr;
2073     switch( eType ){
2074       case SQLITE_NULL:
2075         nAdvance = 1;
2076         if( sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
2077           bChanged = 1;
2078         }
2079         break;
2080 
2081       case SQLITE_FLOAT:
2082       case SQLITE_INTEGER: {
2083         nAdvance = 9;
2084         if( eType==sqlite3_column_type(pStmt, i) ){
2085           sqlite3_int64 iVal = sessionGetI64(&pCsr[1]);
2086           if( eType==SQLITE_INTEGER ){
2087             if( iVal==sqlite3_column_int64(pStmt, i) ) break;
2088           }else{
2089             double dVal;
2090             memcpy(&dVal, &iVal, 8);
2091             if( dVal==sqlite3_column_double(pStmt, i) ) break;
2092           }
2093         }
2094         bChanged = 1;
2095         break;
2096       }
2097 
2098       default: {
2099         int n;
2100         int nHdr = 1 + sessionVarintGet(&pCsr[1], &n);
2101         assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
2102         nAdvance = nHdr + n;
2103         if( eType==sqlite3_column_type(pStmt, i)
2104          && n==sqlite3_column_bytes(pStmt, i)
2105          && (n==0 || 0==memcmp(&pCsr[nHdr], sqlite3_column_blob(pStmt, i), n))
2106         ){
2107           break;
2108         }
2109         bChanged = 1;
2110       }
2111     }
2112 
2113     /* If at least one field has been modified, this is not a no-op. */
2114     if( bChanged ) bNoop = 0;
2115 
2116     /* Add a field to the old.* record. This is omitted if this modules is
2117     ** currently generating a patchset. */
2118     if( bPatchset==0 ){
2119       if( bChanged || abPK[i] ){
2120         sessionAppendBlob(pBuf, pCsr, nAdvance, &rc);
2121       }else{
2122         sessionAppendByte(pBuf, 0, &rc);
2123       }
2124     }
2125 
2126     /* Add a field to the new.* record. Or the only record if currently
2127     ** generating a patchset.  */
2128     if( bChanged || (bPatchset && abPK[i]) ){
2129       sessionAppendCol(&buf2, pStmt, i, &rc);
2130     }else{
2131       sessionAppendByte(&buf2, 0, &rc);
2132     }
2133 
2134     pCsr += nAdvance;
2135   }
2136 
2137   if( bNoop ){
2138     pBuf->nBuf = nRewind;
2139   }else{
2140     sessionAppendBlob(pBuf, buf2.aBuf, buf2.nBuf, &rc);
2141   }
2142   sqlite3_free(buf2.aBuf);
2143 
2144   return rc;
2145 }
2146 
2147 /*
2148 ** Append a DELETE change to the buffer passed as the first argument. Use
2149 ** the changeset format if argument bPatchset is zero, or the patchset
2150 ** format otherwise.
2151 */
2152 static int sessionAppendDelete(
2153   SessionBuffer *pBuf,            /* Buffer to append to */
2154   int bPatchset,                  /* True for "patchset", 0 for "changeset" */
2155   SessionChange *p,               /* Object containing old values */
2156   int nCol,                       /* Number of columns in table */
2157   u8 *abPK                        /* Boolean array - true for PK columns */
2158 ){
2159   int rc = SQLITE_OK;
2160 
2161   sessionAppendByte(pBuf, SQLITE_DELETE, &rc);
2162   sessionAppendByte(pBuf, p->bIndirect, &rc);
2163 
2164   if( bPatchset==0 ){
2165     sessionAppendBlob(pBuf, p->aRecord, p->nRecord, &rc);
2166   }else{
2167     int i;
2168     u8 *a = p->aRecord;
2169     for(i=0; i<nCol; i++){
2170       u8 *pStart = a;
2171       int eType = *a++;
2172 
2173       switch( eType ){
2174         case 0:
2175         case SQLITE_NULL:
2176           assert( abPK[i]==0 );
2177           break;
2178 
2179         case SQLITE_FLOAT:
2180         case SQLITE_INTEGER:
2181           a += 8;
2182           break;
2183 
2184         default: {
2185           int n;
2186           a += sessionVarintGet(a, &n);
2187           a += n;
2188           break;
2189         }
2190       }
2191       if( abPK[i] ){
2192         sessionAppendBlob(pBuf, pStart, (int)(a-pStart), &rc);
2193       }
2194     }
2195     assert( (a - p->aRecord)==p->nRecord );
2196   }
2197 
2198   return rc;
2199 }
2200 
2201 /*
2202 ** Formulate and prepare a SELECT statement to retrieve a row from table
2203 ** zTab in database zDb based on its primary key. i.e.
2204 **
2205 **   SELECT * FROM zDb.zTab WHERE pk1 = ? AND pk2 = ? AND ...
2206 */
2207 static int sessionSelectStmt(
2208   sqlite3 *db,                    /* Database handle */
2209   const char *zDb,                /* Database name */
2210   const char *zTab,               /* Table name */
2211   int nCol,                       /* Number of columns in table */
2212   const char **azCol,             /* Names of table columns */
2213   u8 *abPK,                       /* PRIMARY KEY  array */
2214   sqlite3_stmt **ppStmt           /* OUT: Prepared SELECT statement */
2215 ){
2216   int rc = SQLITE_OK;
2217   char *zSql = 0;
2218   int nSql = -1;
2219 
2220   if( 0==sqlite3_stricmp("sqlite_stat1", zTab) ){
2221     zSql = sqlite3_mprintf(
2222         "SELECT tbl, ?2, stat FROM %Q.sqlite_stat1 WHERE tbl IS ?1 AND "
2223         "idx IS (CASE WHEN ?2=X'' THEN NULL ELSE ?2 END)", zDb
2224     );
2225     if( zSql==0 ) rc = SQLITE_NOMEM;
2226   }else{
2227     int i;
2228     const char *zSep = "";
2229     SessionBuffer buf = {0, 0, 0};
2230 
2231     sessionAppendStr(&buf, "SELECT * FROM ", &rc);
2232     sessionAppendIdent(&buf, zDb, &rc);
2233     sessionAppendStr(&buf, ".", &rc);
2234     sessionAppendIdent(&buf, zTab, &rc);
2235     sessionAppendStr(&buf, " WHERE ", &rc);
2236     for(i=0; i<nCol; i++){
2237       if( abPK[i] ){
2238         sessionAppendStr(&buf, zSep, &rc);
2239         sessionAppendIdent(&buf, azCol[i], &rc);
2240         sessionAppendStr(&buf, " IS ?", &rc);
2241         sessionAppendInteger(&buf, i+1, &rc);
2242         zSep = " AND ";
2243       }
2244     }
2245     zSql = (char*)buf.aBuf;
2246     nSql = buf.nBuf;
2247   }
2248 
2249   if( rc==SQLITE_OK ){
2250     rc = sqlite3_prepare_v2(db, zSql, nSql, ppStmt, 0);
2251   }
2252   sqlite3_free(zSql);
2253   return rc;
2254 }
2255 
2256 /*
2257 ** Bind the PRIMARY KEY values from the change passed in argument pChange
2258 ** to the SELECT statement passed as the first argument. The SELECT statement
2259 ** is as prepared by function sessionSelectStmt().
2260 **
2261 ** Return SQLITE_OK if all PK values are successfully bound, or an SQLite
2262 ** error code (e.g. SQLITE_NOMEM) otherwise.
2263 */
2264 static int sessionSelectBind(
2265   sqlite3_stmt *pSelect,          /* SELECT from sessionSelectStmt() */
2266   int nCol,                       /* Number of columns in table */
2267   u8 *abPK,                       /* PRIMARY KEY array */
2268   SessionChange *pChange          /* Change structure */
2269 ){
2270   int i;
2271   int rc = SQLITE_OK;
2272   u8 *a = pChange->aRecord;
2273 
2274   for(i=0; i<nCol && rc==SQLITE_OK; i++){
2275     int eType = *a++;
2276 
2277     switch( eType ){
2278       case 0:
2279       case SQLITE_NULL:
2280         assert( abPK[i]==0 );
2281         break;
2282 
2283       case SQLITE_INTEGER: {
2284         if( abPK[i] ){
2285           i64 iVal = sessionGetI64(a);
2286           rc = sqlite3_bind_int64(pSelect, i+1, iVal);
2287         }
2288         a += 8;
2289         break;
2290       }
2291 
2292       case SQLITE_FLOAT: {
2293         if( abPK[i] ){
2294           double rVal;
2295           i64 iVal = sessionGetI64(a);
2296           memcpy(&rVal, &iVal, 8);
2297           rc = sqlite3_bind_double(pSelect, i+1, rVal);
2298         }
2299         a += 8;
2300         break;
2301       }
2302 
2303       case SQLITE_TEXT: {
2304         int n;
2305         a += sessionVarintGet(a, &n);
2306         if( abPK[i] ){
2307           rc = sqlite3_bind_text(pSelect, i+1, (char *)a, n, SQLITE_TRANSIENT);
2308         }
2309         a += n;
2310         break;
2311       }
2312 
2313       default: {
2314         int n;
2315         assert( eType==SQLITE_BLOB );
2316         a += sessionVarintGet(a, &n);
2317         if( abPK[i] ){
2318           rc = sqlite3_bind_blob(pSelect, i+1, a, n, SQLITE_TRANSIENT);
2319         }
2320         a += n;
2321         break;
2322       }
2323     }
2324   }
2325 
2326   return rc;
2327 }
2328 
2329 /*
2330 ** This function is a no-op if *pRc is set to other than SQLITE_OK when it
2331 ** is called. Otherwise, append a serialized table header (part of the binary
2332 ** changeset format) to buffer *pBuf. If an error occurs, set *pRc to an
2333 ** SQLite error code before returning.
2334 */
2335 static void sessionAppendTableHdr(
2336   SessionBuffer *pBuf,            /* Append header to this buffer */
2337   int bPatchset,                  /* Use the patchset format if true */
2338   SessionTable *pTab,             /* Table object to append header for */
2339   int *pRc                        /* IN/OUT: Error code */
2340 ){
2341   /* Write a table header */
2342   sessionAppendByte(pBuf, (bPatchset ? 'P' : 'T'), pRc);
2343   sessionAppendVarint(pBuf, pTab->nCol, pRc);
2344   sessionAppendBlob(pBuf, pTab->abPK, pTab->nCol, pRc);
2345   sessionAppendBlob(pBuf, (u8 *)pTab->zName, (int)strlen(pTab->zName)+1, pRc);
2346 }
2347 
2348 /*
2349 ** Generate either a changeset (if argument bPatchset is zero) or a patchset
2350 ** (if it is non-zero) based on the current contents of the session object
2351 ** passed as the first argument.
2352 **
2353 ** If no error occurs, SQLITE_OK is returned and the new changeset/patchset
2354 ** stored in output variables *pnChangeset and *ppChangeset. Or, if an error
2355 ** occurs, an SQLite error code is returned and both output variables set
2356 ** to 0.
2357 */
2358 static int sessionGenerateChangeset(
2359   sqlite3_session *pSession,      /* Session object */
2360   int bPatchset,                  /* True for patchset, false for changeset */
2361   int (*xOutput)(void *pOut, const void *pData, int nData),
2362   void *pOut,                     /* First argument for xOutput */
2363   int *pnChangeset,               /* OUT: Size of buffer at *ppChangeset */
2364   void **ppChangeset              /* OUT: Buffer containing changeset */
2365 ){
2366   sqlite3 *db = pSession->db;     /* Source database handle */
2367   SessionTable *pTab;             /* Used to iterate through attached tables */
2368   SessionBuffer buf = {0,0,0};    /* Buffer in which to accumlate changeset */
2369   int rc;                         /* Return code */
2370 
2371   assert( xOutput==0 || (pnChangeset==0 && ppChangeset==0 ) );
2372 
2373   /* Zero the output variables in case an error occurs. If this session
2374   ** object is already in the error state (sqlite3_session.rc != SQLITE_OK),
2375   ** this call will be a no-op.  */
2376   if( xOutput==0 ){
2377     *pnChangeset = 0;
2378     *ppChangeset = 0;
2379   }
2380 
2381   if( pSession->rc ) return pSession->rc;
2382   rc = sqlite3_exec(pSession->db, "SAVEPOINT changeset", 0, 0, 0);
2383   if( rc!=SQLITE_OK ) return rc;
2384 
2385   sqlite3_mutex_enter(sqlite3_db_mutex(db));
2386 
2387   for(pTab=pSession->pTable; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
2388     if( pTab->nEntry ){
2389       const char *zName = pTab->zName;
2390       int nCol;                   /* Number of columns in table */
2391       u8 *abPK;                   /* Primary key array */
2392       const char **azCol = 0;     /* Table columns */
2393       int i;                      /* Used to iterate through hash buckets */
2394       sqlite3_stmt *pSel = 0;     /* SELECT statement to query table pTab */
2395       int nRewind = buf.nBuf;     /* Initial size of write buffer */
2396       int nNoop;                  /* Size of buffer after writing tbl header */
2397 
2398       /* Check the table schema is still Ok. */
2399       rc = sessionTableInfo(db, pSession->zDb, zName, &nCol, 0, &azCol, &abPK);
2400       if( !rc && (pTab->nCol!=nCol || memcmp(abPK, pTab->abPK, nCol)) ){
2401         rc = SQLITE_SCHEMA;
2402       }
2403 
2404       /* Write a table header */
2405       sessionAppendTableHdr(&buf, bPatchset, pTab, &rc);
2406 
2407       /* Build and compile a statement to execute: */
2408       if( rc==SQLITE_OK ){
2409         rc = sessionSelectStmt(
2410             db, pSession->zDb, zName, nCol, azCol, abPK, &pSel);
2411       }
2412 
2413       nNoop = buf.nBuf;
2414       for(i=0; i<pTab->nChange && rc==SQLITE_OK; i++){
2415         SessionChange *p;         /* Used to iterate through changes */
2416 
2417         for(p=pTab->apChange[i]; rc==SQLITE_OK && p; p=p->pNext){
2418           rc = sessionSelectBind(pSel, nCol, abPK, p);
2419           if( rc!=SQLITE_OK ) continue;
2420           if( sqlite3_step(pSel)==SQLITE_ROW ){
2421             if( p->op==SQLITE_INSERT ){
2422               int iCol;
2423               sessionAppendByte(&buf, SQLITE_INSERT, &rc);
2424               sessionAppendByte(&buf, p->bIndirect, &rc);
2425               for(iCol=0; iCol<nCol; iCol++){
2426                 sessionAppendCol(&buf, pSel, iCol, &rc);
2427               }
2428             }else{
2429               rc = sessionAppendUpdate(&buf, bPatchset, pSel, p, abPK);
2430             }
2431           }else if( p->op!=SQLITE_INSERT ){
2432             rc = sessionAppendDelete(&buf, bPatchset, p, nCol, abPK);
2433           }
2434           if( rc==SQLITE_OK ){
2435             rc = sqlite3_reset(pSel);
2436           }
2437 
2438           /* If the buffer is now larger than sessions_strm_chunk_size, pass
2439           ** its contents to the xOutput() callback. */
2440           if( xOutput
2441            && rc==SQLITE_OK
2442            && buf.nBuf>nNoop
2443            && buf.nBuf>sessions_strm_chunk_size
2444           ){
2445             rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
2446             nNoop = -1;
2447             buf.nBuf = 0;
2448           }
2449 
2450         }
2451       }
2452 
2453       sqlite3_finalize(pSel);
2454       if( buf.nBuf==nNoop ){
2455         buf.nBuf = nRewind;
2456       }
2457       sqlite3_free((char*)azCol);  /* cast works around VC++ bug */
2458     }
2459   }
2460 
2461   if( rc==SQLITE_OK ){
2462     if( xOutput==0 ){
2463       *pnChangeset = buf.nBuf;
2464       *ppChangeset = buf.aBuf;
2465       buf.aBuf = 0;
2466     }else if( buf.nBuf>0 ){
2467       rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
2468     }
2469   }
2470 
2471   sqlite3_free(buf.aBuf);
2472   sqlite3_exec(db, "RELEASE changeset", 0, 0, 0);
2473   sqlite3_mutex_leave(sqlite3_db_mutex(db));
2474   return rc;
2475 }
2476 
2477 /*
2478 ** Obtain a changeset object containing all changes recorded by the
2479 ** session object passed as the first argument.
2480 **
2481 ** It is the responsibility of the caller to eventually free the buffer
2482 ** using sqlite3_free().
2483 */
2484 int sqlite3session_changeset(
2485   sqlite3_session *pSession,      /* Session object */
2486   int *pnChangeset,               /* OUT: Size of buffer at *ppChangeset */
2487   void **ppChangeset              /* OUT: Buffer containing changeset */
2488 ){
2489   return sessionGenerateChangeset(pSession, 0, 0, 0, pnChangeset, ppChangeset);
2490 }
2491 
2492 /*
2493 ** Streaming version of sqlite3session_changeset().
2494 */
2495 int sqlite3session_changeset_strm(
2496   sqlite3_session *pSession,
2497   int (*xOutput)(void *pOut, const void *pData, int nData),
2498   void *pOut
2499 ){
2500   return sessionGenerateChangeset(pSession, 0, xOutput, pOut, 0, 0);
2501 }
2502 
2503 /*
2504 ** Streaming version of sqlite3session_patchset().
2505 */
2506 int sqlite3session_patchset_strm(
2507   sqlite3_session *pSession,
2508   int (*xOutput)(void *pOut, const void *pData, int nData),
2509   void *pOut
2510 ){
2511   return sessionGenerateChangeset(pSession, 1, xOutput, pOut, 0, 0);
2512 }
2513 
2514 /*
2515 ** Obtain a patchset object containing all changes recorded by the
2516 ** session object passed as the first argument.
2517 **
2518 ** It is the responsibility of the caller to eventually free the buffer
2519 ** using sqlite3_free().
2520 */
2521 int sqlite3session_patchset(
2522   sqlite3_session *pSession,      /* Session object */
2523   int *pnPatchset,                /* OUT: Size of buffer at *ppChangeset */
2524   void **ppPatchset               /* OUT: Buffer containing changeset */
2525 ){
2526   return sessionGenerateChangeset(pSession, 1, 0, 0, pnPatchset, ppPatchset);
2527 }
2528 
2529 /*
2530 ** Enable or disable the session object passed as the first argument.
2531 */
2532 int sqlite3session_enable(sqlite3_session *pSession, int bEnable){
2533   int ret;
2534   sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
2535   if( bEnable>=0 ){
2536     pSession->bEnable = bEnable;
2537   }
2538   ret = pSession->bEnable;
2539   sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
2540   return ret;
2541 }
2542 
2543 /*
2544 ** Enable or disable the session object passed as the first argument.
2545 */
2546 int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect){
2547   int ret;
2548   sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
2549   if( bIndirect>=0 ){
2550     pSession->bIndirect = bIndirect;
2551   }
2552   ret = pSession->bIndirect;
2553   sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
2554   return ret;
2555 }
2556 
2557 /*
2558 ** Return true if there have been no changes to monitored tables recorded
2559 ** by the session object passed as the only argument.
2560 */
2561 int sqlite3session_isempty(sqlite3_session *pSession){
2562   int ret = 0;
2563   SessionTable *pTab;
2564 
2565   sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
2566   for(pTab=pSession->pTable; pTab && ret==0; pTab=pTab->pNext){
2567     ret = (pTab->nEntry>0);
2568   }
2569   sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
2570 
2571   return (ret==0);
2572 }
2573 
2574 /*
2575 ** Do the work for either sqlite3changeset_start() or start_strm().
2576 */
2577 static int sessionChangesetStart(
2578   sqlite3_changeset_iter **pp,    /* OUT: Changeset iterator handle */
2579   int (*xInput)(void *pIn, void *pData, int *pnData),
2580   void *pIn,
2581   int nChangeset,                 /* Size of buffer pChangeset in bytes */
2582   void *pChangeset,               /* Pointer to buffer containing changeset */
2583   int bInvert                     /* True to invert changeset */
2584 ){
2585   sqlite3_changeset_iter *pRet;   /* Iterator to return */
2586   int nByte;                      /* Number of bytes to allocate for iterator */
2587 
2588   assert( xInput==0 || (pChangeset==0 && nChangeset==0) );
2589 
2590   /* Zero the output variable in case an error occurs. */
2591   *pp = 0;
2592 
2593   /* Allocate and initialize the iterator structure. */
2594   nByte = sizeof(sqlite3_changeset_iter);
2595   pRet = (sqlite3_changeset_iter *)sqlite3_malloc(nByte);
2596   if( !pRet ) return SQLITE_NOMEM;
2597   memset(pRet, 0, sizeof(sqlite3_changeset_iter));
2598   pRet->in.aData = (u8 *)pChangeset;
2599   pRet->in.nData = nChangeset;
2600   pRet->in.xInput = xInput;
2601   pRet->in.pIn = pIn;
2602   pRet->in.bEof = (xInput ? 0 : 1);
2603   pRet->bInvert = bInvert;
2604 
2605   /* Populate the output variable and return success. */
2606   *pp = pRet;
2607   return SQLITE_OK;
2608 }
2609 
2610 /*
2611 ** Create an iterator used to iterate through the contents of a changeset.
2612 */
2613 int sqlite3changeset_start(
2614   sqlite3_changeset_iter **pp,    /* OUT: Changeset iterator handle */
2615   int nChangeset,                 /* Size of buffer pChangeset in bytes */
2616   void *pChangeset                /* Pointer to buffer containing changeset */
2617 ){
2618   return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset, 0);
2619 }
2620 int sqlite3changeset_start_v2(
2621   sqlite3_changeset_iter **pp,    /* OUT: Changeset iterator handle */
2622   int nChangeset,                 /* Size of buffer pChangeset in bytes */
2623   void *pChangeset,               /* Pointer to buffer containing changeset */
2624   int flags
2625 ){
2626   int bInvert = !!(flags & SQLITE_CHANGESETSTART_INVERT);
2627   return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset, bInvert);
2628 }
2629 
2630 /*
2631 ** Streaming version of sqlite3changeset_start().
2632 */
2633 int sqlite3changeset_start_strm(
2634   sqlite3_changeset_iter **pp,    /* OUT: Changeset iterator handle */
2635   int (*xInput)(void *pIn, void *pData, int *pnData),
2636   void *pIn
2637 ){
2638   return sessionChangesetStart(pp, xInput, pIn, 0, 0, 0);
2639 }
2640 int sqlite3changeset_start_v2_strm(
2641   sqlite3_changeset_iter **pp,    /* OUT: Changeset iterator handle */
2642   int (*xInput)(void *pIn, void *pData, int *pnData),
2643   void *pIn,
2644   int flags
2645 ){
2646   int bInvert = !!(flags & SQLITE_CHANGESETSTART_INVERT);
2647   return sessionChangesetStart(pp, xInput, pIn, 0, 0, bInvert);
2648 }
2649 
2650 /*
2651 ** If the SessionInput object passed as the only argument is a streaming
2652 ** object and the buffer is full, discard some data to free up space.
2653 */
2654 static void sessionDiscardData(SessionInput *pIn){
2655   if( pIn->xInput && pIn->iNext>=sessions_strm_chunk_size ){
2656     int nMove = pIn->buf.nBuf - pIn->iNext;
2657     assert( nMove>=0 );
2658     if( nMove>0 ){
2659       memmove(pIn->buf.aBuf, &pIn->buf.aBuf[pIn->iNext], nMove);
2660     }
2661     pIn->buf.nBuf -= pIn->iNext;
2662     pIn->iNext = 0;
2663     pIn->nData = pIn->buf.nBuf;
2664   }
2665 }
2666 
2667 /*
2668 ** Ensure that there are at least nByte bytes available in the buffer. Or,
2669 ** if there are not nByte bytes remaining in the input, that all available
2670 ** data is in the buffer.
2671 **
2672 ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
2673 */
2674 static int sessionInputBuffer(SessionInput *pIn, int nByte){
2675   int rc = SQLITE_OK;
2676   if( pIn->xInput ){
2677     while( !pIn->bEof && (pIn->iNext+nByte)>=pIn->nData && rc==SQLITE_OK ){
2678       int nNew = sessions_strm_chunk_size;
2679 
2680       if( pIn->bNoDiscard==0 ) sessionDiscardData(pIn);
2681       if( SQLITE_OK==sessionBufferGrow(&pIn->buf, nNew, &rc) ){
2682         rc = pIn->xInput(pIn->pIn, &pIn->buf.aBuf[pIn->buf.nBuf], &nNew);
2683         if( nNew==0 ){
2684           pIn->bEof = 1;
2685         }else{
2686           pIn->buf.nBuf += nNew;
2687         }
2688       }
2689 
2690       pIn->aData = pIn->buf.aBuf;
2691       pIn->nData = pIn->buf.nBuf;
2692     }
2693   }
2694   return rc;
2695 }
2696 
2697 /*
2698 ** When this function is called, *ppRec points to the start of a record
2699 ** that contains nCol values. This function advances the pointer *ppRec
2700 ** until it points to the byte immediately following that record.
2701 */
2702 static void sessionSkipRecord(
2703   u8 **ppRec,                     /* IN/OUT: Record pointer */
2704   int nCol                        /* Number of values in record */
2705 ){
2706   u8 *aRec = *ppRec;
2707   int i;
2708   for(i=0; i<nCol; i++){
2709     int eType = *aRec++;
2710     if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
2711       int nByte;
2712       aRec += sessionVarintGet((u8*)aRec, &nByte);
2713       aRec += nByte;
2714     }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
2715       aRec += 8;
2716     }
2717   }
2718 
2719   *ppRec = aRec;
2720 }
2721 
2722 /*
2723 ** This function sets the value of the sqlite3_value object passed as the
2724 ** first argument to a copy of the string or blob held in the aData[]
2725 ** buffer. SQLITE_OK is returned if successful, or SQLITE_NOMEM if an OOM
2726 ** error occurs.
2727 */
2728 static int sessionValueSetStr(
2729   sqlite3_value *pVal,            /* Set the value of this object */
2730   u8 *aData,                      /* Buffer containing string or blob data */
2731   int nData,                      /* Size of buffer aData[] in bytes */
2732   u8 enc                          /* String encoding (0 for blobs) */
2733 ){
2734   /* In theory this code could just pass SQLITE_TRANSIENT as the final
2735   ** argument to sqlite3ValueSetStr() and have the copy created
2736   ** automatically. But doing so makes it difficult to detect any OOM
2737   ** error. Hence the code to create the copy externally. */
2738   u8 *aCopy = sqlite3_malloc(nData+1);
2739   if( aCopy==0 ) return SQLITE_NOMEM;
2740   memcpy(aCopy, aData, nData);
2741   sqlite3ValueSetStr(pVal, nData, (char*)aCopy, enc, sqlite3_free);
2742   return SQLITE_OK;
2743 }
2744 
2745 /*
2746 ** Deserialize a single record from a buffer in memory. See "RECORD FORMAT"
2747 ** for details.
2748 **
2749 ** When this function is called, *paChange points to the start of the record
2750 ** to deserialize. Assuming no error occurs, *paChange is set to point to
2751 ** one byte after the end of the same record before this function returns.
2752 ** If the argument abPK is NULL, then the record contains nCol values. Or,
2753 ** if abPK is other than NULL, then the record contains only the PK fields
2754 ** (in other words, it is a patchset DELETE record).
2755 **
2756 ** If successful, each element of the apOut[] array (allocated by the caller)
2757 ** is set to point to an sqlite3_value object containing the value read
2758 ** from the corresponding position in the record. If that value is not
2759 ** included in the record (i.e. because the record is part of an UPDATE change
2760 ** and the field was not modified), the corresponding element of apOut[] is
2761 ** set to NULL.
2762 **
2763 ** It is the responsibility of the caller to free all sqlite_value structures
2764 ** using sqlite3_free().
2765 **
2766 ** If an error occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
2767 ** The apOut[] array may have been partially populated in this case.
2768 */
2769 static int sessionReadRecord(
2770   SessionInput *pIn,              /* Input data */
2771   int nCol,                       /* Number of values in record */
2772   u8 *abPK,                       /* Array of primary key flags, or NULL */
2773   sqlite3_value **apOut           /* Write values to this array */
2774 ){
2775   int i;                          /* Used to iterate through columns */
2776   int rc = SQLITE_OK;
2777 
2778   for(i=0; i<nCol && rc==SQLITE_OK; i++){
2779     int eType = 0;                /* Type of value (SQLITE_NULL, TEXT etc.) */
2780     if( abPK && abPK[i]==0 ) continue;
2781     rc = sessionInputBuffer(pIn, 9);
2782     if( rc==SQLITE_OK ){
2783       if( pIn->iNext>=pIn->nData ){
2784         rc = SQLITE_CORRUPT_BKPT;
2785       }else{
2786         eType = pIn->aData[pIn->iNext++];
2787         assert( apOut[i]==0 );
2788         if( eType ){
2789           apOut[i] = sqlite3ValueNew(0);
2790           if( !apOut[i] ) rc = SQLITE_NOMEM;
2791         }
2792       }
2793     }
2794 
2795     if( rc==SQLITE_OK ){
2796       u8 *aVal = &pIn->aData[pIn->iNext];
2797       if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
2798         int nByte;
2799         pIn->iNext += sessionVarintGet(aVal, &nByte);
2800         rc = sessionInputBuffer(pIn, nByte);
2801         if( rc==SQLITE_OK ){
2802           if( nByte<0 || nByte>pIn->nData-pIn->iNext ){
2803             rc = SQLITE_CORRUPT_BKPT;
2804           }else{
2805             u8 enc = (eType==SQLITE_TEXT ? SQLITE_UTF8 : 0);
2806             rc = sessionValueSetStr(apOut[i],&pIn->aData[pIn->iNext],nByte,enc);
2807             pIn->iNext += nByte;
2808           }
2809         }
2810       }
2811       if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
2812         sqlite3_int64 v = sessionGetI64(aVal);
2813         if( eType==SQLITE_INTEGER ){
2814           sqlite3VdbeMemSetInt64(apOut[i], v);
2815         }else{
2816           double d;
2817           memcpy(&d, &v, 8);
2818           sqlite3VdbeMemSetDouble(apOut[i], d);
2819         }
2820         pIn->iNext += 8;
2821       }
2822     }
2823   }
2824 
2825   return rc;
2826 }
2827 
2828 /*
2829 ** The input pointer currently points to the second byte of a table-header.
2830 ** Specifically, to the following:
2831 **
2832 **   + number of columns in table (varint)
2833 **   + array of PK flags (1 byte per column),
2834 **   + table name (nul terminated).
2835 **
2836 ** This function ensures that all of the above is present in the input
2837 ** buffer (i.e. that it can be accessed without any calls to xInput()).
2838 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
2839 ** The input pointer is not moved.
2840 */
2841 static int sessionChangesetBufferTblhdr(SessionInput *pIn, int *pnByte){
2842   int rc = SQLITE_OK;
2843   int nCol = 0;
2844   int nRead = 0;
2845 
2846   rc = sessionInputBuffer(pIn, 9);
2847   if( rc==SQLITE_OK ){
2848     nRead += sessionVarintGet(&pIn->aData[pIn->iNext + nRead], &nCol);
2849     /* The hard upper limit for the number of columns in an SQLite
2850     ** database table is, according to sqliteLimit.h, 32676. So
2851     ** consider any table-header that purports to have more than 65536
2852     ** columns to be corrupt. This is convenient because otherwise,
2853     ** if the (nCol>65536) condition below were omitted, a sufficiently
2854     ** large value for nCol may cause nRead to wrap around and become
2855     ** negative. Leading to a crash. */
2856     if( nCol<0 || nCol>65536 ){
2857       rc = SQLITE_CORRUPT_BKPT;
2858     }else{
2859       rc = sessionInputBuffer(pIn, nRead+nCol+100);
2860       nRead += nCol;
2861     }
2862   }
2863 
2864   while( rc==SQLITE_OK ){
2865     while( (pIn->iNext + nRead)<pIn->nData && pIn->aData[pIn->iNext + nRead] ){
2866       nRead++;
2867     }
2868     if( (pIn->iNext + nRead)<pIn->nData ) break;
2869     rc = sessionInputBuffer(pIn, nRead + 100);
2870   }
2871   *pnByte = nRead+1;
2872   return rc;
2873 }
2874 
2875 /*
2876 ** The input pointer currently points to the first byte of the first field
2877 ** of a record consisting of nCol columns. This function ensures the entire
2878 ** record is buffered. It does not move the input pointer.
2879 **
2880 ** If successful, SQLITE_OK is returned and *pnByte is set to the size of
2881 ** the record in bytes. Otherwise, an SQLite error code is returned. The
2882 ** final value of *pnByte is undefined in this case.
2883 */
2884 static int sessionChangesetBufferRecord(
2885   SessionInput *pIn,              /* Input data */
2886   int nCol,                       /* Number of columns in record */
2887   int *pnByte                     /* OUT: Size of record in bytes */
2888 ){
2889   int rc = SQLITE_OK;
2890   int nByte = 0;
2891   int i;
2892   for(i=0; rc==SQLITE_OK && i<nCol; i++){
2893     int eType;
2894     rc = sessionInputBuffer(pIn, nByte + 10);
2895     if( rc==SQLITE_OK ){
2896       eType = pIn->aData[pIn->iNext + nByte++];
2897       if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
2898         int n;
2899         nByte += sessionVarintGet(&pIn->aData[pIn->iNext+nByte], &n);
2900         nByte += n;
2901         rc = sessionInputBuffer(pIn, nByte);
2902       }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
2903         nByte += 8;
2904       }
2905     }
2906   }
2907   *pnByte = nByte;
2908   return rc;
2909 }
2910 
2911 /*
2912 ** The input pointer currently points to the second byte of a table-header.
2913 ** Specifically, to the following:
2914 **
2915 **   + number of columns in table (varint)
2916 **   + array of PK flags (1 byte per column),
2917 **   + table name (nul terminated).
2918 **
2919 ** This function decodes the table-header and populates the p->nCol,
2920 ** p->zTab and p->abPK[] variables accordingly. The p->apValue[] array is
2921 ** also allocated or resized according to the new value of p->nCol. The
2922 ** input pointer is left pointing to the byte following the table header.
2923 **
2924 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code
2925 ** is returned and the final values of the various fields enumerated above
2926 ** are undefined.
2927 */
2928 static int sessionChangesetReadTblhdr(sqlite3_changeset_iter *p){
2929   int rc;
2930   int nCopy;
2931   assert( p->rc==SQLITE_OK );
2932 
2933   rc = sessionChangesetBufferTblhdr(&p->in, &nCopy);
2934   if( rc==SQLITE_OK ){
2935     int nByte;
2936     int nVarint;
2937     nVarint = sessionVarintGet(&p->in.aData[p->in.iNext], &p->nCol);
2938     if( p->nCol>0 ){
2939       nCopy -= nVarint;
2940       p->in.iNext += nVarint;
2941       nByte = p->nCol * sizeof(sqlite3_value*) * 2 + nCopy;
2942       p->tblhdr.nBuf = 0;
2943       sessionBufferGrow(&p->tblhdr, nByte, &rc);
2944     }else{
2945       rc = SQLITE_CORRUPT_BKPT;
2946     }
2947   }
2948 
2949   if( rc==SQLITE_OK ){
2950     int iPK = sizeof(sqlite3_value*)*p->nCol*2;
2951     memset(p->tblhdr.aBuf, 0, iPK);
2952     memcpy(&p->tblhdr.aBuf[iPK], &p->in.aData[p->in.iNext], nCopy);
2953     p->in.iNext += nCopy;
2954   }
2955 
2956   p->apValue = (sqlite3_value**)p->tblhdr.aBuf;
2957   p->abPK = (u8*)&p->apValue[p->nCol*2];
2958   p->zTab = (char*)&p->abPK[p->nCol];
2959   return (p->rc = rc);
2960 }
2961 
2962 /*
2963 ** Advance the changeset iterator to the next change.
2964 **
2965 ** If both paRec and pnRec are NULL, then this function works like the public
2966 ** API sqlite3changeset_next(). If SQLITE_ROW is returned, then the
2967 ** sqlite3changeset_new() and old() APIs may be used to query for values.
2968 **
2969 ** Otherwise, if paRec and pnRec are not NULL, then a pointer to the change
2970 ** record is written to *paRec before returning and the number of bytes in
2971 ** the record to *pnRec.
2972 **
2973 ** Either way, this function returns SQLITE_ROW if the iterator is
2974 ** successfully advanced to the next change in the changeset, an SQLite
2975 ** error code if an error occurs, or SQLITE_DONE if there are no further
2976 ** changes in the changeset.
2977 */
2978 static int sessionChangesetNext(
2979   sqlite3_changeset_iter *p,      /* Changeset iterator */
2980   u8 **paRec,                     /* If non-NULL, store record pointer here */
2981   int *pnRec,                     /* If non-NULL, store size of record here */
2982   int *pbNew                      /* If non-NULL, true if new table */
2983 ){
2984   int i;
2985   u8 op;
2986 
2987   assert( (paRec==0 && pnRec==0) || (paRec && pnRec) );
2988 
2989   /* If the iterator is in the error-state, return immediately. */
2990   if( p->rc!=SQLITE_OK ) return p->rc;
2991 
2992   /* Free the current contents of p->apValue[], if any. */
2993   if( p->apValue ){
2994     for(i=0; i<p->nCol*2; i++){
2995       sqlite3ValueFree(p->apValue[i]);
2996     }
2997     memset(p->apValue, 0, sizeof(sqlite3_value*)*p->nCol*2);
2998   }
2999 
3000   /* Make sure the buffer contains at least 10 bytes of input data, or all
3001   ** remaining data if there are less than 10 bytes available. This is
3002   ** sufficient either for the 'T' or 'P' byte and the varint that follows
3003   ** it, or for the two single byte values otherwise. */
3004   p->rc = sessionInputBuffer(&p->in, 2);
3005   if( p->rc!=SQLITE_OK ) return p->rc;
3006 
3007   /* If the iterator is already at the end of the changeset, return DONE. */
3008   if( p->in.iNext>=p->in.nData ){
3009     return SQLITE_DONE;
3010   }
3011 
3012   sessionDiscardData(&p->in);
3013   p->in.iCurrent = p->in.iNext;
3014 
3015   op = p->in.aData[p->in.iNext++];
3016   while( op=='T' || op=='P' ){
3017     if( pbNew ) *pbNew = 1;
3018     p->bPatchset = (op=='P');
3019     if( sessionChangesetReadTblhdr(p) ) return p->rc;
3020     if( (p->rc = sessionInputBuffer(&p->in, 2)) ) return p->rc;
3021     p->in.iCurrent = p->in.iNext;
3022     if( p->in.iNext>=p->in.nData ) return SQLITE_DONE;
3023     op = p->in.aData[p->in.iNext++];
3024   }
3025 
3026   if( p->zTab==0 || (p->bPatchset && p->bInvert) ){
3027     /* The first record in the changeset is not a table header. Must be a
3028     ** corrupt changeset. */
3029     assert( p->in.iNext==1 || p->zTab );
3030     return (p->rc = SQLITE_CORRUPT_BKPT);
3031   }
3032 
3033   p->op = op;
3034   p->bIndirect = p->in.aData[p->in.iNext++];
3035   if( p->op!=SQLITE_UPDATE && p->op!=SQLITE_DELETE && p->op!=SQLITE_INSERT ){
3036     return (p->rc = SQLITE_CORRUPT_BKPT);
3037   }
3038 
3039   if( paRec ){
3040     int nVal;                     /* Number of values to buffer */
3041     if( p->bPatchset==0 && op==SQLITE_UPDATE ){
3042       nVal = p->nCol * 2;
3043     }else if( p->bPatchset && op==SQLITE_DELETE ){
3044       nVal = 0;
3045       for(i=0; i<p->nCol; i++) if( p->abPK[i] ) nVal++;
3046     }else{
3047       nVal = p->nCol;
3048     }
3049     p->rc = sessionChangesetBufferRecord(&p->in, nVal, pnRec);
3050     if( p->rc!=SQLITE_OK ) return p->rc;
3051     *paRec = &p->in.aData[p->in.iNext];
3052     p->in.iNext += *pnRec;
3053   }else{
3054     sqlite3_value **apOld = (p->bInvert ? &p->apValue[p->nCol] : p->apValue);
3055     sqlite3_value **apNew = (p->bInvert ? p->apValue : &p->apValue[p->nCol]);
3056 
3057     /* If this is an UPDATE or DELETE, read the old.* record. */
3058     if( p->op!=SQLITE_INSERT && (p->bPatchset==0 || p->op==SQLITE_DELETE) ){
3059       u8 *abPK = p->bPatchset ? p->abPK : 0;
3060       p->rc = sessionReadRecord(&p->in, p->nCol, abPK, apOld);
3061       if( p->rc!=SQLITE_OK ) return p->rc;
3062     }
3063 
3064     /* If this is an INSERT or UPDATE, read the new.* record. */
3065     if( p->op!=SQLITE_DELETE ){
3066       p->rc = sessionReadRecord(&p->in, p->nCol, 0, apNew);
3067       if( p->rc!=SQLITE_OK ) return p->rc;
3068     }
3069 
3070     if( (p->bPatchset || p->bInvert) && p->op==SQLITE_UPDATE ){
3071       /* If this is an UPDATE that is part of a patchset, then all PK and
3072       ** modified fields are present in the new.* record. The old.* record
3073       ** is currently completely empty. This block shifts the PK fields from
3074       ** new.* to old.*, to accommodate the code that reads these arrays.  */
3075       for(i=0; i<p->nCol; i++){
3076         assert( p->bPatchset==0 || p->apValue[i]==0 );
3077         if( p->abPK[i] ){
3078           assert( p->apValue[i]==0 );
3079           p->apValue[i] = p->apValue[i+p->nCol];
3080           if( p->apValue[i]==0 ) return (p->rc = SQLITE_CORRUPT_BKPT);
3081           p->apValue[i+p->nCol] = 0;
3082         }
3083       }
3084     }else if( p->bInvert ){
3085       if( p->op==SQLITE_INSERT ) p->op = SQLITE_DELETE;
3086       else if( p->op==SQLITE_DELETE ) p->op = SQLITE_INSERT;
3087     }
3088   }
3089 
3090   return SQLITE_ROW;
3091 }
3092 
3093 /*
3094 ** Advance an iterator created by sqlite3changeset_start() to the next
3095 ** change in the changeset. This function may return SQLITE_ROW, SQLITE_DONE
3096 ** or SQLITE_CORRUPT.
3097 **
3098 ** This function may not be called on iterators passed to a conflict handler
3099 ** callback by changeset_apply().
3100 */
3101 int sqlite3changeset_next(sqlite3_changeset_iter *p){
3102   return sessionChangesetNext(p, 0, 0, 0);
3103 }
3104 
3105 /*
3106 ** The following function extracts information on the current change
3107 ** from a changeset iterator. It may only be called after changeset_next()
3108 ** has returned SQLITE_ROW.
3109 */
3110 int sqlite3changeset_op(
3111   sqlite3_changeset_iter *pIter,  /* Iterator handle */
3112   const char **pzTab,             /* OUT: Pointer to table name */
3113   int *pnCol,                     /* OUT: Number of columns in table */
3114   int *pOp,                       /* OUT: SQLITE_INSERT, DELETE or UPDATE */
3115   int *pbIndirect                 /* OUT: True if change is indirect */
3116 ){
3117   *pOp = pIter->op;
3118   *pnCol = pIter->nCol;
3119   *pzTab = pIter->zTab;
3120   if( pbIndirect ) *pbIndirect = pIter->bIndirect;
3121   return SQLITE_OK;
3122 }
3123 
3124 /*
3125 ** Return information regarding the PRIMARY KEY and number of columns in
3126 ** the database table affected by the change that pIter currently points
3127 ** to. This function may only be called after changeset_next() returns
3128 ** SQLITE_ROW.
3129 */
3130 int sqlite3changeset_pk(
3131   sqlite3_changeset_iter *pIter,  /* Iterator object */
3132   unsigned char **pabPK,          /* OUT: Array of boolean - true for PK cols */
3133   int *pnCol                      /* OUT: Number of entries in output array */
3134 ){
3135   *pabPK = pIter->abPK;
3136   if( pnCol ) *pnCol = pIter->nCol;
3137   return SQLITE_OK;
3138 }
3139 
3140 /*
3141 ** This function may only be called while the iterator is pointing to an
3142 ** SQLITE_UPDATE or SQLITE_DELETE change (see sqlite3changeset_op()).
3143 ** Otherwise, SQLITE_MISUSE is returned.
3144 **
3145 ** It sets *ppValue to point to an sqlite3_value structure containing the
3146 ** iVal'th value in the old.* record. Or, if that particular value is not
3147 ** included in the record (because the change is an UPDATE and the field
3148 ** was not modified and is not a PK column), set *ppValue to NULL.
3149 **
3150 ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
3151 ** not modified. Otherwise, SQLITE_OK.
3152 */
3153 int sqlite3changeset_old(
3154   sqlite3_changeset_iter *pIter,  /* Changeset iterator */
3155   int iVal,                       /* Index of old.* value to retrieve */
3156   sqlite3_value **ppValue         /* OUT: Old value (or NULL pointer) */
3157 ){
3158   if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_DELETE ){
3159     return SQLITE_MISUSE;
3160   }
3161   if( iVal<0 || iVal>=pIter->nCol ){
3162     return SQLITE_RANGE;
3163   }
3164   *ppValue = pIter->apValue[iVal];
3165   return SQLITE_OK;
3166 }
3167 
3168 /*
3169 ** This function may only be called while the iterator is pointing to an
3170 ** SQLITE_UPDATE or SQLITE_INSERT change (see sqlite3changeset_op()).
3171 ** Otherwise, SQLITE_MISUSE is returned.
3172 **
3173 ** It sets *ppValue to point to an sqlite3_value structure containing the
3174 ** iVal'th value in the new.* record. Or, if that particular value is not
3175 ** included in the record (because the change is an UPDATE and the field
3176 ** was not modified), set *ppValue to NULL.
3177 **
3178 ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
3179 ** not modified. Otherwise, SQLITE_OK.
3180 */
3181 int sqlite3changeset_new(
3182   sqlite3_changeset_iter *pIter,  /* Changeset iterator */
3183   int iVal,                       /* Index of new.* value to retrieve */
3184   sqlite3_value **ppValue         /* OUT: New value (or NULL pointer) */
3185 ){
3186   if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_INSERT ){
3187     return SQLITE_MISUSE;
3188   }
3189   if( iVal<0 || iVal>=pIter->nCol ){
3190     return SQLITE_RANGE;
3191   }
3192   *ppValue = pIter->apValue[pIter->nCol+iVal];
3193   return SQLITE_OK;
3194 }
3195 
3196 /*
3197 ** The following two macros are used internally. They are similar to the
3198 ** sqlite3changeset_new() and sqlite3changeset_old() functions, except that
3199 ** they omit all error checking and return a pointer to the requested value.
3200 */
3201 #define sessionChangesetNew(pIter, iVal) (pIter)->apValue[(pIter)->nCol+(iVal)]
3202 #define sessionChangesetOld(pIter, iVal) (pIter)->apValue[(iVal)]
3203 
3204 /*
3205 ** This function may only be called with a changeset iterator that has been
3206 ** passed to an SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT
3207 ** conflict-handler function. Otherwise, SQLITE_MISUSE is returned.
3208 **
3209 ** If successful, *ppValue is set to point to an sqlite3_value structure
3210 ** containing the iVal'th value of the conflicting record.
3211 **
3212 ** If value iVal is out-of-range or some other error occurs, an SQLite error
3213 ** code is returned. Otherwise, SQLITE_OK.
3214 */
3215 int sqlite3changeset_conflict(
3216   sqlite3_changeset_iter *pIter,  /* Changeset iterator */
3217   int iVal,                       /* Index of conflict record value to fetch */
3218   sqlite3_value **ppValue         /* OUT: Value from conflicting row */
3219 ){
3220   if( !pIter->pConflict ){
3221     return SQLITE_MISUSE;
3222   }
3223   if( iVal<0 || iVal>=pIter->nCol ){
3224     return SQLITE_RANGE;
3225   }
3226   *ppValue = sqlite3_column_value(pIter->pConflict, iVal);
3227   return SQLITE_OK;
3228 }
3229 
3230 /*
3231 ** This function may only be called with an iterator passed to an
3232 ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
3233 ** it sets the output variable to the total number of known foreign key
3234 ** violations in the destination database and returns SQLITE_OK.
3235 **
3236 ** In all other cases this function returns SQLITE_MISUSE.
3237 */
3238 int sqlite3changeset_fk_conflicts(
3239   sqlite3_changeset_iter *pIter,  /* Changeset iterator */
3240   int *pnOut                      /* OUT: Number of FK violations */
3241 ){
3242   if( pIter->pConflict || pIter->apValue ){
3243     return SQLITE_MISUSE;
3244   }
3245   *pnOut = pIter->nCol;
3246   return SQLITE_OK;
3247 }
3248 
3249 
3250 /*
3251 ** Finalize an iterator allocated with sqlite3changeset_start().
3252 **
3253 ** This function may not be called on iterators passed to a conflict handler
3254 ** callback by changeset_apply().
3255 */
3256 int sqlite3changeset_finalize(sqlite3_changeset_iter *p){
3257   int rc = SQLITE_OK;
3258   if( p ){
3259     int i;                        /* Used to iterate through p->apValue[] */
3260     rc = p->rc;
3261     if( p->apValue ){
3262       for(i=0; i<p->nCol*2; i++) sqlite3ValueFree(p->apValue[i]);
3263     }
3264     sqlite3_free(p->tblhdr.aBuf);
3265     sqlite3_free(p->in.buf.aBuf);
3266     sqlite3_free(p);
3267   }
3268   return rc;
3269 }
3270 
3271 static int sessionChangesetInvert(
3272   SessionInput *pInput,           /* Input changeset */
3273   int (*xOutput)(void *pOut, const void *pData, int nData),
3274   void *pOut,
3275   int *pnInverted,                /* OUT: Number of bytes in output changeset */
3276   void **ppInverted               /* OUT: Inverse of pChangeset */
3277 ){
3278   int rc = SQLITE_OK;             /* Return value */
3279   SessionBuffer sOut;             /* Output buffer */
3280   int nCol = 0;                   /* Number of cols in current table */
3281   u8 *abPK = 0;                   /* PK array for current table */
3282   sqlite3_value **apVal = 0;      /* Space for values for UPDATE inversion */
3283   SessionBuffer sPK = {0, 0, 0};  /* PK array for current table */
3284 
3285   /* Initialize the output buffer */
3286   memset(&sOut, 0, sizeof(SessionBuffer));
3287 
3288   /* Zero the output variables in case an error occurs. */
3289   if( ppInverted ){
3290     *ppInverted = 0;
3291     *pnInverted = 0;
3292   }
3293 
3294   while( 1 ){
3295     u8 eType;
3296 
3297     /* Test for EOF. */
3298     if( (rc = sessionInputBuffer(pInput, 2)) ) goto finished_invert;
3299     if( pInput->iNext>=pInput->nData ) break;
3300     eType = pInput->aData[pInput->iNext];
3301 
3302     switch( eType ){
3303       case 'T': {
3304         /* A 'table' record consists of:
3305         **
3306         **   * A constant 'T' character,
3307         **   * Number of columns in said table (a varint),
3308         **   * An array of nCol bytes (sPK),
3309         **   * A nul-terminated table name.
3310         */
3311         int nByte;
3312         int nVar;
3313         pInput->iNext++;
3314         if( (rc = sessionChangesetBufferTblhdr(pInput, &nByte)) ){
3315           goto finished_invert;
3316         }
3317         nVar = sessionVarintGet(&pInput->aData[pInput->iNext], &nCol);
3318         sPK.nBuf = 0;
3319         sessionAppendBlob(&sPK, &pInput->aData[pInput->iNext+nVar], nCol, &rc);
3320         sessionAppendByte(&sOut, eType, &rc);
3321         sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
3322         if( rc ) goto finished_invert;
3323 
3324         pInput->iNext += nByte;
3325         sqlite3_free(apVal);
3326         apVal = 0;
3327         abPK = sPK.aBuf;
3328         break;
3329       }
3330 
3331       case SQLITE_INSERT:
3332       case SQLITE_DELETE: {
3333         int nByte;
3334         int bIndirect = pInput->aData[pInput->iNext+1];
3335         int eType2 = (eType==SQLITE_DELETE ? SQLITE_INSERT : SQLITE_DELETE);
3336         pInput->iNext += 2;
3337         assert( rc==SQLITE_OK );
3338         rc = sessionChangesetBufferRecord(pInput, nCol, &nByte);
3339         sessionAppendByte(&sOut, eType2, &rc);
3340         sessionAppendByte(&sOut, bIndirect, &rc);
3341         sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
3342         pInput->iNext += nByte;
3343         if( rc ) goto finished_invert;
3344         break;
3345       }
3346 
3347       case SQLITE_UPDATE: {
3348         int iCol;
3349 
3350         if( 0==apVal ){
3351           apVal = (sqlite3_value **)sqlite3_malloc(sizeof(apVal[0])*nCol*2);
3352           if( 0==apVal ){
3353             rc = SQLITE_NOMEM;
3354             goto finished_invert;
3355           }
3356           memset(apVal, 0, sizeof(apVal[0])*nCol*2);
3357         }
3358 
3359         /* Write the header for the new UPDATE change. Same as the original. */
3360         sessionAppendByte(&sOut, eType, &rc);
3361         sessionAppendByte(&sOut, pInput->aData[pInput->iNext+1], &rc);
3362 
3363         /* Read the old.* and new.* records for the update change. */
3364         pInput->iNext += 2;
3365         rc = sessionReadRecord(pInput, nCol, 0, &apVal[0]);
3366         if( rc==SQLITE_OK ){
3367           rc = sessionReadRecord(pInput, nCol, 0, &apVal[nCol]);
3368         }
3369 
3370         /* Write the new old.* record. Consists of the PK columns from the
3371         ** original old.* record, and the other values from the original
3372         ** new.* record. */
3373         for(iCol=0; iCol<nCol; iCol++){
3374           sqlite3_value *pVal = apVal[iCol + (abPK[iCol] ? 0 : nCol)];
3375           sessionAppendValue(&sOut, pVal, &rc);
3376         }
3377 
3378         /* Write the new new.* record. Consists of a copy of all values
3379         ** from the original old.* record, except for the PK columns, which
3380         ** are set to "undefined". */
3381         for(iCol=0; iCol<nCol; iCol++){
3382           sqlite3_value *pVal = (abPK[iCol] ? 0 : apVal[iCol]);
3383           sessionAppendValue(&sOut, pVal, &rc);
3384         }
3385 
3386         for(iCol=0; iCol<nCol*2; iCol++){
3387           sqlite3ValueFree(apVal[iCol]);
3388         }
3389         memset(apVal, 0, sizeof(apVal[0])*nCol*2);
3390         if( rc!=SQLITE_OK ){
3391           goto finished_invert;
3392         }
3393 
3394         break;
3395       }
3396 
3397       default:
3398         rc = SQLITE_CORRUPT_BKPT;
3399         goto finished_invert;
3400     }
3401 
3402     assert( rc==SQLITE_OK );
3403     if( xOutput && sOut.nBuf>=sessions_strm_chunk_size ){
3404       rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
3405       sOut.nBuf = 0;
3406       if( rc!=SQLITE_OK ) goto finished_invert;
3407     }
3408   }
3409 
3410   assert( rc==SQLITE_OK );
3411   if( pnInverted ){
3412     *pnInverted = sOut.nBuf;
3413     *ppInverted = sOut.aBuf;
3414     sOut.aBuf = 0;
3415   }else if( sOut.nBuf>0 ){
3416     rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
3417   }
3418 
3419  finished_invert:
3420   sqlite3_free(sOut.aBuf);
3421   sqlite3_free(apVal);
3422   sqlite3_free(sPK.aBuf);
3423   return rc;
3424 }
3425 
3426 
3427 /*
3428 ** Invert a changeset object.
3429 */
3430 int sqlite3changeset_invert(
3431   int nChangeset,                 /* Number of bytes in input */
3432   const void *pChangeset,         /* Input changeset */
3433   int *pnInverted,                /* OUT: Number of bytes in output changeset */
3434   void **ppInverted               /* OUT: Inverse of pChangeset */
3435 ){
3436   SessionInput sInput;
3437 
3438   /* Set up the input stream */
3439   memset(&sInput, 0, sizeof(SessionInput));
3440   sInput.nData = nChangeset;
3441   sInput.aData = (u8*)pChangeset;
3442 
3443   return sessionChangesetInvert(&sInput, 0, 0, pnInverted, ppInverted);
3444 }
3445 
3446 /*
3447 ** Streaming version of sqlite3changeset_invert().
3448 */
3449 int sqlite3changeset_invert_strm(
3450   int (*xInput)(void *pIn, void *pData, int *pnData),
3451   void *pIn,
3452   int (*xOutput)(void *pOut, const void *pData, int nData),
3453   void *pOut
3454 ){
3455   SessionInput sInput;
3456   int rc;
3457 
3458   /* Set up the input stream */
3459   memset(&sInput, 0, sizeof(SessionInput));
3460   sInput.xInput = xInput;
3461   sInput.pIn = pIn;
3462 
3463   rc = sessionChangesetInvert(&sInput, xOutput, pOut, 0, 0);
3464   sqlite3_free(sInput.buf.aBuf);
3465   return rc;
3466 }
3467 
3468 typedef struct SessionApplyCtx SessionApplyCtx;
3469 struct SessionApplyCtx {
3470   sqlite3 *db;
3471   sqlite3_stmt *pDelete;          /* DELETE statement */
3472   sqlite3_stmt *pUpdate;          /* UPDATE statement */
3473   sqlite3_stmt *pInsert;          /* INSERT statement */
3474   sqlite3_stmt *pSelect;          /* SELECT statement */
3475   int nCol;                       /* Size of azCol[] and abPK[] arrays */
3476   const char **azCol;             /* Array of column names */
3477   u8 *abPK;                       /* Boolean array - true if column is in PK */
3478   int bStat1;                     /* True if table is sqlite_stat1 */
3479   int bDeferConstraints;          /* True to defer constraints */
3480   SessionBuffer constraints;      /* Deferred constraints are stored here */
3481   SessionBuffer rebase;           /* Rebase information (if any) here */
3482   u8 bRebaseStarted;              /* If table header is already in rebase */
3483   u8 bRebase;                     /* True to collect rebase information */
3484 };
3485 
3486 /*
3487 ** Formulate a statement to DELETE a row from database db. Assuming a table
3488 ** structure like this:
3489 **
3490 **     CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
3491 **
3492 ** The DELETE statement looks like this:
3493 **
3494 **     DELETE FROM x WHERE a = :1 AND c = :3 AND (:5 OR b IS :2 AND d IS :4)
3495 **
3496 ** Variable :5 (nCol+1) is a boolean. It should be set to 0 if we require
3497 ** matching b and d values, or 1 otherwise. The second case comes up if the
3498 ** conflict handler is invoked with NOTFOUND and returns CHANGESET_REPLACE.
3499 **
3500 ** If successful, SQLITE_OK is returned and SessionApplyCtx.pDelete is left
3501 ** pointing to the prepared version of the SQL statement.
3502 */
3503 static int sessionDeleteRow(
3504   sqlite3 *db,                    /* Database handle */
3505   const char *zTab,               /* Table name */
3506   SessionApplyCtx *p              /* Session changeset-apply context */
3507 ){
3508   int i;
3509   const char *zSep = "";
3510   int rc = SQLITE_OK;
3511   SessionBuffer buf = {0, 0, 0};
3512   int nPk = 0;
3513 
3514   sessionAppendStr(&buf, "DELETE FROM ", &rc);
3515   sessionAppendIdent(&buf, zTab, &rc);
3516   sessionAppendStr(&buf, " WHERE ", &rc);
3517 
3518   for(i=0; i<p->nCol; i++){
3519     if( p->abPK[i] ){
3520       nPk++;
3521       sessionAppendStr(&buf, zSep, &rc);
3522       sessionAppendIdent(&buf, p->azCol[i], &rc);
3523       sessionAppendStr(&buf, " = ?", &rc);
3524       sessionAppendInteger(&buf, i+1, &rc);
3525       zSep = " AND ";
3526     }
3527   }
3528 
3529   if( nPk<p->nCol ){
3530     sessionAppendStr(&buf, " AND (?", &rc);
3531     sessionAppendInteger(&buf, p->nCol+1, &rc);
3532     sessionAppendStr(&buf, " OR ", &rc);
3533 
3534     zSep = "";
3535     for(i=0; i<p->nCol; i++){
3536       if( !p->abPK[i] ){
3537         sessionAppendStr(&buf, zSep, &rc);
3538         sessionAppendIdent(&buf, p->azCol[i], &rc);
3539         sessionAppendStr(&buf, " IS ?", &rc);
3540         sessionAppendInteger(&buf, i+1, &rc);
3541         zSep = "AND ";
3542       }
3543     }
3544     sessionAppendStr(&buf, ")", &rc);
3545   }
3546 
3547   if( rc==SQLITE_OK ){
3548     rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pDelete, 0);
3549   }
3550   sqlite3_free(buf.aBuf);
3551 
3552   return rc;
3553 }
3554 
3555 /*
3556 ** Formulate and prepare a statement to UPDATE a row from database db.
3557 ** Assuming a table structure like this:
3558 **
3559 **     CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
3560 **
3561 ** The UPDATE statement looks like this:
3562 **
3563 **     UPDATE x SET
3564 **     a = CASE WHEN ?2  THEN ?3  ELSE a END,
3565 **     b = CASE WHEN ?5  THEN ?6  ELSE b END,
3566 **     c = CASE WHEN ?8  THEN ?9  ELSE c END,
3567 **     d = CASE WHEN ?11 THEN ?12 ELSE d END
3568 **     WHERE a = ?1 AND c = ?7 AND (?13 OR
3569 **       (?5==0 OR b IS ?4) AND (?11==0 OR d IS ?10) AND
3570 **     )
3571 **
3572 ** For each column in the table, there are three variables to bind:
3573 **
3574 **     ?(i*3+1)    The old.* value of the column, if any.
3575 **     ?(i*3+2)    A boolean flag indicating that the value is being modified.
3576 **     ?(i*3+3)    The new.* value of the column, if any.
3577 **
3578 ** Also, a boolean flag that, if set to true, causes the statement to update
3579 ** a row even if the non-PK values do not match. This is required if the
3580 ** conflict-handler is invoked with CHANGESET_DATA and returns
3581 ** CHANGESET_REPLACE. This is variable "?(nCol*3+1)".
3582 **
3583 ** If successful, SQLITE_OK is returned and SessionApplyCtx.pUpdate is left
3584 ** pointing to the prepared version of the SQL statement.
3585 */
3586 static int sessionUpdateRow(
3587   sqlite3 *db,                    /* Database handle */
3588   const char *zTab,               /* Table name */
3589   SessionApplyCtx *p              /* Session changeset-apply context */
3590 ){
3591   int rc = SQLITE_OK;
3592   int i;
3593   const char *zSep = "";
3594   SessionBuffer buf = {0, 0, 0};
3595 
3596   /* Append "UPDATE tbl SET " */
3597   sessionAppendStr(&buf, "UPDATE ", &rc);
3598   sessionAppendIdent(&buf, zTab, &rc);
3599   sessionAppendStr(&buf, " SET ", &rc);
3600 
3601   /* Append the assignments */
3602   for(i=0; i<p->nCol; i++){
3603     sessionAppendStr(&buf, zSep, &rc);
3604     sessionAppendIdent(&buf, p->azCol[i], &rc);
3605     sessionAppendStr(&buf, " = CASE WHEN ?", &rc);
3606     sessionAppendInteger(&buf, i*3+2, &rc);
3607     sessionAppendStr(&buf, " THEN ?", &rc);
3608     sessionAppendInteger(&buf, i*3+3, &rc);
3609     sessionAppendStr(&buf, " ELSE ", &rc);
3610     sessionAppendIdent(&buf, p->azCol[i], &rc);
3611     sessionAppendStr(&buf, " END", &rc);
3612     zSep = ", ";
3613   }
3614 
3615   /* Append the PK part of the WHERE clause */
3616   sessionAppendStr(&buf, " WHERE ", &rc);
3617   for(i=0; i<p->nCol; i++){
3618     if( p->abPK[i] ){
3619       sessionAppendIdent(&buf, p->azCol[i], &rc);
3620       sessionAppendStr(&buf, " = ?", &rc);
3621       sessionAppendInteger(&buf, i*3+1, &rc);
3622       sessionAppendStr(&buf, " AND ", &rc);
3623     }
3624   }
3625 
3626   /* Append the non-PK part of the WHERE clause */
3627   sessionAppendStr(&buf, " (?", &rc);
3628   sessionAppendInteger(&buf, p->nCol*3+1, &rc);
3629   sessionAppendStr(&buf, " OR 1", &rc);
3630   for(i=0; i<p->nCol; i++){
3631     if( !p->abPK[i] ){
3632       sessionAppendStr(&buf, " AND (?", &rc);
3633       sessionAppendInteger(&buf, i*3+2, &rc);
3634       sessionAppendStr(&buf, "=0 OR ", &rc);
3635       sessionAppendIdent(&buf, p->azCol[i], &rc);
3636       sessionAppendStr(&buf, " IS ?", &rc);
3637       sessionAppendInteger(&buf, i*3+1, &rc);
3638       sessionAppendStr(&buf, ")", &rc);
3639     }
3640   }
3641   sessionAppendStr(&buf, ")", &rc);
3642 
3643   if( rc==SQLITE_OK ){
3644     rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pUpdate, 0);
3645   }
3646   sqlite3_free(buf.aBuf);
3647 
3648   return rc;
3649 }
3650 
3651 
3652 /*
3653 ** Formulate and prepare an SQL statement to query table zTab by primary
3654 ** key. Assuming the following table structure:
3655 **
3656 **     CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
3657 **
3658 ** The SELECT statement looks like this:
3659 **
3660 **     SELECT * FROM x WHERE a = ?1 AND c = ?3
3661 **
3662 ** If successful, SQLITE_OK is returned and SessionApplyCtx.pSelect is left
3663 ** pointing to the prepared version of the SQL statement.
3664 */
3665 static int sessionSelectRow(
3666   sqlite3 *db,                    /* Database handle */
3667   const char *zTab,               /* Table name */
3668   SessionApplyCtx *p              /* Session changeset-apply context */
3669 ){
3670   return sessionSelectStmt(
3671       db, "main", zTab, p->nCol, p->azCol, p->abPK, &p->pSelect);
3672 }
3673 
3674 /*
3675 ** Formulate and prepare an INSERT statement to add a record to table zTab.
3676 ** For example:
3677 **
3678 **     INSERT INTO main."zTab" VALUES(?1, ?2, ?3 ...);
3679 **
3680 ** If successful, SQLITE_OK is returned and SessionApplyCtx.pInsert is left
3681 ** pointing to the prepared version of the SQL statement.
3682 */
3683 static int sessionInsertRow(
3684   sqlite3 *db,                    /* Database handle */
3685   const char *zTab,               /* Table name */
3686   SessionApplyCtx *p              /* Session changeset-apply context */
3687 ){
3688   int rc = SQLITE_OK;
3689   int i;
3690   SessionBuffer buf = {0, 0, 0};
3691 
3692   sessionAppendStr(&buf, "INSERT INTO main.", &rc);
3693   sessionAppendIdent(&buf, zTab, &rc);
3694   sessionAppendStr(&buf, "(", &rc);
3695   for(i=0; i<p->nCol; i++){
3696     if( i!=0 ) sessionAppendStr(&buf, ", ", &rc);
3697     sessionAppendIdent(&buf, p->azCol[i], &rc);
3698   }
3699 
3700   sessionAppendStr(&buf, ") VALUES(?", &rc);
3701   for(i=1; i<p->nCol; i++){
3702     sessionAppendStr(&buf, ", ?", &rc);
3703   }
3704   sessionAppendStr(&buf, ")", &rc);
3705 
3706   if( rc==SQLITE_OK ){
3707     rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pInsert, 0);
3708   }
3709   sqlite3_free(buf.aBuf);
3710   return rc;
3711 }
3712 
3713 static int sessionPrepare(sqlite3 *db, sqlite3_stmt **pp, const char *zSql){
3714   return sqlite3_prepare_v2(db, zSql, -1, pp, 0);
3715 }
3716 
3717 /*
3718 ** Prepare statements for applying changes to the sqlite_stat1 table.
3719 ** These are similar to those created by sessionSelectRow(),
3720 ** sessionInsertRow(), sessionUpdateRow() and sessionDeleteRow() for
3721 ** other tables.
3722 */
3723 static int sessionStat1Sql(sqlite3 *db, SessionApplyCtx *p){
3724   int rc = sessionSelectRow(db, "sqlite_stat1", p);
3725   if( rc==SQLITE_OK ){
3726     rc = sessionPrepare(db, &p->pInsert,
3727         "INSERT INTO main.sqlite_stat1 VALUES(?1, "
3728         "CASE WHEN length(?2)=0 AND typeof(?2)='blob' THEN NULL ELSE ?2 END, "
3729         "?3)"
3730     );
3731   }
3732   if( rc==SQLITE_OK ){
3733     rc = sessionPrepare(db, &p->pUpdate,
3734         "UPDATE main.sqlite_stat1 SET "
3735         "tbl = CASE WHEN ?2 THEN ?3 ELSE tbl END, "
3736         "idx = CASE WHEN ?5 THEN ?6 ELSE idx END, "
3737         "stat = CASE WHEN ?8 THEN ?9 ELSE stat END  "
3738         "WHERE tbl=?1 AND idx IS "
3739         "CASE WHEN length(?4)=0 AND typeof(?4)='blob' THEN NULL ELSE ?4 END "
3740         "AND (?10 OR ?8=0 OR stat IS ?7)"
3741     );
3742   }
3743   if( rc==SQLITE_OK ){
3744     rc = sessionPrepare(db, &p->pDelete,
3745         "DELETE FROM main.sqlite_stat1 WHERE tbl=?1 AND idx IS "
3746         "CASE WHEN length(?2)=0 AND typeof(?2)='blob' THEN NULL ELSE ?2 END "
3747         "AND (?4 OR stat IS ?3)"
3748     );
3749   }
3750   return rc;
3751 }
3752 
3753 /*
3754 ** A wrapper around sqlite3_bind_value() that detects an extra problem.
3755 ** See comments in the body of this function for details.
3756 */
3757 static int sessionBindValue(
3758   sqlite3_stmt *pStmt,            /* Statement to bind value to */
3759   int i,                          /* Parameter number to bind to */
3760   sqlite3_value *pVal             /* Value to bind */
3761 ){
3762   int eType = sqlite3_value_type(pVal);
3763   /* COVERAGE: The (pVal->z==0) branch is never true using current versions
3764   ** of SQLite. If a malloc fails in an sqlite3_value_xxx() function, either
3765   ** the (pVal->z) variable remains as it was or the type of the value is
3766   ** set to SQLITE_NULL.  */
3767   if( (eType==SQLITE_TEXT || eType==SQLITE_BLOB) && pVal->z==0 ){
3768     /* This condition occurs when an earlier OOM in a call to
3769     ** sqlite3_value_text() or sqlite3_value_blob() (perhaps from within
3770     ** a conflict-handler) has zeroed the pVal->z pointer. Return NOMEM. */
3771     return SQLITE_NOMEM;
3772   }
3773   return sqlite3_bind_value(pStmt, i, pVal);
3774 }
3775 
3776 /*
3777 ** Iterator pIter must point to an SQLITE_INSERT entry. This function
3778 ** transfers new.* values from the current iterator entry to statement
3779 ** pStmt. The table being inserted into has nCol columns.
3780 **
3781 ** New.* value $i from the iterator is bound to variable ($i+1) of
3782 ** statement pStmt. If parameter abPK is NULL, all values from 0 to (nCol-1)
3783 ** are transfered to the statement. Otherwise, if abPK is not NULL, it points
3784 ** to an array nCol elements in size. In this case only those values for
3785 ** which abPK[$i] is true are read from the iterator and bound to the
3786 ** statement.
3787 **
3788 ** An SQLite error code is returned if an error occurs. Otherwise, SQLITE_OK.
3789 */
3790 static int sessionBindRow(
3791   sqlite3_changeset_iter *pIter,  /* Iterator to read values from */
3792   int(*xValue)(sqlite3_changeset_iter *, int, sqlite3_value **),
3793   int nCol,                       /* Number of columns */
3794   u8 *abPK,                       /* If not NULL, bind only if true */
3795   sqlite3_stmt *pStmt             /* Bind values to this statement */
3796 ){
3797   int i;
3798   int rc = SQLITE_OK;
3799 
3800   /* Neither sqlite3changeset_old or sqlite3changeset_new can fail if the
3801   ** argument iterator points to a suitable entry. Make sure that xValue
3802   ** is one of these to guarantee that it is safe to ignore the return
3803   ** in the code below. */
3804   assert( xValue==sqlite3changeset_old || xValue==sqlite3changeset_new );
3805 
3806   for(i=0; rc==SQLITE_OK && i<nCol; i++){
3807     if( !abPK || abPK[i] ){
3808       sqlite3_value *pVal;
3809       (void)xValue(pIter, i, &pVal);
3810       if( pVal==0 ){
3811         /* The value in the changeset was "undefined". This indicates a
3812         ** corrupt changeset blob.  */
3813         rc = SQLITE_CORRUPT_BKPT;
3814       }else{
3815         rc = sessionBindValue(pStmt, i+1, pVal);
3816       }
3817     }
3818   }
3819   return rc;
3820 }
3821 
3822 /*
3823 ** SQL statement pSelect is as generated by the sessionSelectRow() function.
3824 ** This function binds the primary key values from the change that changeset
3825 ** iterator pIter points to to the SELECT and attempts to seek to the table
3826 ** entry. If a row is found, the SELECT statement left pointing at the row
3827 ** and SQLITE_ROW is returned. Otherwise, if no row is found and no error
3828 ** has occured, the statement is reset and SQLITE_OK is returned. If an
3829 ** error occurs, the statement is reset and an SQLite error code is returned.
3830 **
3831 ** If this function returns SQLITE_ROW, the caller must eventually reset()
3832 ** statement pSelect. If any other value is returned, the statement does
3833 ** not require a reset().
3834 **
3835 ** If the iterator currently points to an INSERT record, bind values from the
3836 ** new.* record to the SELECT statement. Or, if it points to a DELETE or
3837 ** UPDATE, bind values from the old.* record.
3838 */
3839 static int sessionSeekToRow(
3840   sqlite3 *db,                    /* Database handle */
3841   sqlite3_changeset_iter *pIter,  /* Changeset iterator */
3842   u8 *abPK,                       /* Primary key flags array */
3843   sqlite3_stmt *pSelect           /* SELECT statement from sessionSelectRow() */
3844 ){
3845   int rc;                         /* Return code */
3846   int nCol;                       /* Number of columns in table */
3847   int op;                         /* Changset operation (SQLITE_UPDATE etc.) */
3848   const char *zDummy;             /* Unused */
3849 
3850   sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
3851   rc = sessionBindRow(pIter,
3852       op==SQLITE_INSERT ? sqlite3changeset_new : sqlite3changeset_old,
3853       nCol, abPK, pSelect
3854   );
3855 
3856   if( rc==SQLITE_OK ){
3857     rc = sqlite3_step(pSelect);
3858     if( rc!=SQLITE_ROW ) rc = sqlite3_reset(pSelect);
3859   }
3860 
3861   return rc;
3862 }
3863 
3864 /*
3865 ** This function is called from within sqlite3changset_apply_v2() when
3866 ** a conflict is encountered and resolved using conflict resolution
3867 ** mode eType (either SQLITE_CHANGESET_OMIT or SQLITE_CHANGESET_REPLACE)..
3868 ** It adds a conflict resolution record to the buffer in
3869 ** SessionApplyCtx.rebase, which will eventually be returned to the caller
3870 ** of apply_v2() as the "rebase" buffer.
3871 **
3872 ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
3873 */
3874 static int sessionRebaseAdd(
3875   SessionApplyCtx *p,             /* Apply context */
3876   int eType,                      /* Conflict resolution (OMIT or REPLACE) */
3877   sqlite3_changeset_iter *pIter   /* Iterator pointing at current change */
3878 ){
3879   int rc = SQLITE_OK;
3880   if( p->bRebase ){
3881     int i;
3882     int eOp = pIter->op;
3883     if( p->bRebaseStarted==0 ){
3884       /* Append a table-header to the rebase buffer */
3885       const char *zTab = pIter->zTab;
3886       sessionAppendByte(&p->rebase, 'T', &rc);
3887       sessionAppendVarint(&p->rebase, p->nCol, &rc);
3888       sessionAppendBlob(&p->rebase, p->abPK, p->nCol, &rc);
3889       sessionAppendBlob(&p->rebase, (u8*)zTab, (int)strlen(zTab)+1, &rc);
3890       p->bRebaseStarted = 1;
3891     }
3892 
3893     assert( eType==SQLITE_CHANGESET_REPLACE||eType==SQLITE_CHANGESET_OMIT );
3894     assert( eOp==SQLITE_DELETE || eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE );
3895 
3896     sessionAppendByte(&p->rebase,
3897         (eOp==SQLITE_DELETE ? SQLITE_DELETE : SQLITE_INSERT), &rc
3898         );
3899     sessionAppendByte(&p->rebase, (eType==SQLITE_CHANGESET_REPLACE), &rc);
3900     for(i=0; i<p->nCol; i++){
3901       sqlite3_value *pVal = 0;
3902       if( eOp==SQLITE_DELETE || (eOp==SQLITE_UPDATE && p->abPK[i]) ){
3903         sqlite3changeset_old(pIter, i, &pVal);
3904       }else{
3905         sqlite3changeset_new(pIter, i, &pVal);
3906       }
3907       sessionAppendValue(&p->rebase, pVal, &rc);
3908     }
3909   }
3910   return rc;
3911 }
3912 
3913 /*
3914 ** Invoke the conflict handler for the change that the changeset iterator
3915 ** currently points to.
3916 **
3917 ** Argument eType must be either CHANGESET_DATA or CHANGESET_CONFLICT.
3918 ** If argument pbReplace is NULL, then the type of conflict handler invoked
3919 ** depends solely on eType, as follows:
3920 **
3921 **    eType value                 Value passed to xConflict
3922 **    -------------------------------------------------
3923 **    CHANGESET_DATA              CHANGESET_NOTFOUND
3924 **    CHANGESET_CONFLICT          CHANGESET_CONSTRAINT
3925 **
3926 ** Or, if pbReplace is not NULL, then an attempt is made to find an existing
3927 ** record with the same primary key as the record about to be deleted, updated
3928 ** or inserted. If such a record can be found, it is available to the conflict
3929 ** handler as the "conflicting" record. In this case the type of conflict
3930 ** handler invoked is as follows:
3931 **
3932 **    eType value         PK Record found?   Value passed to xConflict
3933 **    ----------------------------------------------------------------
3934 **    CHANGESET_DATA      Yes                CHANGESET_DATA
3935 **    CHANGESET_DATA      No                 CHANGESET_NOTFOUND
3936 **    CHANGESET_CONFLICT  Yes                CHANGESET_CONFLICT
3937 **    CHANGESET_CONFLICT  No                 CHANGESET_CONSTRAINT
3938 **
3939 ** If pbReplace is not NULL, and a record with a matching PK is found, and
3940 ** the conflict handler function returns SQLITE_CHANGESET_REPLACE, *pbReplace
3941 ** is set to non-zero before returning SQLITE_OK.
3942 **
3943 ** If the conflict handler returns SQLITE_CHANGESET_ABORT, SQLITE_ABORT is
3944 ** returned. Or, if the conflict handler returns an invalid value,
3945 ** SQLITE_MISUSE. If the conflict handler returns SQLITE_CHANGESET_OMIT,
3946 ** this function returns SQLITE_OK.
3947 */
3948 static int sessionConflictHandler(
3949   int eType,                      /* Either CHANGESET_DATA or CONFLICT */
3950   SessionApplyCtx *p,             /* changeset_apply() context */
3951   sqlite3_changeset_iter *pIter,  /* Changeset iterator */
3952   int(*xConflict)(void *, int, sqlite3_changeset_iter*),
3953   void *pCtx,                     /* First argument for conflict handler */
3954   int *pbReplace                  /* OUT: Set to true if PK row is found */
3955 ){
3956   int res = 0;                    /* Value returned by conflict handler */
3957   int rc;
3958   int nCol;
3959   int op;
3960   const char *zDummy;
3961 
3962   sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
3963 
3964   assert( eType==SQLITE_CHANGESET_CONFLICT || eType==SQLITE_CHANGESET_DATA );
3965   assert( SQLITE_CHANGESET_CONFLICT+1==SQLITE_CHANGESET_CONSTRAINT );
3966   assert( SQLITE_CHANGESET_DATA+1==SQLITE_CHANGESET_NOTFOUND );
3967 
3968   /* Bind the new.* PRIMARY KEY values to the SELECT statement. */
3969   if( pbReplace ){
3970     rc = sessionSeekToRow(p->db, pIter, p->abPK, p->pSelect);
3971   }else{
3972     rc = SQLITE_OK;
3973   }
3974 
3975   if( rc==SQLITE_ROW ){
3976     /* There exists another row with the new.* primary key. */
3977     pIter->pConflict = p->pSelect;
3978     res = xConflict(pCtx, eType, pIter);
3979     pIter->pConflict = 0;
3980     rc = sqlite3_reset(p->pSelect);
3981   }else if( rc==SQLITE_OK ){
3982     if( p->bDeferConstraints && eType==SQLITE_CHANGESET_CONFLICT ){
3983       /* Instead of invoking the conflict handler, append the change blob
3984       ** to the SessionApplyCtx.constraints buffer. */
3985       u8 *aBlob = &pIter->in.aData[pIter->in.iCurrent];
3986       int nBlob = pIter->in.iNext - pIter->in.iCurrent;
3987       sessionAppendBlob(&p->constraints, aBlob, nBlob, &rc);
3988       return SQLITE_OK;
3989     }else{
3990       /* No other row with the new.* primary key. */
3991       res = xConflict(pCtx, eType+1, pIter);
3992       if( res==SQLITE_CHANGESET_REPLACE ) rc = SQLITE_MISUSE;
3993     }
3994   }
3995 
3996   if( rc==SQLITE_OK ){
3997     switch( res ){
3998       case SQLITE_CHANGESET_REPLACE:
3999         assert( pbReplace );
4000         *pbReplace = 1;
4001         break;
4002 
4003       case SQLITE_CHANGESET_OMIT:
4004         break;
4005 
4006       case SQLITE_CHANGESET_ABORT:
4007         rc = SQLITE_ABORT;
4008         break;
4009 
4010       default:
4011         rc = SQLITE_MISUSE;
4012         break;
4013     }
4014     if( rc==SQLITE_OK ){
4015       rc = sessionRebaseAdd(p, res, pIter);
4016     }
4017   }
4018 
4019   return rc;
4020 }
4021 
4022 /*
4023 ** Attempt to apply the change that the iterator passed as the first argument
4024 ** currently points to to the database. If a conflict is encountered, invoke
4025 ** the conflict handler callback.
4026 **
4027 ** If argument pbRetry is NULL, then ignore any CHANGESET_DATA conflict. If
4028 ** one is encountered, update or delete the row with the matching primary key
4029 ** instead. Or, if pbRetry is not NULL and a CHANGESET_DATA conflict occurs,
4030 ** invoke the conflict handler. If it returns CHANGESET_REPLACE, set *pbRetry
4031 ** to true before returning. In this case the caller will invoke this function
4032 ** again, this time with pbRetry set to NULL.
4033 **
4034 ** If argument pbReplace is NULL and a CHANGESET_CONFLICT conflict is
4035 ** encountered invoke the conflict handler with CHANGESET_CONSTRAINT instead.
4036 ** Or, if pbReplace is not NULL, invoke it with CHANGESET_CONFLICT. If such
4037 ** an invocation returns SQLITE_CHANGESET_REPLACE, set *pbReplace to true
4038 ** before retrying. In this case the caller attempts to remove the conflicting
4039 ** row before invoking this function again, this time with pbReplace set
4040 ** to NULL.
4041 **
4042 ** If any conflict handler returns SQLITE_CHANGESET_ABORT, this function
4043 ** returns SQLITE_ABORT. Otherwise, if no error occurs, SQLITE_OK is
4044 ** returned.
4045 */
4046 static int sessionApplyOneOp(
4047   sqlite3_changeset_iter *pIter,  /* Changeset iterator */
4048   SessionApplyCtx *p,             /* changeset_apply() context */
4049   int(*xConflict)(void *, int, sqlite3_changeset_iter *),
4050   void *pCtx,                     /* First argument for the conflict handler */
4051   int *pbReplace,                 /* OUT: True to remove PK row and retry */
4052   int *pbRetry                    /* OUT: True to retry. */
4053 ){
4054   const char *zDummy;
4055   int op;
4056   int nCol;
4057   int rc = SQLITE_OK;
4058 
4059   assert( p->pDelete && p->pUpdate && p->pInsert && p->pSelect );
4060   assert( p->azCol && p->abPK );
4061   assert( !pbReplace || *pbReplace==0 );
4062 
4063   sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
4064 
4065   if( op==SQLITE_DELETE ){
4066 
4067     /* Bind values to the DELETE statement. If conflict handling is required,
4068     ** bind values for all columns and set bound variable (nCol+1) to true.
4069     ** Or, if conflict handling is not required, bind just the PK column
4070     ** values and, if it exists, set (nCol+1) to false. Conflict handling
4071     ** is not required if:
4072     **
4073     **   * this is a patchset, or
4074     **   * (pbRetry==0), or
4075     **   * all columns of the table are PK columns (in this case there is
4076     **     no (nCol+1) variable to bind to).
4077     */
4078     u8 *abPK = (pIter->bPatchset ? p->abPK : 0);
4079     rc = sessionBindRow(pIter, sqlite3changeset_old, nCol, abPK, p->pDelete);
4080     if( rc==SQLITE_OK && sqlite3_bind_parameter_count(p->pDelete)>nCol ){
4081       rc = sqlite3_bind_int(p->pDelete, nCol+1, (pbRetry==0 || abPK));
4082     }
4083     if( rc!=SQLITE_OK ) return rc;
4084 
4085     sqlite3_step(p->pDelete);
4086     rc = sqlite3_reset(p->pDelete);
4087     if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
4088       rc = sessionConflictHandler(
4089           SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
4090       );
4091     }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
4092       rc = sessionConflictHandler(
4093           SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
4094       );
4095     }
4096 
4097   }else if( op==SQLITE_UPDATE ){
4098     int i;
4099 
4100     /* Bind values to the UPDATE statement. */
4101     for(i=0; rc==SQLITE_OK && i<nCol; i++){
4102       sqlite3_value *pOld = sessionChangesetOld(pIter, i);
4103       sqlite3_value *pNew = sessionChangesetNew(pIter, i);
4104 
4105       sqlite3_bind_int(p->pUpdate, i*3+2, !!pNew);
4106       if( pOld ){
4107         rc = sessionBindValue(p->pUpdate, i*3+1, pOld);
4108       }
4109       if( rc==SQLITE_OK && pNew ){
4110         rc = sessionBindValue(p->pUpdate, i*3+3, pNew);
4111       }
4112     }
4113     if( rc==SQLITE_OK ){
4114       sqlite3_bind_int(p->pUpdate, nCol*3+1, pbRetry==0 || pIter->bPatchset);
4115     }
4116     if( rc!=SQLITE_OK ) return rc;
4117 
4118     /* Attempt the UPDATE. In the case of a NOTFOUND or DATA conflict,
4119     ** the result will be SQLITE_OK with 0 rows modified. */
4120     sqlite3_step(p->pUpdate);
4121     rc = sqlite3_reset(p->pUpdate);
4122 
4123     if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
4124       /* A NOTFOUND or DATA error. Search the table to see if it contains
4125       ** a row with a matching primary key. If so, this is a DATA conflict.
4126       ** Otherwise, if there is no primary key match, it is a NOTFOUND. */
4127 
4128       rc = sessionConflictHandler(
4129           SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
4130       );
4131 
4132     }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
4133       /* This is always a CONSTRAINT conflict. */
4134       rc = sessionConflictHandler(
4135           SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
4136       );
4137     }
4138 
4139   }else{
4140     assert( op==SQLITE_INSERT );
4141     if( p->bStat1 ){
4142       /* Check if there is a conflicting row. For sqlite_stat1, this needs
4143       ** to be done using a SELECT, as there is no PRIMARY KEY in the
4144       ** database schema to throw an exception if a duplicate is inserted.  */
4145       rc = sessionSeekToRow(p->db, pIter, p->abPK, p->pSelect);
4146       if( rc==SQLITE_ROW ){
4147         rc = SQLITE_CONSTRAINT;
4148         sqlite3_reset(p->pSelect);
4149       }
4150     }
4151 
4152     if( rc==SQLITE_OK ){
4153       rc = sessionBindRow(pIter, sqlite3changeset_new, nCol, 0, p->pInsert);
4154       if( rc!=SQLITE_OK ) return rc;
4155 
4156       sqlite3_step(p->pInsert);
4157       rc = sqlite3_reset(p->pInsert);
4158     }
4159 
4160     if( (rc&0xff)==SQLITE_CONSTRAINT ){
4161       rc = sessionConflictHandler(
4162           SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, pbReplace
4163       );
4164     }
4165   }
4166 
4167   return rc;
4168 }
4169 
4170 /*
4171 ** Attempt to apply the change that the iterator passed as the first argument
4172 ** currently points to to the database. If a conflict is encountered, invoke
4173 ** the conflict handler callback.
4174 **
4175 ** The difference between this function and sessionApplyOne() is that this
4176 ** function handles the case where the conflict-handler is invoked and
4177 ** returns SQLITE_CHANGESET_REPLACE - indicating that the change should be
4178 ** retried in some manner.
4179 */
4180 static int sessionApplyOneWithRetry(
4181   sqlite3 *db,                    /* Apply change to "main" db of this handle */
4182   sqlite3_changeset_iter *pIter,  /* Changeset iterator to read change from */
4183   SessionApplyCtx *pApply,        /* Apply context */
4184   int(*xConflict)(void*, int, sqlite3_changeset_iter*),
4185   void *pCtx                      /* First argument passed to xConflict */
4186 ){
4187   int bReplace = 0;
4188   int bRetry = 0;
4189   int rc;
4190 
4191   rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, &bReplace, &bRetry);
4192   if( rc==SQLITE_OK ){
4193     /* If the bRetry flag is set, the change has not been applied due to an
4194     ** SQLITE_CHANGESET_DATA problem (i.e. this is an UPDATE or DELETE and
4195     ** a row with the correct PK is present in the db, but one or more other
4196     ** fields do not contain the expected values) and the conflict handler
4197     ** returned SQLITE_CHANGESET_REPLACE. In this case retry the operation,
4198     ** but pass NULL as the final argument so that sessionApplyOneOp() ignores
4199     ** the SQLITE_CHANGESET_DATA problem.  */
4200     if( bRetry ){
4201       assert( pIter->op==SQLITE_UPDATE || pIter->op==SQLITE_DELETE );
4202       rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
4203     }
4204 
4205     /* If the bReplace flag is set, the change is an INSERT that has not
4206     ** been performed because the database already contains a row with the
4207     ** specified primary key and the conflict handler returned
4208     ** SQLITE_CHANGESET_REPLACE. In this case remove the conflicting row
4209     ** before reattempting the INSERT.  */
4210     else if( bReplace ){
4211       assert( pIter->op==SQLITE_INSERT );
4212       rc = sqlite3_exec(db, "SAVEPOINT replace_op", 0, 0, 0);
4213       if( rc==SQLITE_OK ){
4214         rc = sessionBindRow(pIter,
4215             sqlite3changeset_new, pApply->nCol, pApply->abPK, pApply->pDelete);
4216         sqlite3_bind_int(pApply->pDelete, pApply->nCol+1, 1);
4217       }
4218       if( rc==SQLITE_OK ){
4219         sqlite3_step(pApply->pDelete);
4220         rc = sqlite3_reset(pApply->pDelete);
4221       }
4222       if( rc==SQLITE_OK ){
4223         rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
4224       }
4225       if( rc==SQLITE_OK ){
4226         rc = sqlite3_exec(db, "RELEASE replace_op", 0, 0, 0);
4227       }
4228     }
4229   }
4230 
4231   return rc;
4232 }
4233 
4234 /*
4235 ** Retry the changes accumulated in the pApply->constraints buffer.
4236 */
4237 static int sessionRetryConstraints(
4238   sqlite3 *db,
4239   int bPatchset,
4240   const char *zTab,
4241   SessionApplyCtx *pApply,
4242   int(*xConflict)(void*, int, sqlite3_changeset_iter*),
4243   void *pCtx                      /* First argument passed to xConflict */
4244 ){
4245   int rc = SQLITE_OK;
4246 
4247   while( pApply->constraints.nBuf ){
4248     sqlite3_changeset_iter *pIter2 = 0;
4249     SessionBuffer cons = pApply->constraints;
4250     memset(&pApply->constraints, 0, sizeof(SessionBuffer));
4251 
4252     rc = sessionChangesetStart(&pIter2, 0, 0, cons.nBuf, cons.aBuf, 0);
4253     if( rc==SQLITE_OK ){
4254       int nByte = 2*pApply->nCol*sizeof(sqlite3_value*);
4255       int rc2;
4256       pIter2->bPatchset = bPatchset;
4257       pIter2->zTab = (char*)zTab;
4258       pIter2->nCol = pApply->nCol;
4259       pIter2->abPK = pApply->abPK;
4260       sessionBufferGrow(&pIter2->tblhdr, nByte, &rc);
4261       pIter2->apValue = (sqlite3_value**)pIter2->tblhdr.aBuf;
4262       if( rc==SQLITE_OK ) memset(pIter2->apValue, 0, nByte);
4263 
4264       while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter2) ){
4265         rc = sessionApplyOneWithRetry(db, pIter2, pApply, xConflict, pCtx);
4266       }
4267 
4268       rc2 = sqlite3changeset_finalize(pIter2);
4269       if( rc==SQLITE_OK ) rc = rc2;
4270     }
4271     assert( pApply->bDeferConstraints || pApply->constraints.nBuf==0 );
4272 
4273     sqlite3_free(cons.aBuf);
4274     if( rc!=SQLITE_OK ) break;
4275     if( pApply->constraints.nBuf>=cons.nBuf ){
4276       /* No progress was made on the last round. */
4277       pApply->bDeferConstraints = 0;
4278     }
4279   }
4280 
4281   return rc;
4282 }
4283 
4284 /*
4285 ** Argument pIter is a changeset iterator that has been initialized, but
4286 ** not yet passed to sqlite3changeset_next(). This function applies the
4287 ** changeset to the main database attached to handle "db". The supplied
4288 ** conflict handler callback is invoked to resolve any conflicts encountered
4289 ** while applying the change.
4290 */
4291 static int sessionChangesetApply(
4292   sqlite3 *db,                    /* Apply change to "main" db of this handle */
4293   sqlite3_changeset_iter *pIter,  /* Changeset to apply */
4294   int(*xFilter)(
4295     void *pCtx,                   /* Copy of sixth arg to _apply() */
4296     const char *zTab              /* Table name */
4297   ),
4298   int(*xConflict)(
4299     void *pCtx,                   /* Copy of fifth arg to _apply() */
4300     int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
4301     sqlite3_changeset_iter *p     /* Handle describing change and conflict */
4302   ),
4303   void *pCtx,                     /* First argument passed to xConflict */
4304   void **ppRebase, int *pnRebase, /* OUT: Rebase information */
4305   int flags                       /* SESSION_APPLY_XXX flags */
4306 ){
4307   int schemaMismatch = 0;
4308   int rc = SQLITE_OK;             /* Return code */
4309   const char *zTab = 0;           /* Name of current table */
4310   int nTab = 0;                   /* Result of sqlite3Strlen30(zTab) */
4311   SessionApplyCtx sApply;         /* changeset_apply() context object */
4312   int bPatchset;
4313 
4314   assert( xConflict!=0 );
4315 
4316   pIter->in.bNoDiscard = 1;
4317   memset(&sApply, 0, sizeof(sApply));
4318   sApply.bRebase = (ppRebase && pnRebase);
4319   sqlite3_mutex_enter(sqlite3_db_mutex(db));
4320   if( (flags & SQLITE_CHANGESETAPPLY_NOSAVEPOINT)==0 ){
4321     rc = sqlite3_exec(db, "SAVEPOINT changeset_apply", 0, 0, 0);
4322   }
4323   if( rc==SQLITE_OK ){
4324     rc = sqlite3_exec(db, "PRAGMA defer_foreign_keys = 1", 0, 0, 0);
4325   }
4326   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter) ){
4327     int nCol;
4328     int op;
4329     const char *zNew;
4330 
4331     sqlite3changeset_op(pIter, &zNew, &nCol, &op, 0);
4332 
4333     if( zTab==0 || sqlite3_strnicmp(zNew, zTab, nTab+1) ){
4334       u8 *abPK;
4335 
4336       rc = sessionRetryConstraints(
4337           db, pIter->bPatchset, zTab, &sApply, xConflict, pCtx
4338       );
4339       if( rc!=SQLITE_OK ) break;
4340 
4341       sqlite3_free((char*)sApply.azCol);  /* cast works around VC++ bug */
4342       sqlite3_finalize(sApply.pDelete);
4343       sqlite3_finalize(sApply.pUpdate);
4344       sqlite3_finalize(sApply.pInsert);
4345       sqlite3_finalize(sApply.pSelect);
4346       sApply.db = db;
4347       sApply.pDelete = 0;
4348       sApply.pUpdate = 0;
4349       sApply.pInsert = 0;
4350       sApply.pSelect = 0;
4351       sApply.nCol = 0;
4352       sApply.azCol = 0;
4353       sApply.abPK = 0;
4354       sApply.bStat1 = 0;
4355       sApply.bDeferConstraints = 1;
4356       sApply.bRebaseStarted = 0;
4357       memset(&sApply.constraints, 0, sizeof(SessionBuffer));
4358 
4359       /* If an xFilter() callback was specified, invoke it now. If the
4360       ** xFilter callback returns zero, skip this table. If it returns
4361       ** non-zero, proceed. */
4362       schemaMismatch = (xFilter && (0==xFilter(pCtx, zNew)));
4363       if( schemaMismatch ){
4364         zTab = sqlite3_mprintf("%s", zNew);
4365         if( zTab==0 ){
4366           rc = SQLITE_NOMEM;
4367           break;
4368         }
4369         nTab = (int)strlen(zTab);
4370         sApply.azCol = (const char **)zTab;
4371       }else{
4372         int nMinCol = 0;
4373         int i;
4374 
4375         sqlite3changeset_pk(pIter, &abPK, 0);
4376         rc = sessionTableInfo(
4377             db, "main", zNew, &sApply.nCol, &zTab, &sApply.azCol, &sApply.abPK
4378         );
4379         if( rc!=SQLITE_OK ) break;
4380         for(i=0; i<sApply.nCol; i++){
4381           if( sApply.abPK[i] ) nMinCol = i+1;
4382         }
4383 
4384         if( sApply.nCol==0 ){
4385           schemaMismatch = 1;
4386           sqlite3_log(SQLITE_SCHEMA,
4387               "sqlite3changeset_apply(): no such table: %s", zTab
4388           );
4389         }
4390         else if( sApply.nCol<nCol ){
4391           schemaMismatch = 1;
4392           sqlite3_log(SQLITE_SCHEMA,
4393               "sqlite3changeset_apply(): table %s has %d columns, "
4394               "expected %d or more",
4395               zTab, sApply.nCol, nCol
4396           );
4397         }
4398         else if( nCol<nMinCol || memcmp(sApply.abPK, abPK, nCol)!=0 ){
4399           schemaMismatch = 1;
4400           sqlite3_log(SQLITE_SCHEMA, "sqlite3changeset_apply(): "
4401               "primary key mismatch for table %s", zTab
4402           );
4403         }
4404         else{
4405           sApply.nCol = nCol;
4406           if( 0==sqlite3_stricmp(zTab, "sqlite_stat1") ){
4407             if( (rc = sessionStat1Sql(db, &sApply) ) ){
4408               break;
4409             }
4410             sApply.bStat1 = 1;
4411           }else{
4412             if((rc = sessionSelectRow(db, zTab, &sApply))
4413                 || (rc = sessionUpdateRow(db, zTab, &sApply))
4414                 || (rc = sessionDeleteRow(db, zTab, &sApply))
4415                 || (rc = sessionInsertRow(db, zTab, &sApply))
4416               ){
4417               break;
4418             }
4419             sApply.bStat1 = 0;
4420           }
4421         }
4422         nTab = sqlite3Strlen30(zTab);
4423       }
4424     }
4425 
4426     /* If there is a schema mismatch on the current table, proceed to the
4427     ** next change. A log message has already been issued. */
4428     if( schemaMismatch ) continue;
4429 
4430     rc = sessionApplyOneWithRetry(db, pIter, &sApply, xConflict, pCtx);
4431   }
4432 
4433   bPatchset = pIter->bPatchset;
4434   if( rc==SQLITE_OK ){
4435     rc = sqlite3changeset_finalize(pIter);
4436   }else{
4437     sqlite3changeset_finalize(pIter);
4438   }
4439 
4440   if( rc==SQLITE_OK ){
4441     rc = sessionRetryConstraints(db, bPatchset, zTab, &sApply, xConflict, pCtx);
4442   }
4443 
4444   if( rc==SQLITE_OK ){
4445     int nFk, notUsed;
4446     sqlite3_db_status(db, SQLITE_DBSTATUS_DEFERRED_FKS, &nFk, &notUsed, 0);
4447     if( nFk!=0 ){
4448       int res = SQLITE_CHANGESET_ABORT;
4449       sqlite3_changeset_iter sIter;
4450       memset(&sIter, 0, sizeof(sIter));
4451       sIter.nCol = nFk;
4452       res = xConflict(pCtx, SQLITE_CHANGESET_FOREIGN_KEY, &sIter);
4453       if( res!=SQLITE_CHANGESET_OMIT ){
4454         rc = SQLITE_CONSTRAINT;
4455       }
4456     }
4457   }
4458   sqlite3_exec(db, "PRAGMA defer_foreign_keys = 0", 0, 0, 0);
4459 
4460   if( (flags & SQLITE_CHANGESETAPPLY_NOSAVEPOINT)==0 ){
4461     if( rc==SQLITE_OK ){
4462       rc = sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
4463     }else{
4464       sqlite3_exec(db, "ROLLBACK TO changeset_apply", 0, 0, 0);
4465       sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
4466     }
4467   }
4468 
4469   assert( sApply.bRebase || sApply.rebase.nBuf==0 );
4470   if( rc==SQLITE_OK && bPatchset==0 && sApply.bRebase ){
4471     *ppRebase = (void*)sApply.rebase.aBuf;
4472     *pnRebase = sApply.rebase.nBuf;
4473     sApply.rebase.aBuf = 0;
4474   }
4475   sqlite3_finalize(sApply.pInsert);
4476   sqlite3_finalize(sApply.pDelete);
4477   sqlite3_finalize(sApply.pUpdate);
4478   sqlite3_finalize(sApply.pSelect);
4479   sqlite3_free((char*)sApply.azCol);  /* cast works around VC++ bug */
4480   sqlite3_free((char*)sApply.constraints.aBuf);
4481   sqlite3_free((char*)sApply.rebase.aBuf);
4482   sqlite3_mutex_leave(sqlite3_db_mutex(db));
4483   return rc;
4484 }
4485 
4486 /*
4487 ** Apply the changeset passed via pChangeset/nChangeset to the main
4488 ** database attached to handle "db".
4489 */
4490 int sqlite3changeset_apply_v2(
4491   sqlite3 *db,                    /* Apply change to "main" db of this handle */
4492   int nChangeset,                 /* Size of changeset in bytes */
4493   void *pChangeset,               /* Changeset blob */
4494   int(*xFilter)(
4495     void *pCtx,                   /* Copy of sixth arg to _apply() */
4496     const char *zTab              /* Table name */
4497   ),
4498   int(*xConflict)(
4499     void *pCtx,                   /* Copy of sixth arg to _apply() */
4500     int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
4501     sqlite3_changeset_iter *p     /* Handle describing change and conflict */
4502   ),
4503   void *pCtx,                     /* First argument passed to xConflict */
4504   void **ppRebase, int *pnRebase,
4505   int flags
4506 ){
4507   sqlite3_changeset_iter *pIter;  /* Iterator to skip through changeset */
4508   int bInverse = !!(flags & SQLITE_CHANGESETAPPLY_INVERT);
4509   int rc = sessionChangesetStart(&pIter, 0, 0, nChangeset, pChangeset,bInverse);
4510   if( rc==SQLITE_OK ){
4511     rc = sessionChangesetApply(
4512         db, pIter, xFilter, xConflict, pCtx, ppRebase, pnRebase, flags
4513     );
4514   }
4515   return rc;
4516 }
4517 
4518 /*
4519 ** Apply the changeset passed via pChangeset/nChangeset to the main database
4520 ** attached to handle "db". Invoke the supplied conflict handler callback
4521 ** to resolve any conflicts encountered while applying the change.
4522 */
4523 int sqlite3changeset_apply(
4524   sqlite3 *db,                    /* Apply change to "main" db of this handle */
4525   int nChangeset,                 /* Size of changeset in bytes */
4526   void *pChangeset,               /* Changeset blob */
4527   int(*xFilter)(
4528     void *pCtx,                   /* Copy of sixth arg to _apply() */
4529     const char *zTab              /* Table name */
4530   ),
4531   int(*xConflict)(
4532     void *pCtx,                   /* Copy of fifth arg to _apply() */
4533     int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
4534     sqlite3_changeset_iter *p     /* Handle describing change and conflict */
4535   ),
4536   void *pCtx                      /* First argument passed to xConflict */
4537 ){
4538   return sqlite3changeset_apply_v2(
4539       db, nChangeset, pChangeset, xFilter, xConflict, pCtx, 0, 0, 0
4540   );
4541 }
4542 
4543 /*
4544 ** Apply the changeset passed via xInput/pIn to the main database
4545 ** attached to handle "db". Invoke the supplied conflict handler callback
4546 ** to resolve any conflicts encountered while applying the change.
4547 */
4548 int sqlite3changeset_apply_v2_strm(
4549   sqlite3 *db,                    /* Apply change to "main" db of this handle */
4550   int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
4551   void *pIn,                                          /* First arg for xInput */
4552   int(*xFilter)(
4553     void *pCtx,                   /* Copy of sixth arg to _apply() */
4554     const char *zTab              /* Table name */
4555   ),
4556   int(*xConflict)(
4557     void *pCtx,                   /* Copy of sixth arg to _apply() */
4558     int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
4559     sqlite3_changeset_iter *p     /* Handle describing change and conflict */
4560   ),
4561   void *pCtx,                     /* First argument passed to xConflict */
4562   void **ppRebase, int *pnRebase,
4563   int flags
4564 ){
4565   sqlite3_changeset_iter *pIter;  /* Iterator to skip through changeset */
4566   int bInverse = !!(flags & SQLITE_CHANGESETAPPLY_INVERT);
4567   int rc = sessionChangesetStart(&pIter, xInput, pIn, 0, 0, bInverse);
4568   if( rc==SQLITE_OK ){
4569     rc = sessionChangesetApply(
4570         db, pIter, xFilter, xConflict, pCtx, ppRebase, pnRebase, flags
4571     );
4572   }
4573   return rc;
4574 }
4575 int sqlite3changeset_apply_strm(
4576   sqlite3 *db,                    /* Apply change to "main" db of this handle */
4577   int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
4578   void *pIn,                                          /* First arg for xInput */
4579   int(*xFilter)(
4580     void *pCtx,                   /* Copy of sixth arg to _apply() */
4581     const char *zTab              /* Table name */
4582   ),
4583   int(*xConflict)(
4584     void *pCtx,                   /* Copy of sixth arg to _apply() */
4585     int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
4586     sqlite3_changeset_iter *p     /* Handle describing change and conflict */
4587   ),
4588   void *pCtx                      /* First argument passed to xConflict */
4589 ){
4590   return sqlite3changeset_apply_v2_strm(
4591       db, xInput, pIn, xFilter, xConflict, pCtx, 0, 0, 0
4592   );
4593 }
4594 
4595 /*
4596 ** sqlite3_changegroup handle.
4597 */
4598 struct sqlite3_changegroup {
4599   int rc;                         /* Error code */
4600   int bPatch;                     /* True to accumulate patchsets */
4601   SessionTable *pList;            /* List of tables in current patch */
4602 };
4603 
4604 /*
4605 ** This function is called to merge two changes to the same row together as
4606 ** part of an sqlite3changeset_concat() operation. A new change object is
4607 ** allocated and a pointer to it stored in *ppNew.
4608 */
4609 static int sessionChangeMerge(
4610   SessionTable *pTab,             /* Table structure */
4611   int bRebase,                    /* True for a rebase hash-table */
4612   int bPatchset,                  /* True for patchsets */
4613   SessionChange *pExist,          /* Existing change */
4614   int op2,                        /* Second change operation */
4615   int bIndirect,                  /* True if second change is indirect */
4616   u8 *aRec,                       /* Second change record */
4617   int nRec,                       /* Number of bytes in aRec */
4618   SessionChange **ppNew           /* OUT: Merged change */
4619 ){
4620   SessionChange *pNew = 0;
4621   int rc = SQLITE_OK;
4622 
4623   if( !pExist ){
4624     pNew = (SessionChange *)sqlite3_malloc(sizeof(SessionChange) + nRec);
4625     if( !pNew ){
4626       return SQLITE_NOMEM;
4627     }
4628     memset(pNew, 0, sizeof(SessionChange));
4629     pNew->op = op2;
4630     pNew->bIndirect = bIndirect;
4631     pNew->aRecord = (u8*)&pNew[1];
4632     if( bIndirect==0 || bRebase==0 ){
4633       pNew->nRecord = nRec;
4634       memcpy(pNew->aRecord, aRec, nRec);
4635     }else{
4636       int i;
4637       u8 *pIn = aRec;
4638       u8 *pOut = pNew->aRecord;
4639       for(i=0; i<pTab->nCol; i++){
4640         int nIn = sessionSerialLen(pIn);
4641         if( *pIn==0 ){
4642           *pOut++ = 0;
4643         }else if( pTab->abPK[i]==0 ){
4644           *pOut++ = 0xFF;
4645         }else{
4646           memcpy(pOut, pIn, nIn);
4647           pOut += nIn;
4648         }
4649         pIn += nIn;
4650       }
4651       pNew->nRecord = pOut - pNew->aRecord;
4652     }
4653   }else if( bRebase ){
4654     if( pExist->op==SQLITE_DELETE && pExist->bIndirect ){
4655       *ppNew = pExist;
4656     }else{
4657       int nByte = nRec + pExist->nRecord + sizeof(SessionChange);
4658       pNew = (SessionChange*)sqlite3_malloc(nByte);
4659       if( pNew==0 ){
4660         rc = SQLITE_NOMEM;
4661       }else{
4662         int i;
4663         u8 *a1 = pExist->aRecord;
4664         u8 *a2 = aRec;
4665         u8 *pOut;
4666 
4667         memset(pNew, 0, nByte);
4668         pNew->bIndirect = bIndirect || pExist->bIndirect;
4669         pNew->op = op2;
4670         pOut = pNew->aRecord = (u8*)&pNew[1];
4671 
4672         for(i=0; i<pTab->nCol; i++){
4673           int n1 = sessionSerialLen(a1);
4674           int n2 = sessionSerialLen(a2);
4675           if( *a1==0xFF || (pTab->abPK[i]==0 && bIndirect) ){
4676             *pOut++ = 0xFF;
4677           }else if( *a2==0 ){
4678             memcpy(pOut, a1, n1);
4679             pOut += n1;
4680           }else{
4681             memcpy(pOut, a2, n2);
4682             pOut += n2;
4683           }
4684           a1 += n1;
4685           a2 += n2;
4686         }
4687         pNew->nRecord = pOut - pNew->aRecord;
4688       }
4689       sqlite3_free(pExist);
4690     }
4691   }else{
4692     int op1 = pExist->op;
4693 
4694     /*
4695     **   op1=INSERT, op2=INSERT      ->      Unsupported. Discard op2.
4696     **   op1=INSERT, op2=UPDATE      ->      INSERT.
4697     **   op1=INSERT, op2=DELETE      ->      (none)
4698     **
4699     **   op1=UPDATE, op2=INSERT      ->      Unsupported. Discard op2.
4700     **   op1=UPDATE, op2=UPDATE      ->      UPDATE.
4701     **   op1=UPDATE, op2=DELETE      ->      DELETE.
4702     **
4703     **   op1=DELETE, op2=INSERT      ->      UPDATE.
4704     **   op1=DELETE, op2=UPDATE      ->      Unsupported. Discard op2.
4705     **   op1=DELETE, op2=DELETE      ->      Unsupported. Discard op2.
4706     */
4707     if( (op1==SQLITE_INSERT && op2==SQLITE_INSERT)
4708      || (op1==SQLITE_UPDATE && op2==SQLITE_INSERT)
4709      || (op1==SQLITE_DELETE && op2==SQLITE_UPDATE)
4710      || (op1==SQLITE_DELETE && op2==SQLITE_DELETE)
4711     ){
4712       pNew = pExist;
4713     }else if( op1==SQLITE_INSERT && op2==SQLITE_DELETE ){
4714       sqlite3_free(pExist);
4715       assert( pNew==0 );
4716     }else{
4717       u8 *aExist = pExist->aRecord;
4718       int nByte;
4719       u8 *aCsr;
4720 
4721       /* Allocate a new SessionChange object. Ensure that the aRecord[]
4722       ** buffer of the new object is large enough to hold any record that
4723       ** may be generated by combining the input records.  */
4724       nByte = sizeof(SessionChange) + pExist->nRecord + nRec;
4725       pNew = (SessionChange *)sqlite3_malloc(nByte);
4726       if( !pNew ){
4727         sqlite3_free(pExist);
4728         return SQLITE_NOMEM;
4729       }
4730       memset(pNew, 0, sizeof(SessionChange));
4731       pNew->bIndirect = (bIndirect && pExist->bIndirect);
4732       aCsr = pNew->aRecord = (u8 *)&pNew[1];
4733 
4734       if( op1==SQLITE_INSERT ){             /* INSERT + UPDATE */
4735         u8 *a1 = aRec;
4736         assert( op2==SQLITE_UPDATE );
4737         pNew->op = SQLITE_INSERT;
4738         if( bPatchset==0 ) sessionSkipRecord(&a1, pTab->nCol);
4739         sessionMergeRecord(&aCsr, pTab->nCol, aExist, a1);
4740       }else if( op1==SQLITE_DELETE ){       /* DELETE + INSERT */
4741         assert( op2==SQLITE_INSERT );
4742         pNew->op = SQLITE_UPDATE;
4743         if( bPatchset ){
4744           memcpy(aCsr, aRec, nRec);
4745           aCsr += nRec;
4746         }else{
4747           if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aExist, 0,aRec,0) ){
4748             sqlite3_free(pNew);
4749             pNew = 0;
4750           }
4751         }
4752       }else if( op2==SQLITE_UPDATE ){       /* UPDATE + UPDATE */
4753         u8 *a1 = aExist;
4754         u8 *a2 = aRec;
4755         assert( op1==SQLITE_UPDATE );
4756         if( bPatchset==0 ){
4757           sessionSkipRecord(&a1, pTab->nCol);
4758           sessionSkipRecord(&a2, pTab->nCol);
4759         }
4760         pNew->op = SQLITE_UPDATE;
4761         if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aRec, aExist,a1,a2) ){
4762           sqlite3_free(pNew);
4763           pNew = 0;
4764         }
4765       }else{                                /* UPDATE + DELETE */
4766         assert( op1==SQLITE_UPDATE && op2==SQLITE_DELETE );
4767         pNew->op = SQLITE_DELETE;
4768         if( bPatchset ){
4769           memcpy(aCsr, aRec, nRec);
4770           aCsr += nRec;
4771         }else{
4772           sessionMergeRecord(&aCsr, pTab->nCol, aRec, aExist);
4773         }
4774       }
4775 
4776       if( pNew ){
4777         pNew->nRecord = (int)(aCsr - pNew->aRecord);
4778       }
4779       sqlite3_free(pExist);
4780     }
4781   }
4782 
4783   *ppNew = pNew;
4784   return rc;
4785 }
4786 
4787 /*
4788 ** Add all changes in the changeset traversed by the iterator passed as
4789 ** the first argument to the changegroup hash tables.
4790 */
4791 static int sessionChangesetToHash(
4792   sqlite3_changeset_iter *pIter,   /* Iterator to read from */
4793   sqlite3_changegroup *pGrp,       /* Changegroup object to add changeset to */
4794   int bRebase                      /* True if hash table is for rebasing */
4795 ){
4796   u8 *aRec;
4797   int nRec;
4798   int rc = SQLITE_OK;
4799   SessionTable *pTab = 0;
4800 
4801   while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec, 0) ){
4802     const char *zNew;
4803     int nCol;
4804     int op;
4805     int iHash;
4806     int bIndirect;
4807     SessionChange *pChange;
4808     SessionChange *pExist = 0;
4809     SessionChange **pp;
4810 
4811     if( pGrp->pList==0 ){
4812       pGrp->bPatch = pIter->bPatchset;
4813     }else if( pIter->bPatchset!=pGrp->bPatch ){
4814       rc = SQLITE_ERROR;
4815       break;
4816     }
4817 
4818     sqlite3changeset_op(pIter, &zNew, &nCol, &op, &bIndirect);
4819     if( !pTab || sqlite3_stricmp(zNew, pTab->zName) ){
4820       /* Search the list for a matching table */
4821       int nNew = (int)strlen(zNew);
4822       u8 *abPK;
4823 
4824       sqlite3changeset_pk(pIter, &abPK, 0);
4825       for(pTab = pGrp->pList; pTab; pTab=pTab->pNext){
4826         if( 0==sqlite3_strnicmp(pTab->zName, zNew, nNew+1) ) break;
4827       }
4828       if( !pTab ){
4829         SessionTable **ppTab;
4830 
4831         pTab = sqlite3_malloc(sizeof(SessionTable) + nCol + nNew+1);
4832         if( !pTab ){
4833           rc = SQLITE_NOMEM;
4834           break;
4835         }
4836         memset(pTab, 0, sizeof(SessionTable));
4837         pTab->nCol = nCol;
4838         pTab->abPK = (u8*)&pTab[1];
4839         memcpy(pTab->abPK, abPK, nCol);
4840         pTab->zName = (char*)&pTab->abPK[nCol];
4841         memcpy(pTab->zName, zNew, nNew+1);
4842 
4843         /* The new object must be linked on to the end of the list, not
4844         ** simply added to the start of it. This is to ensure that the
4845         ** tables within the output of sqlite3changegroup_output() are in
4846         ** the right order.  */
4847         for(ppTab=&pGrp->pList; *ppTab; ppTab=&(*ppTab)->pNext);
4848         *ppTab = pTab;
4849       }else if( pTab->nCol!=nCol || memcmp(pTab->abPK, abPK, nCol) ){
4850         rc = SQLITE_SCHEMA;
4851         break;
4852       }
4853     }
4854 
4855     if( sessionGrowHash(pIter->bPatchset, pTab) ){
4856       rc = SQLITE_NOMEM;
4857       break;
4858     }
4859     iHash = sessionChangeHash(
4860         pTab, (pIter->bPatchset && op==SQLITE_DELETE), aRec, pTab->nChange
4861     );
4862 
4863     /* Search for existing entry. If found, remove it from the hash table.
4864     ** Code below may link it back in.
4865     */
4866     for(pp=&pTab->apChange[iHash]; *pp; pp=&(*pp)->pNext){
4867       int bPkOnly1 = 0;
4868       int bPkOnly2 = 0;
4869       if( pIter->bPatchset ){
4870         bPkOnly1 = (*pp)->op==SQLITE_DELETE;
4871         bPkOnly2 = op==SQLITE_DELETE;
4872       }
4873       if( sessionChangeEqual(pTab, bPkOnly1, (*pp)->aRecord, bPkOnly2, aRec) ){
4874         pExist = *pp;
4875         *pp = (*pp)->pNext;
4876         pTab->nEntry--;
4877         break;
4878       }
4879     }
4880 
4881     rc = sessionChangeMerge(pTab, bRebase,
4882         pIter->bPatchset, pExist, op, bIndirect, aRec, nRec, &pChange
4883     );
4884     if( rc ) break;
4885     if( pChange ){
4886       pChange->pNext = pTab->apChange[iHash];
4887       pTab->apChange[iHash] = pChange;
4888       pTab->nEntry++;
4889     }
4890   }
4891 
4892   if( rc==SQLITE_OK ) rc = pIter->rc;
4893   return rc;
4894 }
4895 
4896 /*
4897 ** Serialize a changeset (or patchset) based on all changesets (or patchsets)
4898 ** added to the changegroup object passed as the first argument.
4899 **
4900 ** If xOutput is not NULL, then the changeset/patchset is returned to the
4901 ** user via one or more calls to xOutput, as with the other streaming
4902 ** interfaces.
4903 **
4904 ** Or, if xOutput is NULL, then (*ppOut) is populated with a pointer to a
4905 ** buffer containing the output changeset before this function returns. In
4906 ** this case (*pnOut) is set to the size of the output buffer in bytes. It
4907 ** is the responsibility of the caller to free the output buffer using
4908 ** sqlite3_free() when it is no longer required.
4909 **
4910 ** If successful, SQLITE_OK is returned. Or, if an error occurs, an SQLite
4911 ** error code. If an error occurs and xOutput is NULL, (*ppOut) and (*pnOut)
4912 ** are both set to 0 before returning.
4913 */
4914 static int sessionChangegroupOutput(
4915   sqlite3_changegroup *pGrp,
4916   int (*xOutput)(void *pOut, const void *pData, int nData),
4917   void *pOut,
4918   int *pnOut,
4919   void **ppOut
4920 ){
4921   int rc = SQLITE_OK;
4922   SessionBuffer buf = {0, 0, 0};
4923   SessionTable *pTab;
4924   assert( xOutput==0 || (ppOut==0 && pnOut==0) );
4925 
4926   /* Create the serialized output changeset based on the contents of the
4927   ** hash tables attached to the SessionTable objects in list p->pList.
4928   */
4929   for(pTab=pGrp->pList; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
4930     int i;
4931     if( pTab->nEntry==0 ) continue;
4932 
4933     sessionAppendTableHdr(&buf, pGrp->bPatch, pTab, &rc);
4934     for(i=0; i<pTab->nChange; i++){
4935       SessionChange *p;
4936       for(p=pTab->apChange[i]; p; p=p->pNext){
4937         sessionAppendByte(&buf, p->op, &rc);
4938         sessionAppendByte(&buf, p->bIndirect, &rc);
4939         sessionAppendBlob(&buf, p->aRecord, p->nRecord, &rc);
4940         if( rc==SQLITE_OK && xOutput && buf.nBuf>=sessions_strm_chunk_size ){
4941           rc = xOutput(pOut, buf.aBuf, buf.nBuf);
4942           buf.nBuf = 0;
4943         }
4944       }
4945     }
4946   }
4947 
4948   if( rc==SQLITE_OK ){
4949     if( xOutput ){
4950       if( buf.nBuf>0 ) rc = xOutput(pOut, buf.aBuf, buf.nBuf);
4951     }else{
4952       *ppOut = buf.aBuf;
4953       *pnOut = buf.nBuf;
4954       buf.aBuf = 0;
4955     }
4956   }
4957   sqlite3_free(buf.aBuf);
4958 
4959   return rc;
4960 }
4961 
4962 /*
4963 ** Allocate a new, empty, sqlite3_changegroup.
4964 */
4965 int sqlite3changegroup_new(sqlite3_changegroup **pp){
4966   int rc = SQLITE_OK;             /* Return code */
4967   sqlite3_changegroup *p;         /* New object */
4968   p = (sqlite3_changegroup*)sqlite3_malloc(sizeof(sqlite3_changegroup));
4969   if( p==0 ){
4970     rc = SQLITE_NOMEM;
4971   }else{
4972     memset(p, 0, sizeof(sqlite3_changegroup));
4973   }
4974   *pp = p;
4975   return rc;
4976 }
4977 
4978 /*
4979 ** Add the changeset currently stored in buffer pData, size nData bytes,
4980 ** to changeset-group p.
4981 */
4982 int sqlite3changegroup_add(sqlite3_changegroup *pGrp, int nData, void *pData){
4983   sqlite3_changeset_iter *pIter;  /* Iterator opened on pData/nData */
4984   int rc;                         /* Return code */
4985 
4986   rc = sqlite3changeset_start(&pIter, nData, pData);
4987   if( rc==SQLITE_OK ){
4988     rc = sessionChangesetToHash(pIter, pGrp, 0);
4989   }
4990   sqlite3changeset_finalize(pIter);
4991   return rc;
4992 }
4993 
4994 /*
4995 ** Obtain a buffer containing a changeset representing the concatenation
4996 ** of all changesets added to the group so far.
4997 */
4998 int sqlite3changegroup_output(
4999     sqlite3_changegroup *pGrp,
5000     int *pnData,
5001     void **ppData
5002 ){
5003   return sessionChangegroupOutput(pGrp, 0, 0, pnData, ppData);
5004 }
5005 
5006 /*
5007 ** Streaming versions of changegroup_add().
5008 */
5009 int sqlite3changegroup_add_strm(
5010   sqlite3_changegroup *pGrp,
5011   int (*xInput)(void *pIn, void *pData, int *pnData),
5012   void *pIn
5013 ){
5014   sqlite3_changeset_iter *pIter;  /* Iterator opened on pData/nData */
5015   int rc;                         /* Return code */
5016 
5017   rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
5018   if( rc==SQLITE_OK ){
5019     rc = sessionChangesetToHash(pIter, pGrp, 0);
5020   }
5021   sqlite3changeset_finalize(pIter);
5022   return rc;
5023 }
5024 
5025 /*
5026 ** Streaming versions of changegroup_output().
5027 */
5028 int sqlite3changegroup_output_strm(
5029   sqlite3_changegroup *pGrp,
5030   int (*xOutput)(void *pOut, const void *pData, int nData),
5031   void *pOut
5032 ){
5033   return sessionChangegroupOutput(pGrp, xOutput, pOut, 0, 0);
5034 }
5035 
5036 /*
5037 ** Delete a changegroup object.
5038 */
5039 void sqlite3changegroup_delete(sqlite3_changegroup *pGrp){
5040   if( pGrp ){
5041     sessionDeleteTable(pGrp->pList);
5042     sqlite3_free(pGrp);
5043   }
5044 }
5045 
5046 /*
5047 ** Combine two changesets together.
5048 */
5049 int sqlite3changeset_concat(
5050   int nLeft,                      /* Number of bytes in lhs input */
5051   void *pLeft,                    /* Lhs input changeset */
5052   int nRight                      /* Number of bytes in rhs input */,
5053   void *pRight,                   /* Rhs input changeset */
5054   int *pnOut,                     /* OUT: Number of bytes in output changeset */
5055   void **ppOut                    /* OUT: changeset (left <concat> right) */
5056 ){
5057   sqlite3_changegroup *pGrp;
5058   int rc;
5059 
5060   rc = sqlite3changegroup_new(&pGrp);
5061   if( rc==SQLITE_OK ){
5062     rc = sqlite3changegroup_add(pGrp, nLeft, pLeft);
5063   }
5064   if( rc==SQLITE_OK ){
5065     rc = sqlite3changegroup_add(pGrp, nRight, pRight);
5066   }
5067   if( rc==SQLITE_OK ){
5068     rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
5069   }
5070   sqlite3changegroup_delete(pGrp);
5071 
5072   return rc;
5073 }
5074 
5075 /*
5076 ** Streaming version of sqlite3changeset_concat().
5077 */
5078 int sqlite3changeset_concat_strm(
5079   int (*xInputA)(void *pIn, void *pData, int *pnData),
5080   void *pInA,
5081   int (*xInputB)(void *pIn, void *pData, int *pnData),
5082   void *pInB,
5083   int (*xOutput)(void *pOut, const void *pData, int nData),
5084   void *pOut
5085 ){
5086   sqlite3_changegroup *pGrp;
5087   int rc;
5088 
5089   rc = sqlite3changegroup_new(&pGrp);
5090   if( rc==SQLITE_OK ){
5091     rc = sqlite3changegroup_add_strm(pGrp, xInputA, pInA);
5092   }
5093   if( rc==SQLITE_OK ){
5094     rc = sqlite3changegroup_add_strm(pGrp, xInputB, pInB);
5095   }
5096   if( rc==SQLITE_OK ){
5097     rc = sqlite3changegroup_output_strm(pGrp, xOutput, pOut);
5098   }
5099   sqlite3changegroup_delete(pGrp);
5100 
5101   return rc;
5102 }
5103 
5104 /*
5105 ** Changeset rebaser handle.
5106 */
5107 struct sqlite3_rebaser {
5108   sqlite3_changegroup grp;        /* Hash table */
5109 };
5110 
5111 /*
5112 ** Buffers a1 and a2 must both contain a sessions module record nCol
5113 ** fields in size. This function appends an nCol sessions module
5114 ** record to buffer pBuf that is a copy of a1, except that for
5115 ** each field that is undefined in a1[], swap in the field from a2[].
5116 */
5117 static void sessionAppendRecordMerge(
5118   SessionBuffer *pBuf,            /* Buffer to append to */
5119   int nCol,                       /* Number of columns in each record */
5120   u8 *a1, int n1,                 /* Record 1 */
5121   u8 *a2, int n2,                 /* Record 2 */
5122   int *pRc                        /* IN/OUT: error code */
5123 ){
5124   sessionBufferGrow(pBuf, n1+n2, pRc);
5125   if( *pRc==SQLITE_OK ){
5126     int i;
5127     u8 *pOut = &pBuf->aBuf[pBuf->nBuf];
5128     for(i=0; i<nCol; i++){
5129       int nn1 = sessionSerialLen(a1);
5130       int nn2 = sessionSerialLen(a2);
5131       if( *a1==0 || *a1==0xFF ){
5132         memcpy(pOut, a2, nn2);
5133         pOut += nn2;
5134       }else{
5135         memcpy(pOut, a1, nn1);
5136         pOut += nn1;
5137       }
5138       a1 += nn1;
5139       a2 += nn2;
5140     }
5141 
5142     pBuf->nBuf = pOut-pBuf->aBuf;
5143     assert( pBuf->nBuf<=pBuf->nAlloc );
5144   }
5145 }
5146 
5147 /*
5148 ** This function is called when rebasing a local UPDATE change against one
5149 ** or more remote UPDATE changes. The aRec/nRec buffer contains the current
5150 ** old.* and new.* records for the change. The rebase buffer (a single
5151 ** record) is in aChange/nChange. The rebased change is appended to buffer
5152 ** pBuf.
5153 **
5154 ** Rebasing the UPDATE involves:
5155 **
5156 **   * Removing any changes to fields for which the corresponding field
5157 **     in the rebase buffer is set to "replaced" (type 0xFF). If this
5158 **     means the UPDATE change updates no fields, nothing is appended
5159 **     to the output buffer.
5160 **
5161 **   * For each field modified by the local change for which the
5162 **     corresponding field in the rebase buffer is not "undefined" (0x00)
5163 **     or "replaced" (0xFF), the old.* value is replaced by the value
5164 **     in the rebase buffer.
5165 */
5166 static void sessionAppendPartialUpdate(
5167   SessionBuffer *pBuf,            /* Append record here */
5168   sqlite3_changeset_iter *pIter,  /* Iterator pointed at local change */
5169   u8 *aRec, int nRec,             /* Local change */
5170   u8 *aChange, int nChange,       /* Record to rebase against */
5171   int *pRc                        /* IN/OUT: Return Code */
5172 ){
5173   sessionBufferGrow(pBuf, 2+nRec+nChange, pRc);
5174   if( *pRc==SQLITE_OK ){
5175     int bData = 0;
5176     u8 *pOut = &pBuf->aBuf[pBuf->nBuf];
5177     int i;
5178     u8 *a1 = aRec;
5179     u8 *a2 = aChange;
5180 
5181     *pOut++ = SQLITE_UPDATE;
5182     *pOut++ = pIter->bIndirect;
5183     for(i=0; i<pIter->nCol; i++){
5184       int n1 = sessionSerialLen(a1);
5185       int n2 = sessionSerialLen(a2);
5186       if( pIter->abPK[i] || a2[0]==0 ){
5187         if( !pIter->abPK[i] ) bData = 1;
5188         memcpy(pOut, a1, n1);
5189         pOut += n1;
5190       }else if( a2[0]!=0xFF ){
5191         bData = 1;
5192         memcpy(pOut, a2, n2);
5193         pOut += n2;
5194       }else{
5195         *pOut++ = '\0';
5196       }
5197       a1 += n1;
5198       a2 += n2;
5199     }
5200     if( bData ){
5201       a2 = aChange;
5202       for(i=0; i<pIter->nCol; i++){
5203         int n1 = sessionSerialLen(a1);
5204         int n2 = sessionSerialLen(a2);
5205         if( pIter->abPK[i] || a2[0]!=0xFF ){
5206           memcpy(pOut, a1, n1);
5207           pOut += n1;
5208         }else{
5209           *pOut++ = '\0';
5210         }
5211         a1 += n1;
5212         a2 += n2;
5213       }
5214       pBuf->nBuf = (pOut - pBuf->aBuf);
5215     }
5216   }
5217 }
5218 
5219 /*
5220 ** pIter is configured to iterate through a changeset. This function rebases
5221 ** that changeset according to the current configuration of the rebaser
5222 ** object passed as the first argument. If no error occurs and argument xOutput
5223 ** is not NULL, then the changeset is returned to the caller by invoking
5224 ** xOutput zero or more times and SQLITE_OK returned. Or, if xOutput is NULL,
5225 ** then (*ppOut) is set to point to a buffer containing the rebased changeset
5226 ** before this function returns. In this case (*pnOut) is set to the size of
5227 ** the buffer in bytes.  It is the responsibility of the caller to eventually
5228 ** free the (*ppOut) buffer using sqlite3_free().
5229 **
5230 ** If an error occurs, an SQLite error code is returned. If ppOut and
5231 ** pnOut are not NULL, then the two output parameters are set to 0 before
5232 ** returning.
5233 */
5234 static int sessionRebase(
5235   sqlite3_rebaser *p,             /* Rebaser hash table */
5236   sqlite3_changeset_iter *pIter,  /* Input data */
5237   int (*xOutput)(void *pOut, const void *pData, int nData),
5238   void *pOut,                     /* Context for xOutput callback */
5239   int *pnOut,                     /* OUT: Number of bytes in output changeset */
5240   void **ppOut                    /* OUT: Inverse of pChangeset */
5241 ){
5242   int rc = SQLITE_OK;
5243   u8 *aRec = 0;
5244   int nRec = 0;
5245   int bNew = 0;
5246   SessionTable *pTab = 0;
5247   SessionBuffer sOut = {0,0,0};
5248 
5249   while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec, &bNew) ){
5250     SessionChange *pChange = 0;
5251     int bDone = 0;
5252 
5253     if( bNew ){
5254       const char *zTab = pIter->zTab;
5255       for(pTab=p->grp.pList; pTab; pTab=pTab->pNext){
5256         if( 0==sqlite3_stricmp(pTab->zName, zTab) ) break;
5257       }
5258       bNew = 0;
5259 
5260       /* A patchset may not be rebased */
5261       if( pIter->bPatchset ){
5262         rc = SQLITE_ERROR;
5263       }
5264 
5265       /* Append a table header to the output for this new table */
5266       sessionAppendByte(&sOut, pIter->bPatchset ? 'P' : 'T', &rc);
5267       sessionAppendVarint(&sOut, pIter->nCol, &rc);
5268       sessionAppendBlob(&sOut, pIter->abPK, pIter->nCol, &rc);
5269       sessionAppendBlob(&sOut,(u8*)pIter->zTab,(int)strlen(pIter->zTab)+1,&rc);
5270     }
5271 
5272     if( pTab && rc==SQLITE_OK ){
5273       int iHash = sessionChangeHash(pTab, 0, aRec, pTab->nChange);
5274 
5275       for(pChange=pTab->apChange[iHash]; pChange; pChange=pChange->pNext){
5276         if( sessionChangeEqual(pTab, 0, aRec, 0, pChange->aRecord) ){
5277           break;
5278         }
5279       }
5280     }
5281 
5282     if( pChange ){
5283       assert( pChange->op==SQLITE_DELETE || pChange->op==SQLITE_INSERT );
5284       switch( pIter->op ){
5285         case SQLITE_INSERT:
5286           if( pChange->op==SQLITE_INSERT ){
5287             bDone = 1;
5288             if( pChange->bIndirect==0 ){
5289               sessionAppendByte(&sOut, SQLITE_UPDATE, &rc);
5290               sessionAppendByte(&sOut, pIter->bIndirect, &rc);
5291               sessionAppendBlob(&sOut, pChange->aRecord, pChange->nRecord, &rc);
5292               sessionAppendBlob(&sOut, aRec, nRec, &rc);
5293             }
5294           }
5295           break;
5296 
5297         case SQLITE_UPDATE:
5298           bDone = 1;
5299           if( pChange->op==SQLITE_DELETE ){
5300             if( pChange->bIndirect==0 ){
5301               u8 *pCsr = aRec;
5302               sessionSkipRecord(&pCsr, pIter->nCol);
5303               sessionAppendByte(&sOut, SQLITE_INSERT, &rc);
5304               sessionAppendByte(&sOut, pIter->bIndirect, &rc);
5305               sessionAppendRecordMerge(&sOut, pIter->nCol,
5306                   pCsr, nRec-(pCsr-aRec),
5307                   pChange->aRecord, pChange->nRecord, &rc
5308               );
5309             }
5310           }else{
5311             sessionAppendPartialUpdate(&sOut, pIter,
5312                 aRec, nRec, pChange->aRecord, pChange->nRecord, &rc
5313             );
5314           }
5315           break;
5316 
5317         default:
5318           assert( pIter->op==SQLITE_DELETE );
5319           bDone = 1;
5320           if( pChange->op==SQLITE_INSERT ){
5321             sessionAppendByte(&sOut, SQLITE_DELETE, &rc);
5322             sessionAppendByte(&sOut, pIter->bIndirect, &rc);
5323             sessionAppendRecordMerge(&sOut, pIter->nCol,
5324                 pChange->aRecord, pChange->nRecord, aRec, nRec, &rc
5325             );
5326           }
5327           break;
5328       }
5329     }
5330 
5331     if( bDone==0 ){
5332       sessionAppendByte(&sOut, pIter->op, &rc);
5333       sessionAppendByte(&sOut, pIter->bIndirect, &rc);
5334       sessionAppendBlob(&sOut, aRec, nRec, &rc);
5335     }
5336     if( rc==SQLITE_OK && xOutput && sOut.nBuf>sessions_strm_chunk_size ){
5337       rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
5338       sOut.nBuf = 0;
5339     }
5340     if( rc ) break;
5341   }
5342 
5343   if( rc!=SQLITE_OK ){
5344     sqlite3_free(sOut.aBuf);
5345     memset(&sOut, 0, sizeof(sOut));
5346   }
5347 
5348   if( rc==SQLITE_OK ){
5349     if( xOutput ){
5350       if( sOut.nBuf>0 ){
5351         rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
5352       }
5353     }else{
5354       *ppOut = (void*)sOut.aBuf;
5355       *pnOut = sOut.nBuf;
5356       sOut.aBuf = 0;
5357     }
5358   }
5359   sqlite3_free(sOut.aBuf);
5360   return rc;
5361 }
5362 
5363 /*
5364 ** Create a new rebaser object.
5365 */
5366 int sqlite3rebaser_create(sqlite3_rebaser **ppNew){
5367   int rc = SQLITE_OK;
5368   sqlite3_rebaser *pNew;
5369 
5370   pNew = sqlite3_malloc(sizeof(sqlite3_rebaser));
5371   if( pNew==0 ){
5372     rc = SQLITE_NOMEM;
5373   }else{
5374     memset(pNew, 0, sizeof(sqlite3_rebaser));
5375   }
5376   *ppNew = pNew;
5377   return rc;
5378 }
5379 
5380 /*
5381 ** Call this one or more times to configure a rebaser.
5382 */
5383 int sqlite3rebaser_configure(
5384   sqlite3_rebaser *p,
5385   int nRebase, const void *pRebase
5386 ){
5387   sqlite3_changeset_iter *pIter = 0;   /* Iterator opened on pData/nData */
5388   int rc;                              /* Return code */
5389   rc = sqlite3changeset_start(&pIter, nRebase, (void*)pRebase);
5390   if( rc==SQLITE_OK ){
5391     rc = sessionChangesetToHash(pIter, &p->grp, 1);
5392   }
5393   sqlite3changeset_finalize(pIter);
5394   return rc;
5395 }
5396 
5397 /*
5398 ** Rebase a changeset according to current rebaser configuration
5399 */
5400 int sqlite3rebaser_rebase(
5401   sqlite3_rebaser *p,
5402   int nIn, const void *pIn,
5403   int *pnOut, void **ppOut
5404 ){
5405   sqlite3_changeset_iter *pIter = 0;   /* Iterator to skip through input */
5406   int rc = sqlite3changeset_start(&pIter, nIn, (void*)pIn);
5407 
5408   if( rc==SQLITE_OK ){
5409     rc = sessionRebase(p, pIter, 0, 0, pnOut, ppOut);
5410     sqlite3changeset_finalize(pIter);
5411   }
5412 
5413   return rc;
5414 }
5415 
5416 /*
5417 ** Rebase a changeset according to current rebaser configuration
5418 */
5419 int sqlite3rebaser_rebase_strm(
5420   sqlite3_rebaser *p,
5421   int (*xInput)(void *pIn, void *pData, int *pnData),
5422   void *pIn,
5423   int (*xOutput)(void *pOut, const void *pData, int nData),
5424   void *pOut
5425 ){
5426   sqlite3_changeset_iter *pIter = 0;   /* Iterator to skip through input */
5427   int rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
5428 
5429   if( rc==SQLITE_OK ){
5430     rc = sessionRebase(p, pIter, xOutput, pOut, 0, 0);
5431     sqlite3changeset_finalize(pIter);
5432   }
5433 
5434   return rc;
5435 }
5436 
5437 /*
5438 ** Destroy a rebaser object
5439 */
5440 void sqlite3rebaser_delete(sqlite3_rebaser *p){
5441   if( p ){
5442     sessionDeleteTable(p->grp.pList);
5443     sqlite3_free(p);
5444   }
5445 }
5446 
5447 /*
5448 ** Global configuration
5449 */
5450 int sqlite3session_config(int op, void *pArg){
5451   int rc = SQLITE_OK;
5452   switch( op ){
5453     case SQLITE_SESSION_CONFIG_STRMSIZE: {
5454       int *pInt = (int*)pArg;
5455       if( *pInt>0 ){
5456         sessions_strm_chunk_size = *pInt;
5457       }
5458       *pInt = sessions_strm_chunk_size;
5459       break;
5460     }
5461     default:
5462       rc = SQLITE_MISUSE;
5463       break;
5464   }
5465   return rc;
5466 }
5467 
5468 #endif /* SQLITE_ENABLE_SESSION && SQLITE_ENABLE_PREUPDATE_HOOK */
5469