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