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