Fix obsolete comments. No changes to code.
[sqlite.git] / ext / session / sqlite3session.c
blobde27acd0db63ac32e2dfd16fd3a7c18e6cb5ae37
2 #if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
3 #include "sqlite3session.h"
4 #include <assert.h>
5 #include <string.h>
7 #ifndef SQLITE_AMALGAMATION
8 # include "sqliteInt.h"
9 # include "vdbeInt.h"
10 #endif
12 typedef struct SessionTable SessionTable;
13 typedef struct SessionChange SessionChange;
14 typedef struct SessionBuffer SessionBuffer;
15 typedef struct SessionInput SessionInput;
18 ** Minimum chunk size used by streaming versions of functions.
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
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*);
38 ** Session handle structure.
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 */
55 ** Instances of this structure are used to build strings or binary records.
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 */
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()).
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 */
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 */
83 ** Structure for changeset iterators.
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 */
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.
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.
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.
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 */
124 ** RECORD FORMAT:
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.
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:
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.
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:
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.
151 ** Blob values:
152 ** A varint containing the number of bytes in the value, followed by
153 ** a buffer containing the value itself.
155 ** Integer values:
156 ** An 8-byte big-endian integer value.
158 ** Real values:
159 ** An 8-byte big-endian IEEE 754-2008 real value.
161 ** Varint values are encoded in the same way as varints in the SQLite
162 ** record format.
164 ** CHANGESET FORMAT:
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).
171 ** Each group of changes begins with a table header:
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.
178 ** Followed by one or more changes to the table.
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)
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.
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.
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".
207 ** PATCHSET FORMAT:
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.
213 ** Each group of changes begins with a table header:
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.
220 ** Followed by one or more changes to the table.
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).
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.
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.
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.
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".
247 ** For each row modified during a session, there exists a single instance of
248 ** this structure stored in a SessionTable.aChange[] hash table.
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 */
259 ** Write a varint with value iVal into the buffer at aBuf. Return the
260 ** number of bytes written.
262 static int sessionVarintPut(u8 *aBuf, int iVal){
263 return putVarint32(aBuf, iVal);
267 ** Return the number of bytes required to store value iVal as a varint.
269 static int sessionVarintLen(int iVal){
270 return sqlite3VarintLen(iVal);
274 ** Read a varint value from aBuf[] into *piVal. Return the number of
275 ** bytes read.
277 static int sessionVarintGet(u8 *aBuf, int *piVal){
278 return getVarint32(aBuf, *piVal);
281 /* Load an unaligned and unsigned 32-bit integer */
282 #define SESSION_UINT32(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
285 ** Read a 64-bit big-endian integer value from buffer aRec[]. Return
286 ** the value read.
288 static sqlite3_int64 sessionGetI64(u8 *aRec){
289 u64 x = SESSION_UINT32(aRec);
290 u32 y = SESSION_UINT32(aRec+4);
291 x = (x<<32) + y;
292 return (sqlite3_int64)x;
296 ** Write a 64-bit big-endian integer value to the buffer aBuf[].
298 static void sessionPutI64(u8 *aBuf, sqlite3_int64 i){
299 aBuf[0] = (i>>56) & 0xFF;
300 aBuf[1] = (i>>48) & 0xFF;
301 aBuf[2] = (i>>40) & 0xFF;
302 aBuf[3] = (i>>32) & 0xFF;
303 aBuf[4] = (i>>24) & 0xFF;
304 aBuf[5] = (i>>16) & 0xFF;
305 aBuf[6] = (i>> 8) & 0xFF;
306 aBuf[7] = (i>> 0) & 0xFF;
310 ** This function is used to serialize the contents of value pValue (see
311 ** comment titled "RECORD FORMAT" above).
313 ** If it is non-NULL, the serialized form of the value is written to
314 ** buffer aBuf. *pnWrite is set to the number of bytes written before
315 ** returning. Or, if aBuf is NULL, the only thing this function does is
316 ** set *pnWrite.
318 ** If no error occurs, SQLITE_OK is returned. Or, if an OOM error occurs
319 ** within a call to sqlite3_value_text() (may fail if the db is utf-16))
320 ** SQLITE_NOMEM is returned.
322 static int sessionSerializeValue(
323 u8 *aBuf, /* If non-NULL, write serialized value here */
324 sqlite3_value *pValue, /* Value to serialize */
325 int *pnWrite /* IN/OUT: Increment by bytes written */
327 int nByte; /* Size of serialized value in bytes */
329 if( pValue ){
330 int eType; /* Value type (SQLITE_NULL, TEXT etc.) */
332 eType = sqlite3_value_type(pValue);
333 if( aBuf ) aBuf[0] = eType;
335 switch( eType ){
336 case SQLITE_NULL:
337 nByte = 1;
338 break;
340 case SQLITE_INTEGER:
341 case SQLITE_FLOAT:
342 if( aBuf ){
343 /* TODO: SQLite does something special to deal with mixed-endian
344 ** floating point values (e.g. ARM7). This code probably should
345 ** too. */
346 u64 i;
347 if( eType==SQLITE_INTEGER ){
348 i = (u64)sqlite3_value_int64(pValue);
349 }else{
350 double r;
351 assert( sizeof(double)==8 && sizeof(u64)==8 );
352 r = sqlite3_value_double(pValue);
353 memcpy(&i, &r, 8);
355 sessionPutI64(&aBuf[1], i);
357 nByte = 9;
358 break;
360 default: {
361 u8 *z;
362 int n;
363 int nVarint;
365 assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
366 if( eType==SQLITE_TEXT ){
367 z = (u8 *)sqlite3_value_text(pValue);
368 }else{
369 z = (u8 *)sqlite3_value_blob(pValue);
371 n = sqlite3_value_bytes(pValue);
372 if( z==0 && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
373 nVarint = sessionVarintLen(n);
375 if( aBuf ){
376 sessionVarintPut(&aBuf[1], n);
377 if( n ) memcpy(&aBuf[nVarint + 1], z, n);
380 nByte = 1 + nVarint + n;
381 break;
384 }else{
385 nByte = 1;
386 if( aBuf ) aBuf[0] = '\0';
389 if( pnWrite ) *pnWrite += nByte;
390 return SQLITE_OK;
395 ** This macro is used to calculate hash key values for data structures. In
396 ** order to use this macro, the entire data structure must be represented
397 ** as a series of unsigned integers. In order to calculate a hash-key value
398 ** for a data structure represented as three such integers, the macro may
399 ** then be used as follows:
401 ** int hash_key_value;
402 ** hash_key_value = HASH_APPEND(0, <value 1>);
403 ** hash_key_value = HASH_APPEND(hash_key_value, <value 2>);
404 ** hash_key_value = HASH_APPEND(hash_key_value, <value 3>);
406 ** In practice, the data structures this macro is used for are the primary
407 ** key values of modified rows.
409 #define HASH_APPEND(hash, add) ((hash) << 3) ^ (hash) ^ (unsigned int)(add)
412 ** Append the hash of the 64-bit integer passed as the second argument to the
413 ** hash-key value passed as the first. Return the new hash-key value.
415 static unsigned int sessionHashAppendI64(unsigned int h, i64 i){
416 h = HASH_APPEND(h, i & 0xFFFFFFFF);
417 return HASH_APPEND(h, (i>>32)&0xFFFFFFFF);
421 ** Append the hash of the blob passed via the second and third arguments to
422 ** the hash-key value passed as the first. Return the new hash-key value.
424 static unsigned int sessionHashAppendBlob(unsigned int h, int n, const u8 *z){
425 int i;
426 for(i=0; i<n; i++) h = HASH_APPEND(h, z[i]);
427 return h;
431 ** Append the hash of the data type passed as the second argument to the
432 ** hash-key value passed as the first. Return the new hash-key value.
434 static unsigned int sessionHashAppendType(unsigned int h, int eType){
435 return HASH_APPEND(h, eType);
439 ** This function may only be called from within a pre-update callback.
440 ** It calculates a hash based on the primary key values of the old.* or
441 ** new.* row currently available and, assuming no error occurs, writes it to
442 ** *piHash before returning. If the primary key contains one or more NULL
443 ** values, *pbNullPK is set to true before returning.
445 ** If an error occurs, an SQLite error code is returned and the final values
446 ** of *piHash asn *pbNullPK are undefined. Otherwise, SQLITE_OK is returned
447 ** and the output variables are set as described above.
449 static int sessionPreupdateHash(
450 sqlite3_session *pSession, /* Session object that owns pTab */
451 SessionTable *pTab, /* Session table handle */
452 int bNew, /* True to hash the new.* PK */
453 int *piHash, /* OUT: Hash value */
454 int *pbNullPK /* OUT: True if there are NULL values in PK */
456 unsigned int h = 0; /* Hash value to return */
457 int i; /* Used to iterate through columns */
459 assert( *pbNullPK==0 );
460 assert( pTab->nCol==pSession->hook.xCount(pSession->hook.pCtx) );
461 for(i=0; i<pTab->nCol; i++){
462 if( pTab->abPK[i] ){
463 int rc;
464 int eType;
465 sqlite3_value *pVal;
467 if( bNew ){
468 rc = pSession->hook.xNew(pSession->hook.pCtx, i, &pVal);
469 }else{
470 rc = pSession->hook.xOld(pSession->hook.pCtx, i, &pVal);
472 if( rc!=SQLITE_OK ) return rc;
474 eType = sqlite3_value_type(pVal);
475 h = sessionHashAppendType(h, eType);
476 if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
477 i64 iVal;
478 if( eType==SQLITE_INTEGER ){
479 iVal = sqlite3_value_int64(pVal);
480 }else{
481 double rVal = sqlite3_value_double(pVal);
482 assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
483 memcpy(&iVal, &rVal, 8);
485 h = sessionHashAppendI64(h, iVal);
486 }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
487 const u8 *z;
488 int n;
489 if( eType==SQLITE_TEXT ){
490 z = (const u8 *)sqlite3_value_text(pVal);
491 }else{
492 z = (const u8 *)sqlite3_value_blob(pVal);
494 n = sqlite3_value_bytes(pVal);
495 if( !z && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
496 h = sessionHashAppendBlob(h, n, z);
497 }else{
498 assert( eType==SQLITE_NULL );
499 *pbNullPK = 1;
504 *piHash = (h % pTab->nChange);
505 return SQLITE_OK;
509 ** The buffer that the argument points to contains a serialized SQL value.
510 ** Return the number of bytes of space occupied by the value (including
511 ** the type byte).
513 static int sessionSerialLen(u8 *a){
514 int e = *a;
515 int n;
516 if( e==0 ) return 1;
517 if( e==SQLITE_NULL ) return 1;
518 if( e==SQLITE_INTEGER || e==SQLITE_FLOAT ) return 9;
519 return sessionVarintGet(&a[1], &n) + 1 + n;
523 ** Based on the primary key values stored in change aRecord, calculate a
524 ** hash key. Assume the has table has nBucket buckets. The hash keys
525 ** calculated by this function are compatible with those calculated by
526 ** sessionPreupdateHash().
528 ** The bPkOnly argument is non-zero if the record at aRecord[] is from
529 ** a patchset DELETE. In this case the non-PK fields are omitted entirely.
531 static unsigned int sessionChangeHash(
532 SessionTable *pTab, /* Table handle */
533 int bPkOnly, /* Record consists of PK fields only */
534 u8 *aRecord, /* Change record */
535 int nBucket /* Assume this many buckets in hash table */
537 unsigned int h = 0; /* Value to return */
538 int i; /* Used to iterate through columns */
539 u8 *a = aRecord; /* Used to iterate through change record */
541 for(i=0; i<pTab->nCol; i++){
542 int eType = *a;
543 int isPK = pTab->abPK[i];
544 if( bPkOnly && isPK==0 ) continue;
546 /* It is not possible for eType to be SQLITE_NULL here. The session
547 ** module does not record changes for rows with NULL values stored in
548 ** primary key columns. */
549 assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
550 || eType==SQLITE_TEXT || eType==SQLITE_BLOB
551 || eType==SQLITE_NULL || eType==0
553 assert( !isPK || (eType!=0 && eType!=SQLITE_NULL) );
555 if( isPK ){
556 a++;
557 h = sessionHashAppendType(h, eType);
558 if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
559 h = sessionHashAppendI64(h, sessionGetI64(a));
560 a += 8;
561 }else{
562 int n;
563 a += sessionVarintGet(a, &n);
564 h = sessionHashAppendBlob(h, n, a);
565 a += n;
567 }else{
568 a += sessionSerialLen(a);
571 return (h % nBucket);
575 ** Arguments aLeft and aRight are pointers to change records for table pTab.
576 ** This function returns true if the two records apply to the same row (i.e.
577 ** have the same values stored in the primary key columns), or false
578 ** otherwise.
580 static int sessionChangeEqual(
581 SessionTable *pTab, /* Table used for PK definition */
582 int bLeftPkOnly, /* True if aLeft[] contains PK fields only */
583 u8 *aLeft, /* Change record */
584 int bRightPkOnly, /* True if aRight[] contains PK fields only */
585 u8 *aRight /* Change record */
587 u8 *a1 = aLeft; /* Cursor to iterate through aLeft */
588 u8 *a2 = aRight; /* Cursor to iterate through aRight */
589 int iCol; /* Used to iterate through table columns */
591 for(iCol=0; iCol<pTab->nCol; iCol++){
592 if( pTab->abPK[iCol] ){
593 int n1 = sessionSerialLen(a1);
594 int n2 = sessionSerialLen(a2);
596 if( pTab->abPK[iCol] && (n1!=n2 || memcmp(a1, a2, n1)) ){
597 return 0;
599 a1 += n1;
600 a2 += n2;
601 }else{
602 if( bLeftPkOnly==0 ) a1 += sessionSerialLen(a1);
603 if( bRightPkOnly==0 ) a2 += sessionSerialLen(a2);
607 return 1;
611 ** Arguments aLeft and aRight both point to buffers containing change
612 ** records with nCol columns. This function "merges" the two records into
613 ** a single records which is written to the buffer at *paOut. *paOut is
614 ** then set to point to one byte after the last byte written before
615 ** returning.
617 ** The merging of records is done as follows: For each column, if the
618 ** aRight record contains a value for the column, copy the value from
619 ** their. Otherwise, if aLeft contains a value, copy it. If neither
620 ** record contains a value for a given column, then neither does the
621 ** output record.
623 static void sessionMergeRecord(
624 u8 **paOut,
625 int nCol,
626 u8 *aLeft,
627 u8 *aRight
629 u8 *a1 = aLeft; /* Cursor used to iterate through aLeft */
630 u8 *a2 = aRight; /* Cursor used to iterate through aRight */
631 u8 *aOut = *paOut; /* Output cursor */
632 int iCol; /* Used to iterate from 0 to nCol */
634 for(iCol=0; iCol<nCol; iCol++){
635 int n1 = sessionSerialLen(a1);
636 int n2 = sessionSerialLen(a2);
637 if( *a2 ){
638 memcpy(aOut, a2, n2);
639 aOut += n2;
640 }else{
641 memcpy(aOut, a1, n1);
642 aOut += n1;
644 a1 += n1;
645 a2 += n2;
648 *paOut = aOut;
652 ** This is a helper function used by sessionMergeUpdate().
654 ** When this function is called, both *paOne and *paTwo point to a value
655 ** within a change record. Before it returns, both have been advanced so
656 ** as to point to the next value in the record.
658 ** If, when this function is called, *paTwo points to a valid value (i.e.
659 ** *paTwo[0] is not 0x00 - the "no value" placeholder), a copy of the *paTwo
660 ** pointer is returned and *pnVal is set to the number of bytes in the
661 ** serialized value. Otherwise, a copy of *paOne is returned and *pnVal
662 ** set to the number of bytes in the value at *paOne. If *paOne points
663 ** to the "no value" placeholder, *pnVal is set to 1. In other words:
665 ** if( *paTwo is valid ) return *paTwo;
666 ** return *paOne;
669 static u8 *sessionMergeValue(
670 u8 **paOne, /* IN/OUT: Left-hand buffer pointer */
671 u8 **paTwo, /* IN/OUT: Right-hand buffer pointer */
672 int *pnVal /* OUT: Bytes in returned value */
674 u8 *a1 = *paOne;
675 u8 *a2 = *paTwo;
676 u8 *pRet = 0;
677 int n1;
679 assert( a1 );
680 if( a2 ){
681 int n2 = sessionSerialLen(a2);
682 if( *a2 ){
683 *pnVal = n2;
684 pRet = a2;
686 *paTwo = &a2[n2];
689 n1 = sessionSerialLen(a1);
690 if( pRet==0 ){
691 *pnVal = n1;
692 pRet = a1;
694 *paOne = &a1[n1];
696 return pRet;
700 ** This function is used by changeset_concat() to merge two UPDATE changes
701 ** on the same row.
703 static int sessionMergeUpdate(
704 u8 **paOut, /* IN/OUT: Pointer to output buffer */
705 SessionTable *pTab, /* Table change pertains to */
706 int bPatchset, /* True if records are patchset records */
707 u8 *aOldRecord1, /* old.* record for first change */
708 u8 *aOldRecord2, /* old.* record for second change */
709 u8 *aNewRecord1, /* new.* record for first change */
710 u8 *aNewRecord2 /* new.* record for second change */
712 u8 *aOld1 = aOldRecord1;
713 u8 *aOld2 = aOldRecord2;
714 u8 *aNew1 = aNewRecord1;
715 u8 *aNew2 = aNewRecord2;
717 u8 *aOut = *paOut;
718 int i;
720 if( bPatchset==0 ){
721 int bRequired = 0;
723 assert( aOldRecord1 && aNewRecord1 );
725 /* Write the old.* vector first. */
726 for(i=0; i<pTab->nCol; i++){
727 int nOld;
728 u8 *aOld;
729 int nNew;
730 u8 *aNew;
732 aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
733 aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
734 if( pTab->abPK[i] || nOld!=nNew || memcmp(aOld, aNew, nNew) ){
735 if( pTab->abPK[i]==0 ) bRequired = 1;
736 memcpy(aOut, aOld, nOld);
737 aOut += nOld;
738 }else{
739 *(aOut++) = '\0';
743 if( !bRequired ) return 0;
746 /* Write the new.* vector */
747 aOld1 = aOldRecord1;
748 aOld2 = aOldRecord2;
749 aNew1 = aNewRecord1;
750 aNew2 = aNewRecord2;
751 for(i=0; i<pTab->nCol; i++){
752 int nOld;
753 u8 *aOld;
754 int nNew;
755 u8 *aNew;
757 aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
758 aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
759 if( bPatchset==0
760 && (pTab->abPK[i] || (nOld==nNew && 0==memcmp(aOld, aNew, nNew)))
762 *(aOut++) = '\0';
763 }else{
764 memcpy(aOut, aNew, nNew);
765 aOut += nNew;
769 *paOut = aOut;
770 return 1;
774 ** This function is only called from within a pre-update-hook callback.
775 ** It determines if the current pre-update-hook change affects the same row
776 ** as the change stored in argument pChange. If so, it returns true. Otherwise
777 ** if the pre-update-hook does not affect the same row as pChange, it returns
778 ** false.
780 static int sessionPreupdateEqual(
781 sqlite3_session *pSession, /* Session object that owns SessionTable */
782 SessionTable *pTab, /* Table associated with change */
783 SessionChange *pChange, /* Change to compare to */
784 int op /* Current pre-update operation */
786 int iCol; /* Used to iterate through columns */
787 u8 *a = pChange->aRecord; /* Cursor used to scan change record */
789 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
790 for(iCol=0; iCol<pTab->nCol; iCol++){
791 if( !pTab->abPK[iCol] ){
792 a += sessionSerialLen(a);
793 }else{
794 sqlite3_value *pVal; /* Value returned by preupdate_new/old */
795 int rc; /* Error code from preupdate_new/old */
796 int eType = *a++; /* Type of value from change record */
798 /* The following calls to preupdate_new() and preupdate_old() can not
799 ** fail. This is because they cache their return values, and by the
800 ** time control flows to here they have already been called once from
801 ** within sessionPreupdateHash(). The first two asserts below verify
802 ** this (that the method has already been called). */
803 if( op==SQLITE_INSERT ){
804 /* assert( db->pPreUpdate->pNewUnpacked || db->pPreUpdate->aNew ); */
805 rc = pSession->hook.xNew(pSession->hook.pCtx, iCol, &pVal);
806 }else{
807 /* assert( db->pPreUpdate->pUnpacked ); */
808 rc = pSession->hook.xOld(pSession->hook.pCtx, iCol, &pVal);
810 assert( rc==SQLITE_OK );
811 if( sqlite3_value_type(pVal)!=eType ) return 0;
813 /* A SessionChange object never has a NULL value in a PK column */
814 assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
815 || eType==SQLITE_BLOB || eType==SQLITE_TEXT
818 if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
819 i64 iVal = sessionGetI64(a);
820 a += 8;
821 if( eType==SQLITE_INTEGER ){
822 if( sqlite3_value_int64(pVal)!=iVal ) return 0;
823 }else{
824 double rVal;
825 assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
826 memcpy(&rVal, &iVal, 8);
827 if( sqlite3_value_double(pVal)!=rVal ) return 0;
829 }else{
830 int n;
831 const u8 *z;
832 a += sessionVarintGet(a, &n);
833 if( sqlite3_value_bytes(pVal)!=n ) return 0;
834 if( eType==SQLITE_TEXT ){
835 z = sqlite3_value_text(pVal);
836 }else{
837 z = sqlite3_value_blob(pVal);
839 if( memcmp(a, z, n) ) return 0;
840 a += n;
841 break;
846 return 1;
850 ** If required, grow the hash table used to store changes on table pTab
851 ** (part of the session pSession). If a fatal OOM error occurs, set the
852 ** session object to failed and return SQLITE_ERROR. Otherwise, return
853 ** SQLITE_OK.
855 ** It is possible that a non-fatal OOM error occurs in this function. In
856 ** that case the hash-table does not grow, but SQLITE_OK is returned anyway.
857 ** Growing the hash table in this case is a performance optimization only,
858 ** it is not required for correct operation.
860 static int sessionGrowHash(int bPatchset, SessionTable *pTab){
861 if( pTab->nChange==0 || pTab->nEntry>=(pTab->nChange/2) ){
862 int i;
863 SessionChange **apNew;
864 int nNew = (pTab->nChange ? pTab->nChange : 128) * 2;
866 apNew = (SessionChange **)sqlite3_malloc(sizeof(SessionChange *) * nNew);
867 if( apNew==0 ){
868 if( pTab->nChange==0 ){
869 return SQLITE_ERROR;
871 return SQLITE_OK;
873 memset(apNew, 0, sizeof(SessionChange *) * nNew);
875 for(i=0; i<pTab->nChange; i++){
876 SessionChange *p;
877 SessionChange *pNext;
878 for(p=pTab->apChange[i]; p; p=pNext){
879 int bPkOnly = (p->op==SQLITE_DELETE && bPatchset);
880 int iHash = sessionChangeHash(pTab, bPkOnly, p->aRecord, nNew);
881 pNext = p->pNext;
882 p->pNext = apNew[iHash];
883 apNew[iHash] = p;
887 sqlite3_free(pTab->apChange);
888 pTab->nChange = nNew;
889 pTab->apChange = apNew;
892 return SQLITE_OK;
896 ** This function queries the database for the names of the columns of table
897 ** zThis, in schema zDb.
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.
906 ** For example, if the table is declared as:
908 ** CREATE TABLE tbl1(w, x, y, z, PRIMARY KEY(w, z));
910 ** Then the four output variables are populated as follows:
912 ** *pnCol = 4
913 ** *pzTab = "tbl1"
914 ** *pazCol = {"w", "x", "y", "z"}
915 ** *pabPK = {1, 0, 0, 1}
917 ** All returned buffers are part of the same single allocation, which must
918 ** be freed using sqlite3_free() by the caller
920 static int sessionTableInfo(
921 sqlite3 *db, /* Database connection */
922 const char *zDb, /* Name of attached database (e.g. "main") */
923 const char *zThis, /* Table name */
924 int *pnCol, /* OUT: number of columns */
925 const char **pzTab, /* OUT: Copy of zThis */
926 const char ***pazCol, /* OUT: Array of column names for table */
927 u8 **pabPK /* OUT: Array of booleans - true for PK col */
929 char *zPragma;
930 sqlite3_stmt *pStmt;
931 int rc;
932 int nByte;
933 int nDbCol = 0;
934 int nThis;
935 int i;
936 u8 *pAlloc = 0;
937 char **azCol = 0;
938 u8 *abPK = 0;
940 assert( pazCol && pabPK );
942 nThis = sqlite3Strlen30(zThis);
943 if( nThis==12 && 0==sqlite3_stricmp("sqlite_stat1", zThis) ){
944 /* For sqlite_stat1, pretend that (tbl,idx) is the PRIMARY KEY. */
945 zPragma = sqlite3_mprintf(
946 "SELECT 0, 'tbl', '', 0, '', 1 UNION ALL "
947 "SELECT 1, 'idx', '', 0, '', 2 UNION ALL "
948 "SELECT 2, 'stat', '', 0, '', 0"
950 }else{
951 zPragma = sqlite3_mprintf("PRAGMA '%q'.table_info('%q')", zDb, zThis);
953 if( !zPragma ) return SQLITE_NOMEM;
955 rc = sqlite3_prepare_v2(db, zPragma, -1, &pStmt, 0);
956 sqlite3_free(zPragma);
957 if( rc!=SQLITE_OK ) return rc;
959 nByte = nThis + 1;
960 while( SQLITE_ROW==sqlite3_step(pStmt) ){
961 nByte += sqlite3_column_bytes(pStmt, 1);
962 nDbCol++;
964 rc = sqlite3_reset(pStmt);
966 if( rc==SQLITE_OK ){
967 nByte += nDbCol * (sizeof(const char *) + sizeof(u8) + 1);
968 pAlloc = sqlite3_malloc(nByte);
969 if( pAlloc==0 ){
970 rc = SQLITE_NOMEM;
973 if( rc==SQLITE_OK ){
974 azCol = (char **)pAlloc;
975 pAlloc = (u8 *)&azCol[nDbCol];
976 abPK = (u8 *)pAlloc;
977 pAlloc = &abPK[nDbCol];
978 if( pzTab ){
979 memcpy(pAlloc, zThis, nThis+1);
980 *pzTab = (char *)pAlloc;
981 pAlloc += nThis+1;
984 i = 0;
985 while( SQLITE_ROW==sqlite3_step(pStmt) ){
986 int nName = sqlite3_column_bytes(pStmt, 1);
987 const unsigned char *zName = sqlite3_column_text(pStmt, 1);
988 if( zName==0 ) break;
989 memcpy(pAlloc, zName, nName+1);
990 azCol[i] = (char *)pAlloc;
991 pAlloc += nName+1;
992 abPK[i] = sqlite3_column_int(pStmt, 5);
993 i++;
995 rc = sqlite3_reset(pStmt);
999 /* If successful, populate the output variables. Otherwise, zero them and
1000 ** free any allocation made. An error code will be returned in this case.
1002 if( rc==SQLITE_OK ){
1003 *pazCol = (const char **)azCol;
1004 *pabPK = abPK;
1005 *pnCol = nDbCol;
1006 }else{
1007 *pazCol = 0;
1008 *pabPK = 0;
1009 *pnCol = 0;
1010 if( pzTab ) *pzTab = 0;
1011 sqlite3_free(azCol);
1013 sqlite3_finalize(pStmt);
1014 return rc;
1018 ** This function is only called from within a pre-update handler for a
1019 ** write to table pTab, part of session pSession. If this is the first
1020 ** write to this table, initalize the SessionTable.nCol, azCol[] and
1021 ** abPK[] arrays accordingly.
1023 ** If an error occurs, an error code is stored in sqlite3_session.rc and
1024 ** non-zero returned. Or, if no error occurs but the table has no primary
1025 ** key, sqlite3_session.rc is left set to SQLITE_OK and non-zero returned to
1026 ** indicate that updates on this table should be ignored. SessionTable.abPK
1027 ** is set to NULL in this case.
1029 static int sessionInitTable(sqlite3_session *pSession, SessionTable *pTab){
1030 if( pTab->nCol==0 ){
1031 u8 *abPK;
1032 assert( pTab->azCol==0 || pTab->abPK==0 );
1033 pSession->rc = sessionTableInfo(pSession->db, pSession->zDb,
1034 pTab->zName, &pTab->nCol, 0, &pTab->azCol, &abPK
1036 if( pSession->rc==SQLITE_OK ){
1037 int i;
1038 for(i=0; i<pTab->nCol; i++){
1039 if( abPK[i] ){
1040 pTab->abPK = abPK;
1041 break;
1046 return (pSession->rc || pTab->abPK==0);
1050 ** This function is only called from with a pre-update-hook reporting a
1051 ** change on table pTab (attached to session pSession). The type of change
1052 ** (UPDATE, INSERT, DELETE) is specified by the first argument.
1054 ** Unless one is already present or an error occurs, an entry is added
1055 ** to the changed-rows hash table associated with table pTab.
1057 static void sessionPreupdateOneChange(
1058 int op, /* One of SQLITE_UPDATE, INSERT, DELETE */
1059 sqlite3_session *pSession, /* Session object pTab is attached to */
1060 SessionTable *pTab /* Table that change applies to */
1062 int iHash;
1063 int bNull = 0;
1064 int rc = SQLITE_OK;
1066 if( pSession->rc ) return;
1068 /* Load table details if required */
1069 if( sessionInitTable(pSession, pTab) ) return;
1071 /* Check the number of columns in this xPreUpdate call matches the
1072 ** number of columns in the table. */
1073 if( pTab->nCol!=pSession->hook.xCount(pSession->hook.pCtx) ){
1074 pSession->rc = SQLITE_SCHEMA;
1075 return;
1078 /* Grow the hash table if required */
1079 if( sessionGrowHash(0, pTab) ){
1080 pSession->rc = SQLITE_NOMEM;
1081 return;
1084 /* Calculate the hash-key for this change. If the primary key of the row
1085 ** includes a NULL value, exit early. Such changes are ignored by the
1086 ** session module. */
1087 rc = sessionPreupdateHash(pSession, pTab, op==SQLITE_INSERT, &iHash, &bNull);
1088 if( rc!=SQLITE_OK ) goto error_out;
1090 if( bNull==0 ){
1091 /* Search the hash table for an existing record for this row. */
1092 SessionChange *pC;
1093 for(pC=pTab->apChange[iHash]; pC; pC=pC->pNext){
1094 if( sessionPreupdateEqual(pSession, pTab, pC, op) ) break;
1097 if( pC==0 ){
1098 /* Create a new change object containing all the old values (if
1099 ** this is an SQLITE_UPDATE or SQLITE_DELETE), or just the PK
1100 ** values (if this is an INSERT). */
1101 SessionChange *pChange; /* New change object */
1102 int nByte; /* Number of bytes to allocate */
1103 int i; /* Used to iterate through columns */
1105 assert( rc==SQLITE_OK );
1106 pTab->nEntry++;
1108 /* Figure out how large an allocation is required */
1109 nByte = sizeof(SessionChange);
1110 for(i=0; i<pTab->nCol; i++){
1111 sqlite3_value *p = 0;
1112 if( op!=SQLITE_INSERT ){
1113 TESTONLY(int trc = ) pSession->hook.xOld(pSession->hook.pCtx, i, &p);
1114 assert( trc==SQLITE_OK );
1115 }else if( pTab->abPK[i] ){
1116 TESTONLY(int trc = ) pSession->hook.xNew(pSession->hook.pCtx, i, &p);
1117 assert( trc==SQLITE_OK );
1120 /* This may fail if SQLite value p contains a utf-16 string that must
1121 ** be converted to utf-8 and an OOM error occurs while doing so. */
1122 rc = sessionSerializeValue(0, p, &nByte);
1123 if( rc!=SQLITE_OK ) goto error_out;
1126 /* Allocate the change object */
1127 pChange = (SessionChange *)sqlite3_malloc(nByte);
1128 if( !pChange ){
1129 rc = SQLITE_NOMEM;
1130 goto error_out;
1131 }else{
1132 memset(pChange, 0, sizeof(SessionChange));
1133 pChange->aRecord = (u8 *)&pChange[1];
1136 /* Populate the change object. None of the preupdate_old(),
1137 ** preupdate_new() or SerializeValue() calls below may fail as all
1138 ** required values and encodings have already been cached in memory.
1139 ** It is not possible for an OOM to occur in this block. */
1140 nByte = 0;
1141 for(i=0; i<pTab->nCol; i++){
1142 sqlite3_value *p = 0;
1143 if( op!=SQLITE_INSERT ){
1144 pSession->hook.xOld(pSession->hook.pCtx, i, &p);
1145 }else if( pTab->abPK[i] ){
1146 pSession->hook.xNew(pSession->hook.pCtx, i, &p);
1148 sessionSerializeValue(&pChange->aRecord[nByte], p, &nByte);
1151 /* Add the change to the hash-table */
1152 if( pSession->bIndirect || pSession->hook.xDepth(pSession->hook.pCtx) ){
1153 pChange->bIndirect = 1;
1155 pChange->nRecord = nByte;
1156 pChange->op = op;
1157 pChange->pNext = pTab->apChange[iHash];
1158 pTab->apChange[iHash] = pChange;
1160 }else if( pC->bIndirect ){
1161 /* If the existing change is considered "indirect", but this current
1162 ** change is "direct", mark the change object as direct. */
1163 if( pSession->hook.xDepth(pSession->hook.pCtx)==0
1164 && pSession->bIndirect==0
1166 pC->bIndirect = 0;
1171 /* If an error has occurred, mark the session object as failed. */
1172 error_out:
1173 if( rc!=SQLITE_OK ){
1174 pSession->rc = rc;
1178 static int sessionFindTable(
1179 sqlite3_session *pSession,
1180 const char *zName,
1181 SessionTable **ppTab
1183 int rc = SQLITE_OK;
1184 int nName = sqlite3Strlen30(zName);
1185 SessionTable *pRet;
1187 /* Search for an existing table */
1188 for(pRet=pSession->pTable; pRet; pRet=pRet->pNext){
1189 if( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) ) break;
1192 if( pRet==0 && pSession->bAutoAttach ){
1193 /* If there is a table-filter configured, invoke it. If it returns 0,
1194 ** do not automatically add the new table. */
1195 if( pSession->xTableFilter==0
1196 || pSession->xTableFilter(pSession->pFilterCtx, zName)
1198 rc = sqlite3session_attach(pSession, zName);
1199 if( rc==SQLITE_OK ){
1200 for(pRet=pSession->pTable; pRet->pNext; pRet=pRet->pNext);
1201 assert( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) );
1206 assert( rc==SQLITE_OK || pRet==0 );
1207 *ppTab = pRet;
1208 return rc;
1212 ** The 'pre-update' hook registered by this module with SQLite databases.
1214 static void xPreUpdate(
1215 void *pCtx, /* Copy of third arg to preupdate_hook() */
1216 sqlite3 *db, /* Database handle */
1217 int op, /* SQLITE_UPDATE, DELETE or INSERT */
1218 char const *zDb, /* Database name */
1219 char const *zName, /* Table name */
1220 sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */
1221 sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */
1223 sqlite3_session *pSession;
1224 int nDb = sqlite3Strlen30(zDb);
1226 assert( sqlite3_mutex_held(db->mutex) );
1228 for(pSession=(sqlite3_session *)pCtx; pSession; pSession=pSession->pNext){
1229 SessionTable *pTab;
1231 /* If this session is attached to a different database ("main", "temp"
1232 ** etc.), or if it is not currently enabled, there is nothing to do. Skip
1233 ** to the next session object attached to this database. */
1234 if( pSession->bEnable==0 ) continue;
1235 if( pSession->rc ) continue;
1236 if( sqlite3_strnicmp(zDb, pSession->zDb, nDb+1) ) continue;
1238 pSession->rc = sessionFindTable(pSession, zName, &pTab);
1239 if( pTab ){
1240 assert( pSession->rc==SQLITE_OK );
1241 sessionPreupdateOneChange(op, pSession, pTab);
1242 if( op==SQLITE_UPDATE ){
1243 sessionPreupdateOneChange(SQLITE_INSERT, pSession, pTab);
1250 ** The pre-update hook implementations.
1252 static int sessionPreupdateOld(void *pCtx, int iVal, sqlite3_value **ppVal){
1253 return sqlite3_preupdate_old((sqlite3*)pCtx, iVal, ppVal);
1255 static int sessionPreupdateNew(void *pCtx, int iVal, sqlite3_value **ppVal){
1256 return sqlite3_preupdate_new((sqlite3*)pCtx, iVal, ppVal);
1258 static int sessionPreupdateCount(void *pCtx){
1259 return sqlite3_preupdate_count((sqlite3*)pCtx);
1261 static int sessionPreupdateDepth(void *pCtx){
1262 return sqlite3_preupdate_depth((sqlite3*)pCtx);
1266 ** Install the pre-update hooks on the session object passed as the only
1267 ** argument.
1269 static void sessionPreupdateHooks(
1270 sqlite3_session *pSession
1272 pSession->hook.pCtx = (void*)pSession->db;
1273 pSession->hook.xOld = sessionPreupdateOld;
1274 pSession->hook.xNew = sessionPreupdateNew;
1275 pSession->hook.xCount = sessionPreupdateCount;
1276 pSession->hook.xDepth = sessionPreupdateDepth;
1279 typedef struct SessionDiffCtx SessionDiffCtx;
1280 struct SessionDiffCtx {
1281 sqlite3_stmt *pStmt;
1282 int nOldOff;
1286 ** The diff hook implementations.
1288 static int sessionDiffOld(void *pCtx, int iVal, sqlite3_value **ppVal){
1289 SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
1290 *ppVal = sqlite3_column_value(p->pStmt, iVal+p->nOldOff);
1291 return SQLITE_OK;
1293 static int sessionDiffNew(void *pCtx, int iVal, sqlite3_value **ppVal){
1294 SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
1295 *ppVal = sqlite3_column_value(p->pStmt, iVal);
1296 return SQLITE_OK;
1298 static int sessionDiffCount(void *pCtx){
1299 SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
1300 return p->nOldOff ? p->nOldOff : sqlite3_column_count(p->pStmt);
1302 static int sessionDiffDepth(void *pCtx){
1303 return 0;
1307 ** Install the diff hooks on the session object passed as the only
1308 ** argument.
1310 static void sessionDiffHooks(
1311 sqlite3_session *pSession,
1312 SessionDiffCtx *pDiffCtx
1314 pSession->hook.pCtx = (void*)pDiffCtx;
1315 pSession->hook.xOld = sessionDiffOld;
1316 pSession->hook.xNew = sessionDiffNew;
1317 pSession->hook.xCount = sessionDiffCount;
1318 pSession->hook.xDepth = sessionDiffDepth;
1321 static char *sessionExprComparePK(
1322 int nCol,
1323 const char *zDb1, const char *zDb2,
1324 const char *zTab,
1325 const char **azCol, u8 *abPK
1327 int i;
1328 const char *zSep = "";
1329 char *zRet = 0;
1331 for(i=0; i<nCol; i++){
1332 if( abPK[i] ){
1333 zRet = sqlite3_mprintf("%z%s\"%w\".\"%w\".\"%w\"=\"%w\".\"%w\".\"%w\"",
1334 zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
1336 zSep = " AND ";
1337 if( zRet==0 ) break;
1341 return zRet;
1344 static char *sessionExprCompareOther(
1345 int nCol,
1346 const char *zDb1, const char *zDb2,
1347 const char *zTab,
1348 const char **azCol, u8 *abPK
1350 int i;
1351 const char *zSep = "";
1352 char *zRet = 0;
1353 int bHave = 0;
1355 for(i=0; i<nCol; i++){
1356 if( abPK[i]==0 ){
1357 bHave = 1;
1358 zRet = sqlite3_mprintf(
1359 "%z%s\"%w\".\"%w\".\"%w\" IS NOT \"%w\".\"%w\".\"%w\"",
1360 zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
1362 zSep = " OR ";
1363 if( zRet==0 ) break;
1367 if( bHave==0 ){
1368 assert( zRet==0 );
1369 zRet = sqlite3_mprintf("0");
1372 return zRet;
1375 static char *sessionSelectFindNew(
1376 int nCol,
1377 const char *zDb1, /* Pick rows in this db only */
1378 const char *zDb2, /* But not in this one */
1379 const char *zTbl, /* Table name */
1380 const char *zExpr
1382 char *zRet = sqlite3_mprintf(
1383 "SELECT * FROM \"%w\".\"%w\" WHERE NOT EXISTS ("
1384 " SELECT 1 FROM \"%w\".\"%w\" WHERE %s"
1385 ")",
1386 zDb1, zTbl, zDb2, zTbl, zExpr
1388 return zRet;
1391 static int sessionDiffFindNew(
1392 int op,
1393 sqlite3_session *pSession,
1394 SessionTable *pTab,
1395 const char *zDb1,
1396 const char *zDb2,
1397 char *zExpr
1399 int rc = SQLITE_OK;
1400 char *zStmt = sessionSelectFindNew(pTab->nCol, zDb1, zDb2, pTab->zName,zExpr);
1402 if( zStmt==0 ){
1403 rc = SQLITE_NOMEM;
1404 }else{
1405 sqlite3_stmt *pStmt;
1406 rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
1407 if( rc==SQLITE_OK ){
1408 SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
1409 pDiffCtx->pStmt = pStmt;
1410 pDiffCtx->nOldOff = 0;
1411 while( SQLITE_ROW==sqlite3_step(pStmt) ){
1412 sessionPreupdateOneChange(op, pSession, pTab);
1414 rc = sqlite3_finalize(pStmt);
1416 sqlite3_free(zStmt);
1419 return rc;
1422 static int sessionDiffFindModified(
1423 sqlite3_session *pSession,
1424 SessionTable *pTab,
1425 const char *zFrom,
1426 const char *zExpr
1428 int rc = SQLITE_OK;
1430 char *zExpr2 = sessionExprCompareOther(pTab->nCol,
1431 pSession->zDb, zFrom, pTab->zName, pTab->azCol, pTab->abPK
1433 if( zExpr2==0 ){
1434 rc = SQLITE_NOMEM;
1435 }else{
1436 char *zStmt = sqlite3_mprintf(
1437 "SELECT * FROM \"%w\".\"%w\", \"%w\".\"%w\" WHERE %s AND (%z)",
1438 pSession->zDb, pTab->zName, zFrom, pTab->zName, zExpr, zExpr2
1440 if( zStmt==0 ){
1441 rc = SQLITE_NOMEM;
1442 }else{
1443 sqlite3_stmt *pStmt;
1444 rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
1446 if( rc==SQLITE_OK ){
1447 SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
1448 pDiffCtx->pStmt = pStmt;
1449 pDiffCtx->nOldOff = pTab->nCol;
1450 while( SQLITE_ROW==sqlite3_step(pStmt) ){
1451 sessionPreupdateOneChange(SQLITE_UPDATE, pSession, pTab);
1453 rc = sqlite3_finalize(pStmt);
1455 sqlite3_free(zStmt);
1459 return rc;
1462 int sqlite3session_diff(
1463 sqlite3_session *pSession,
1464 const char *zFrom,
1465 const char *zTbl,
1466 char **pzErrMsg
1468 const char *zDb = pSession->zDb;
1469 int rc = pSession->rc;
1470 SessionDiffCtx d;
1472 memset(&d, 0, sizeof(d));
1473 sessionDiffHooks(pSession, &d);
1475 sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
1476 if( pzErrMsg ) *pzErrMsg = 0;
1477 if( rc==SQLITE_OK ){
1478 char *zExpr = 0;
1479 sqlite3 *db = pSession->db;
1480 SessionTable *pTo; /* Table zTbl */
1482 /* Locate and if necessary initialize the target table object */
1483 rc = sessionFindTable(pSession, zTbl, &pTo);
1484 if( pTo==0 ) goto diff_out;
1485 if( sessionInitTable(pSession, pTo) ){
1486 rc = pSession->rc;
1487 goto diff_out;
1490 /* Check the table schemas match */
1491 if( rc==SQLITE_OK ){
1492 int bHasPk = 0;
1493 int bMismatch = 0;
1494 int nCol; /* Columns in zFrom.zTbl */
1495 u8 *abPK;
1496 const char **azCol = 0;
1497 rc = sessionTableInfo(db, zFrom, zTbl, &nCol, 0, &azCol, &abPK);
1498 if( rc==SQLITE_OK ){
1499 if( pTo->nCol!=nCol ){
1500 bMismatch = 1;
1501 }else{
1502 int i;
1503 for(i=0; i<nCol; i++){
1504 if( pTo->abPK[i]!=abPK[i] ) bMismatch = 1;
1505 if( sqlite3_stricmp(azCol[i], pTo->azCol[i]) ) bMismatch = 1;
1506 if( abPK[i] ) bHasPk = 1;
1511 sqlite3_free((char*)azCol);
1512 if( bMismatch ){
1513 *pzErrMsg = sqlite3_mprintf("table schemas do not match");
1514 rc = SQLITE_SCHEMA;
1516 if( bHasPk==0 ){
1517 /* Ignore tables with no primary keys */
1518 goto diff_out;
1522 if( rc==SQLITE_OK ){
1523 zExpr = sessionExprComparePK(pTo->nCol,
1524 zDb, zFrom, pTo->zName, pTo->azCol, pTo->abPK
1528 /* Find new rows */
1529 if( rc==SQLITE_OK ){
1530 rc = sessionDiffFindNew(SQLITE_INSERT, pSession, pTo, zDb, zFrom, zExpr);
1533 /* Find old rows */
1534 if( rc==SQLITE_OK ){
1535 rc = sessionDiffFindNew(SQLITE_DELETE, pSession, pTo, zFrom, zDb, zExpr);
1538 /* Find modified rows */
1539 if( rc==SQLITE_OK ){
1540 rc = sessionDiffFindModified(pSession, pTo, zFrom, zExpr);
1543 sqlite3_free(zExpr);
1546 diff_out:
1547 sessionPreupdateHooks(pSession);
1548 sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
1549 return rc;
1553 ** Create a session object. This session object will record changes to
1554 ** database zDb attached to connection db.
1556 int sqlite3session_create(
1557 sqlite3 *db, /* Database handle */
1558 const char *zDb, /* Name of db (e.g. "main") */
1559 sqlite3_session **ppSession /* OUT: New session object */
1561 sqlite3_session *pNew; /* Newly allocated session object */
1562 sqlite3_session *pOld; /* Session object already attached to db */
1563 int nDb = sqlite3Strlen30(zDb); /* Length of zDb in bytes */
1565 /* Zero the output value in case an error occurs. */
1566 *ppSession = 0;
1568 /* Allocate and populate the new session object. */
1569 pNew = (sqlite3_session *)sqlite3_malloc(sizeof(sqlite3_session) + nDb + 1);
1570 if( !pNew ) return SQLITE_NOMEM;
1571 memset(pNew, 0, sizeof(sqlite3_session));
1572 pNew->db = db;
1573 pNew->zDb = (char *)&pNew[1];
1574 pNew->bEnable = 1;
1575 memcpy(pNew->zDb, zDb, nDb+1);
1576 sessionPreupdateHooks(pNew);
1578 /* Add the new session object to the linked list of session objects
1579 ** attached to database handle $db. Do this under the cover of the db
1580 ** handle mutex. */
1581 sqlite3_mutex_enter(sqlite3_db_mutex(db));
1582 pOld = (sqlite3_session*)sqlite3_preupdate_hook(db, xPreUpdate, (void*)pNew);
1583 pNew->pNext = pOld;
1584 sqlite3_mutex_leave(sqlite3_db_mutex(db));
1586 *ppSession = pNew;
1587 return SQLITE_OK;
1591 ** Free the list of table objects passed as the first argument. The contents
1592 ** of the changed-rows hash tables are also deleted.
1594 static void sessionDeleteTable(SessionTable *pList){
1595 SessionTable *pNext;
1596 SessionTable *pTab;
1598 for(pTab=pList; pTab; pTab=pNext){
1599 int i;
1600 pNext = pTab->pNext;
1601 for(i=0; i<pTab->nChange; i++){
1602 SessionChange *p;
1603 SessionChange *pNextChange;
1604 for(p=pTab->apChange[i]; p; p=pNextChange){
1605 pNextChange = p->pNext;
1606 sqlite3_free(p);
1609 sqlite3_free((char*)pTab->azCol); /* cast works around VC++ bug */
1610 sqlite3_free(pTab->apChange);
1611 sqlite3_free(pTab);
1616 ** Delete a session object previously allocated using sqlite3session_create().
1618 void sqlite3session_delete(sqlite3_session *pSession){
1619 sqlite3 *db = pSession->db;
1620 sqlite3_session *pHead;
1621 sqlite3_session **pp;
1623 /* Unlink the session from the linked list of sessions attached to the
1624 ** database handle. Hold the db mutex while doing so. */
1625 sqlite3_mutex_enter(sqlite3_db_mutex(db));
1626 pHead = (sqlite3_session*)sqlite3_preupdate_hook(db, 0, 0);
1627 for(pp=&pHead; ALWAYS((*pp)!=0); pp=&((*pp)->pNext)){
1628 if( (*pp)==pSession ){
1629 *pp = (*pp)->pNext;
1630 if( pHead ) sqlite3_preupdate_hook(db, xPreUpdate, (void*)pHead);
1631 break;
1634 sqlite3_mutex_leave(sqlite3_db_mutex(db));
1636 /* Delete all attached table objects. And the contents of their
1637 ** associated hash-tables. */
1638 sessionDeleteTable(pSession->pTable);
1640 /* Free the session object itself. */
1641 sqlite3_free(pSession);
1645 ** Set a table filter on a Session Object.
1647 void sqlite3session_table_filter(
1648 sqlite3_session *pSession,
1649 int(*xFilter)(void*, const char*),
1650 void *pCtx /* First argument passed to xFilter */
1652 pSession->bAutoAttach = 1;
1653 pSession->pFilterCtx = pCtx;
1654 pSession->xTableFilter = xFilter;
1658 ** Attach a table to a session. All subsequent changes made to the table
1659 ** while the session object is enabled will be recorded.
1661 ** Only tables that have a PRIMARY KEY defined may be attached. It does
1662 ** not matter if the PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias)
1663 ** or not.
1665 int sqlite3session_attach(
1666 sqlite3_session *pSession, /* Session object */
1667 const char *zName /* Table name */
1669 int rc = SQLITE_OK;
1670 sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
1672 if( !zName ){
1673 pSession->bAutoAttach = 1;
1674 }else{
1675 SessionTable *pTab; /* New table object (if required) */
1676 int nName; /* Number of bytes in string zName */
1678 /* First search for an existing entry. If one is found, this call is
1679 ** a no-op. Return early. */
1680 nName = sqlite3Strlen30(zName);
1681 for(pTab=pSession->pTable; pTab; pTab=pTab->pNext){
1682 if( 0==sqlite3_strnicmp(pTab->zName, zName, nName+1) ) break;
1685 if( !pTab ){
1686 /* Allocate new SessionTable object. */
1687 pTab = (SessionTable *)sqlite3_malloc(sizeof(SessionTable) + nName + 1);
1688 if( !pTab ){
1689 rc = SQLITE_NOMEM;
1690 }else{
1691 /* Populate the new SessionTable object and link it into the list.
1692 ** The new object must be linked onto the end of the list, not
1693 ** simply added to the start of it in order to ensure that tables
1694 ** appear in the correct order when a changeset or patchset is
1695 ** eventually generated. */
1696 SessionTable **ppTab;
1697 memset(pTab, 0, sizeof(SessionTable));
1698 pTab->zName = (char *)&pTab[1];
1699 memcpy(pTab->zName, zName, nName+1);
1700 for(ppTab=&pSession->pTable; *ppTab; ppTab=&(*ppTab)->pNext);
1701 *ppTab = pTab;
1706 sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
1707 return rc;
1711 ** Ensure that there is room in the buffer to append nByte bytes of data.
1712 ** If not, use sqlite3_realloc() to grow the buffer so that there is.
1714 ** If successful, return zero. Otherwise, if an OOM condition is encountered,
1715 ** set *pRc to SQLITE_NOMEM and return non-zero.
1717 static int sessionBufferGrow(SessionBuffer *p, int nByte, int *pRc){
1718 if( *pRc==SQLITE_OK && p->nAlloc-p->nBuf<nByte ){
1719 u8 *aNew;
1720 int nNew = p->nAlloc ? p->nAlloc : 128;
1721 do {
1722 nNew = nNew*2;
1723 }while( nNew<(p->nBuf+nByte) );
1725 aNew = (u8 *)sqlite3_realloc(p->aBuf, nNew);
1726 if( 0==aNew ){
1727 *pRc = SQLITE_NOMEM;
1728 }else{
1729 p->aBuf = aNew;
1730 p->nAlloc = nNew;
1733 return (*pRc!=SQLITE_OK);
1737 ** Append the value passed as the second argument to the buffer passed
1738 ** as the first.
1740 ** This function is a no-op if *pRc is non-zero when it is called.
1741 ** Otherwise, if an error occurs, *pRc is set to an SQLite error code
1742 ** before returning.
1744 static void sessionAppendValue(SessionBuffer *p, sqlite3_value *pVal, int *pRc){
1745 int rc = *pRc;
1746 if( rc==SQLITE_OK ){
1747 int nByte = 0;
1748 rc = sessionSerializeValue(0, pVal, &nByte);
1749 sessionBufferGrow(p, nByte, &rc);
1750 if( rc==SQLITE_OK ){
1751 rc = sessionSerializeValue(&p->aBuf[p->nBuf], pVal, 0);
1752 p->nBuf += nByte;
1753 }else{
1754 *pRc = rc;
1760 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
1761 ** called. Otherwise, append a single byte to the buffer.
1763 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
1764 ** returning.
1766 static void sessionAppendByte(SessionBuffer *p, u8 v, int *pRc){
1767 if( 0==sessionBufferGrow(p, 1, pRc) ){
1768 p->aBuf[p->nBuf++] = v;
1773 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
1774 ** called. Otherwise, append a single varint to the buffer.
1776 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
1777 ** returning.
1779 static void sessionAppendVarint(SessionBuffer *p, int v, int *pRc){
1780 if( 0==sessionBufferGrow(p, 9, pRc) ){
1781 p->nBuf += sessionVarintPut(&p->aBuf[p->nBuf], v);
1786 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
1787 ** called. Otherwise, append a blob of data to the buffer.
1789 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
1790 ** returning.
1792 static void sessionAppendBlob(
1793 SessionBuffer *p,
1794 const u8 *aBlob,
1795 int nBlob,
1796 int *pRc
1798 if( nBlob>0 && 0==sessionBufferGrow(p, nBlob, pRc) ){
1799 memcpy(&p->aBuf[p->nBuf], aBlob, nBlob);
1800 p->nBuf += nBlob;
1805 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
1806 ** called. Otherwise, append a string to the buffer. All bytes in the string
1807 ** up to (but not including) the nul-terminator are written to the buffer.
1809 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
1810 ** returning.
1812 static void sessionAppendStr(
1813 SessionBuffer *p,
1814 const char *zStr,
1815 int *pRc
1817 int nStr = sqlite3Strlen30(zStr);
1818 if( 0==sessionBufferGrow(p, nStr, pRc) ){
1819 memcpy(&p->aBuf[p->nBuf], zStr, nStr);
1820 p->nBuf += nStr;
1825 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
1826 ** called. Otherwise, append the string representation of integer iVal
1827 ** to the buffer. No nul-terminator is written.
1829 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
1830 ** returning.
1832 static void sessionAppendInteger(
1833 SessionBuffer *p, /* Buffer to append to */
1834 int iVal, /* Value to write the string rep. of */
1835 int *pRc /* IN/OUT: Error code */
1837 char aBuf[24];
1838 sqlite3_snprintf(sizeof(aBuf)-1, aBuf, "%d", iVal);
1839 sessionAppendStr(p, aBuf, pRc);
1843 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
1844 ** called. Otherwise, append the string zStr enclosed in quotes (") and
1845 ** with any embedded quote characters escaped to the buffer. No
1846 ** nul-terminator byte is written.
1848 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
1849 ** returning.
1851 static void sessionAppendIdent(
1852 SessionBuffer *p, /* Buffer to a append to */
1853 const char *zStr, /* String to quote, escape and append */
1854 int *pRc /* IN/OUT: Error code */
1856 int nStr = sqlite3Strlen30(zStr)*2 + 2 + 1;
1857 if( 0==sessionBufferGrow(p, nStr, pRc) ){
1858 char *zOut = (char *)&p->aBuf[p->nBuf];
1859 const char *zIn = zStr;
1860 *zOut++ = '"';
1861 while( *zIn ){
1862 if( *zIn=='"' ) *zOut++ = '"';
1863 *zOut++ = *(zIn++);
1865 *zOut++ = '"';
1866 p->nBuf = (int)((u8 *)zOut - p->aBuf);
1871 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
1872 ** called. Otherwse, it appends the serialized version of the value stored
1873 ** in column iCol of the row that SQL statement pStmt currently points
1874 ** to to the buffer.
1876 static void sessionAppendCol(
1877 SessionBuffer *p, /* Buffer to append to */
1878 sqlite3_stmt *pStmt, /* Handle pointing to row containing value */
1879 int iCol, /* Column to read value from */
1880 int *pRc /* IN/OUT: Error code */
1882 if( *pRc==SQLITE_OK ){
1883 int eType = sqlite3_column_type(pStmt, iCol);
1884 sessionAppendByte(p, (u8)eType, pRc);
1885 if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
1886 sqlite3_int64 i;
1887 u8 aBuf[8];
1888 if( eType==SQLITE_INTEGER ){
1889 i = sqlite3_column_int64(pStmt, iCol);
1890 }else{
1891 double r = sqlite3_column_double(pStmt, iCol);
1892 memcpy(&i, &r, 8);
1894 sessionPutI64(aBuf, i);
1895 sessionAppendBlob(p, aBuf, 8, pRc);
1897 if( eType==SQLITE_BLOB || eType==SQLITE_TEXT ){
1898 u8 *z;
1899 int nByte;
1900 if( eType==SQLITE_BLOB ){
1901 z = (u8 *)sqlite3_column_blob(pStmt, iCol);
1902 }else{
1903 z = (u8 *)sqlite3_column_text(pStmt, iCol);
1905 nByte = sqlite3_column_bytes(pStmt, iCol);
1906 if( z || (eType==SQLITE_BLOB && nByte==0) ){
1907 sessionAppendVarint(p, nByte, pRc);
1908 sessionAppendBlob(p, z, nByte, pRc);
1909 }else{
1910 *pRc = SQLITE_NOMEM;
1918 ** This function appends an update change to the buffer (see the comments
1919 ** under "CHANGESET FORMAT" at the top of the file). An update change
1920 ** consists of:
1922 ** 1 byte: SQLITE_UPDATE (0x17)
1923 ** n bytes: old.* record (see RECORD FORMAT)
1924 ** m bytes: new.* record (see RECORD FORMAT)
1926 ** The SessionChange object passed as the third argument contains the
1927 ** values that were stored in the row when the session began (the old.*
1928 ** values). The statement handle passed as the second argument points
1929 ** at the current version of the row (the new.* values).
1931 ** If all of the old.* values are equal to their corresponding new.* value
1932 ** (i.e. nothing has changed), then no data at all is appended to the buffer.
1934 ** Otherwise, the old.* record contains all primary key values and the
1935 ** original values of any fields that have been modified. The new.* record
1936 ** contains the new values of only those fields that have been modified.
1938 static int sessionAppendUpdate(
1939 SessionBuffer *pBuf, /* Buffer to append to */
1940 int bPatchset, /* True for "patchset", 0 for "changeset" */
1941 sqlite3_stmt *pStmt, /* Statement handle pointing at new row */
1942 SessionChange *p, /* Object containing old values */
1943 u8 *abPK /* Boolean array - true for PK columns */
1945 int rc = SQLITE_OK;
1946 SessionBuffer buf2 = {0,0,0}; /* Buffer to accumulate new.* record in */
1947 int bNoop = 1; /* Set to zero if any values are modified */
1948 int nRewind = pBuf->nBuf; /* Set to zero if any values are modified */
1949 int i; /* Used to iterate through columns */
1950 u8 *pCsr = p->aRecord; /* Used to iterate through old.* values */
1952 sessionAppendByte(pBuf, SQLITE_UPDATE, &rc);
1953 sessionAppendByte(pBuf, p->bIndirect, &rc);
1954 for(i=0; i<sqlite3_column_count(pStmt); i++){
1955 int bChanged = 0;
1956 int nAdvance;
1957 int eType = *pCsr;
1958 switch( eType ){
1959 case SQLITE_NULL:
1960 nAdvance = 1;
1961 if( sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
1962 bChanged = 1;
1964 break;
1966 case SQLITE_FLOAT:
1967 case SQLITE_INTEGER: {
1968 nAdvance = 9;
1969 if( eType==sqlite3_column_type(pStmt, i) ){
1970 sqlite3_int64 iVal = sessionGetI64(&pCsr[1]);
1971 if( eType==SQLITE_INTEGER ){
1972 if( iVal==sqlite3_column_int64(pStmt, i) ) break;
1973 }else{
1974 double dVal;
1975 memcpy(&dVal, &iVal, 8);
1976 if( dVal==sqlite3_column_double(pStmt, i) ) break;
1979 bChanged = 1;
1980 break;
1983 default: {
1984 int n;
1985 int nHdr = 1 + sessionVarintGet(&pCsr[1], &n);
1986 assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
1987 nAdvance = nHdr + n;
1988 if( eType==sqlite3_column_type(pStmt, i)
1989 && n==sqlite3_column_bytes(pStmt, i)
1990 && (n==0 || 0==memcmp(&pCsr[nHdr], sqlite3_column_blob(pStmt, i), n))
1992 break;
1994 bChanged = 1;
1998 /* If at least one field has been modified, this is not a no-op. */
1999 if( bChanged ) bNoop = 0;
2001 /* Add a field to the old.* record. This is omitted if this modules is
2002 ** currently generating a patchset. */
2003 if( bPatchset==0 ){
2004 if( bChanged || abPK[i] ){
2005 sessionAppendBlob(pBuf, pCsr, nAdvance, &rc);
2006 }else{
2007 sessionAppendByte(pBuf, 0, &rc);
2011 /* Add a field to the new.* record. Or the only record if currently
2012 ** generating a patchset. */
2013 if( bChanged || (bPatchset && abPK[i]) ){
2014 sessionAppendCol(&buf2, pStmt, i, &rc);
2015 }else{
2016 sessionAppendByte(&buf2, 0, &rc);
2019 pCsr += nAdvance;
2022 if( bNoop ){
2023 pBuf->nBuf = nRewind;
2024 }else{
2025 sessionAppendBlob(pBuf, buf2.aBuf, buf2.nBuf, &rc);
2027 sqlite3_free(buf2.aBuf);
2029 return rc;
2033 ** Append a DELETE change to the buffer passed as the first argument. Use
2034 ** the changeset format if argument bPatchset is zero, or the patchset
2035 ** format otherwise.
2037 static int sessionAppendDelete(
2038 SessionBuffer *pBuf, /* Buffer to append to */
2039 int bPatchset, /* True for "patchset", 0 for "changeset" */
2040 SessionChange *p, /* Object containing old values */
2041 int nCol, /* Number of columns in table */
2042 u8 *abPK /* Boolean array - true for PK columns */
2044 int rc = SQLITE_OK;
2046 sessionAppendByte(pBuf, SQLITE_DELETE, &rc);
2047 sessionAppendByte(pBuf, p->bIndirect, &rc);
2049 if( bPatchset==0 ){
2050 sessionAppendBlob(pBuf, p->aRecord, p->nRecord, &rc);
2051 }else{
2052 int i;
2053 u8 *a = p->aRecord;
2054 for(i=0; i<nCol; i++){
2055 u8 *pStart = a;
2056 int eType = *a++;
2058 switch( eType ){
2059 case 0:
2060 case SQLITE_NULL:
2061 assert( abPK[i]==0 );
2062 break;
2064 case SQLITE_FLOAT:
2065 case SQLITE_INTEGER:
2066 a += 8;
2067 break;
2069 default: {
2070 int n;
2071 a += sessionVarintGet(a, &n);
2072 a += n;
2073 break;
2076 if( abPK[i] ){
2077 sessionAppendBlob(pBuf, pStart, (int)(a-pStart), &rc);
2080 assert( (a - p->aRecord)==p->nRecord );
2083 return rc;
2087 ** Formulate and prepare a SELECT statement to retrieve a row from table
2088 ** zTab in database zDb based on its primary key. i.e.
2090 ** SELECT * FROM zDb.zTab WHERE pk1 = ? AND pk2 = ? AND ...
2092 static int sessionSelectStmt(
2093 sqlite3 *db, /* Database handle */
2094 const char *zDb, /* Database name */
2095 const char *zTab, /* Table name */
2096 int nCol, /* Number of columns in table */
2097 const char **azCol, /* Names of table columns */
2098 u8 *abPK, /* PRIMARY KEY array */
2099 sqlite3_stmt **ppStmt /* OUT: Prepared SELECT statement */
2101 int rc = SQLITE_OK;
2102 int i;
2103 const char *zSep = "";
2104 SessionBuffer buf = {0, 0, 0};
2106 sessionAppendStr(&buf, "SELECT * FROM ", &rc);
2107 sessionAppendIdent(&buf, zDb, &rc);
2108 sessionAppendStr(&buf, ".", &rc);
2109 sessionAppendIdent(&buf, zTab, &rc);
2110 sessionAppendStr(&buf, " WHERE ", &rc);
2111 for(i=0; i<nCol; i++){
2112 if( abPK[i] ){
2113 sessionAppendStr(&buf, zSep, &rc);
2114 sessionAppendIdent(&buf, azCol[i], &rc);
2115 sessionAppendStr(&buf, " = ?", &rc);
2116 sessionAppendInteger(&buf, i+1, &rc);
2117 zSep = " AND ";
2120 if( rc==SQLITE_OK ){
2121 rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, ppStmt, 0);
2123 sqlite3_free(buf.aBuf);
2124 return rc;
2128 ** Bind the PRIMARY KEY values from the change passed in argument pChange
2129 ** to the SELECT statement passed as the first argument. The SELECT statement
2130 ** is as prepared by function sessionSelectStmt().
2132 ** Return SQLITE_OK if all PK values are successfully bound, or an SQLite
2133 ** error code (e.g. SQLITE_NOMEM) otherwise.
2135 static int sessionSelectBind(
2136 sqlite3_stmt *pSelect, /* SELECT from sessionSelectStmt() */
2137 int nCol, /* Number of columns in table */
2138 u8 *abPK, /* PRIMARY KEY array */
2139 SessionChange *pChange /* Change structure */
2141 int i;
2142 int rc = SQLITE_OK;
2143 u8 *a = pChange->aRecord;
2145 for(i=0; i<nCol && rc==SQLITE_OK; i++){
2146 int eType = *a++;
2148 switch( eType ){
2149 case 0:
2150 case SQLITE_NULL:
2151 assert( abPK[i]==0 );
2152 break;
2154 case SQLITE_INTEGER: {
2155 if( abPK[i] ){
2156 i64 iVal = sessionGetI64(a);
2157 rc = sqlite3_bind_int64(pSelect, i+1, iVal);
2159 a += 8;
2160 break;
2163 case SQLITE_FLOAT: {
2164 if( abPK[i] ){
2165 double rVal;
2166 i64 iVal = sessionGetI64(a);
2167 memcpy(&rVal, &iVal, 8);
2168 rc = sqlite3_bind_double(pSelect, i+1, rVal);
2170 a += 8;
2171 break;
2174 case SQLITE_TEXT: {
2175 int n;
2176 a += sessionVarintGet(a, &n);
2177 if( abPK[i] ){
2178 rc = sqlite3_bind_text(pSelect, i+1, (char *)a, n, SQLITE_TRANSIENT);
2180 a += n;
2181 break;
2184 default: {
2185 int n;
2186 assert( eType==SQLITE_BLOB );
2187 a += sessionVarintGet(a, &n);
2188 if( abPK[i] ){
2189 rc = sqlite3_bind_blob(pSelect, i+1, a, n, SQLITE_TRANSIENT);
2191 a += n;
2192 break;
2197 return rc;
2201 ** This function is a no-op if *pRc is set to other than SQLITE_OK when it
2202 ** is called. Otherwise, append a serialized table header (part of the binary
2203 ** changeset format) to buffer *pBuf. If an error occurs, set *pRc to an
2204 ** SQLite error code before returning.
2206 static void sessionAppendTableHdr(
2207 SessionBuffer *pBuf, /* Append header to this buffer */
2208 int bPatchset, /* Use the patchset format if true */
2209 SessionTable *pTab, /* Table object to append header for */
2210 int *pRc /* IN/OUT: Error code */
2212 /* Write a table header */
2213 sessionAppendByte(pBuf, (bPatchset ? 'P' : 'T'), pRc);
2214 sessionAppendVarint(pBuf, pTab->nCol, pRc);
2215 sessionAppendBlob(pBuf, pTab->abPK, pTab->nCol, pRc);
2216 sessionAppendBlob(pBuf, (u8 *)pTab->zName, (int)strlen(pTab->zName)+1, pRc);
2220 ** Generate either a changeset (if argument bPatchset is zero) or a patchset
2221 ** (if it is non-zero) based on the current contents of the session object
2222 ** passed as the first argument.
2224 ** If no error occurs, SQLITE_OK is returned and the new changeset/patchset
2225 ** stored in output variables *pnChangeset and *ppChangeset. Or, if an error
2226 ** occurs, an SQLite error code is returned and both output variables set
2227 ** to 0.
2229 static int sessionGenerateChangeset(
2230 sqlite3_session *pSession, /* Session object */
2231 int bPatchset, /* True for patchset, false for changeset */
2232 int (*xOutput)(void *pOut, const void *pData, int nData),
2233 void *pOut, /* First argument for xOutput */
2234 int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
2235 void **ppChangeset /* OUT: Buffer containing changeset */
2237 sqlite3 *db = pSession->db; /* Source database handle */
2238 SessionTable *pTab; /* Used to iterate through attached tables */
2239 SessionBuffer buf = {0,0,0}; /* Buffer in which to accumlate changeset */
2240 int rc; /* Return code */
2242 assert( xOutput==0 || (pnChangeset==0 && ppChangeset==0 ) );
2244 /* Zero the output variables in case an error occurs. If this session
2245 ** object is already in the error state (sqlite3_session.rc != SQLITE_OK),
2246 ** this call will be a no-op. */
2247 if( xOutput==0 ){
2248 *pnChangeset = 0;
2249 *ppChangeset = 0;
2252 if( pSession->rc ) return pSession->rc;
2253 rc = sqlite3_exec(pSession->db, "SAVEPOINT changeset", 0, 0, 0);
2254 if( rc!=SQLITE_OK ) return rc;
2256 sqlite3_mutex_enter(sqlite3_db_mutex(db));
2258 for(pTab=pSession->pTable; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
2259 if( pTab->nEntry ){
2260 const char *zName = pTab->zName;
2261 int nCol; /* Number of columns in table */
2262 u8 *abPK; /* Primary key array */
2263 const char **azCol = 0; /* Table columns */
2264 int i; /* Used to iterate through hash buckets */
2265 sqlite3_stmt *pSel = 0; /* SELECT statement to query table pTab */
2266 int nRewind = buf.nBuf; /* Initial size of write buffer */
2267 int nNoop; /* Size of buffer after writing tbl header */
2269 /* Check the table schema is still Ok. */
2270 rc = sessionTableInfo(db, pSession->zDb, zName, &nCol, 0, &azCol, &abPK);
2271 if( !rc && (pTab->nCol!=nCol || memcmp(abPK, pTab->abPK, nCol)) ){
2272 rc = SQLITE_SCHEMA;
2275 /* Write a table header */
2276 sessionAppendTableHdr(&buf, bPatchset, pTab, &rc);
2278 /* Build and compile a statement to execute: */
2279 if( rc==SQLITE_OK ){
2280 rc = sessionSelectStmt(
2281 db, pSession->zDb, zName, nCol, azCol, abPK, &pSel);
2284 nNoop = buf.nBuf;
2285 for(i=0; i<pTab->nChange && rc==SQLITE_OK; i++){
2286 SessionChange *p; /* Used to iterate through changes */
2288 for(p=pTab->apChange[i]; rc==SQLITE_OK && p; p=p->pNext){
2289 rc = sessionSelectBind(pSel, nCol, abPK, p);
2290 if( rc!=SQLITE_OK ) continue;
2291 if( sqlite3_step(pSel)==SQLITE_ROW ){
2292 if( p->op==SQLITE_INSERT ){
2293 int iCol;
2294 sessionAppendByte(&buf, SQLITE_INSERT, &rc);
2295 sessionAppendByte(&buf, p->bIndirect, &rc);
2296 for(iCol=0; iCol<nCol; iCol++){
2297 sessionAppendCol(&buf, pSel, iCol, &rc);
2299 }else{
2300 rc = sessionAppendUpdate(&buf, bPatchset, pSel, p, abPK);
2302 }else if( p->op!=SQLITE_INSERT ){
2303 rc = sessionAppendDelete(&buf, bPatchset, p, nCol, abPK);
2305 if( rc==SQLITE_OK ){
2306 rc = sqlite3_reset(pSel);
2309 /* If the buffer is now larger than SESSIONS_STRM_CHUNK_SIZE, pass
2310 ** its contents to the xOutput() callback. */
2311 if( xOutput
2312 && rc==SQLITE_OK
2313 && buf.nBuf>nNoop
2314 && buf.nBuf>SESSIONS_STRM_CHUNK_SIZE
2316 rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
2317 nNoop = -1;
2318 buf.nBuf = 0;
2324 sqlite3_finalize(pSel);
2325 if( buf.nBuf==nNoop ){
2326 buf.nBuf = nRewind;
2328 sqlite3_free((char*)azCol); /* cast works around VC++ bug */
2332 if( rc==SQLITE_OK ){
2333 if( xOutput==0 ){
2334 *pnChangeset = buf.nBuf;
2335 *ppChangeset = buf.aBuf;
2336 buf.aBuf = 0;
2337 }else if( buf.nBuf>0 ){
2338 rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
2342 sqlite3_free(buf.aBuf);
2343 sqlite3_exec(db, "RELEASE changeset", 0, 0, 0);
2344 sqlite3_mutex_leave(sqlite3_db_mutex(db));
2345 return rc;
2349 ** Obtain a changeset object containing all changes recorded by the
2350 ** session object passed as the first argument.
2352 ** It is the responsibility of the caller to eventually free the buffer
2353 ** using sqlite3_free().
2355 int sqlite3session_changeset(
2356 sqlite3_session *pSession, /* Session object */
2357 int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
2358 void **ppChangeset /* OUT: Buffer containing changeset */
2360 return sessionGenerateChangeset(pSession, 0, 0, 0, pnChangeset, ppChangeset);
2364 ** Streaming version of sqlite3session_changeset().
2366 int sqlite3session_changeset_strm(
2367 sqlite3_session *pSession,
2368 int (*xOutput)(void *pOut, const void *pData, int nData),
2369 void *pOut
2371 return sessionGenerateChangeset(pSession, 0, xOutput, pOut, 0, 0);
2375 ** Streaming version of sqlite3session_patchset().
2377 int sqlite3session_patchset_strm(
2378 sqlite3_session *pSession,
2379 int (*xOutput)(void *pOut, const void *pData, int nData),
2380 void *pOut
2382 return sessionGenerateChangeset(pSession, 1, xOutput, pOut, 0, 0);
2386 ** Obtain a patchset object containing all changes recorded by the
2387 ** session object passed as the first argument.
2389 ** It is the responsibility of the caller to eventually free the buffer
2390 ** using sqlite3_free().
2392 int sqlite3session_patchset(
2393 sqlite3_session *pSession, /* Session object */
2394 int *pnPatchset, /* OUT: Size of buffer at *ppChangeset */
2395 void **ppPatchset /* OUT: Buffer containing changeset */
2397 return sessionGenerateChangeset(pSession, 1, 0, 0, pnPatchset, ppPatchset);
2401 ** Enable or disable the session object passed as the first argument.
2403 int sqlite3session_enable(sqlite3_session *pSession, int bEnable){
2404 int ret;
2405 sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
2406 if( bEnable>=0 ){
2407 pSession->bEnable = bEnable;
2409 ret = pSession->bEnable;
2410 sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
2411 return ret;
2415 ** Enable or disable the session object passed as the first argument.
2417 int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect){
2418 int ret;
2419 sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
2420 if( bIndirect>=0 ){
2421 pSession->bIndirect = bIndirect;
2423 ret = pSession->bIndirect;
2424 sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
2425 return ret;
2429 ** Return true if there have been no changes to monitored tables recorded
2430 ** by the session object passed as the only argument.
2432 int sqlite3session_isempty(sqlite3_session *pSession){
2433 int ret = 0;
2434 SessionTable *pTab;
2436 sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
2437 for(pTab=pSession->pTable; pTab && ret==0; pTab=pTab->pNext){
2438 ret = (pTab->nEntry>0);
2440 sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
2442 return (ret==0);
2446 ** Do the work for either sqlite3changeset_start() or start_strm().
2448 static int sessionChangesetStart(
2449 sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
2450 int (*xInput)(void *pIn, void *pData, int *pnData),
2451 void *pIn,
2452 int nChangeset, /* Size of buffer pChangeset in bytes */
2453 void *pChangeset /* Pointer to buffer containing changeset */
2455 sqlite3_changeset_iter *pRet; /* Iterator to return */
2456 int nByte; /* Number of bytes to allocate for iterator */
2458 assert( xInput==0 || (pChangeset==0 && nChangeset==0) );
2460 /* Zero the output variable in case an error occurs. */
2461 *pp = 0;
2463 /* Allocate and initialize the iterator structure. */
2464 nByte = sizeof(sqlite3_changeset_iter);
2465 pRet = (sqlite3_changeset_iter *)sqlite3_malloc(nByte);
2466 if( !pRet ) return SQLITE_NOMEM;
2467 memset(pRet, 0, sizeof(sqlite3_changeset_iter));
2468 pRet->in.aData = (u8 *)pChangeset;
2469 pRet->in.nData = nChangeset;
2470 pRet->in.xInput = xInput;
2471 pRet->in.pIn = pIn;
2472 pRet->in.bEof = (xInput ? 0 : 1);
2474 /* Populate the output variable and return success. */
2475 *pp = pRet;
2476 return SQLITE_OK;
2480 ** Create an iterator used to iterate through the contents of a changeset.
2482 int sqlite3changeset_start(
2483 sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
2484 int nChangeset, /* Size of buffer pChangeset in bytes */
2485 void *pChangeset /* Pointer to buffer containing changeset */
2487 return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset);
2491 ** Streaming version of sqlite3changeset_start().
2493 int sqlite3changeset_start_strm(
2494 sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
2495 int (*xInput)(void *pIn, void *pData, int *pnData),
2496 void *pIn
2498 return sessionChangesetStart(pp, xInput, pIn, 0, 0);
2502 ** If the SessionInput object passed as the only argument is a streaming
2503 ** object and the buffer is full, discard some data to free up space.
2505 static void sessionDiscardData(SessionInput *pIn){
2506 if( pIn->bEof && pIn->xInput && pIn->iNext>=SESSIONS_STRM_CHUNK_SIZE ){
2507 int nMove = pIn->buf.nBuf - pIn->iNext;
2508 assert( nMove>=0 );
2509 if( nMove>0 ){
2510 memmove(pIn->buf.aBuf, &pIn->buf.aBuf[pIn->iNext], nMove);
2512 pIn->buf.nBuf -= pIn->iNext;
2513 pIn->iNext = 0;
2514 pIn->nData = pIn->buf.nBuf;
2519 ** Ensure that there are at least nByte bytes available in the buffer. Or,
2520 ** if there are not nByte bytes remaining in the input, that all available
2521 ** data is in the buffer.
2523 ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
2525 static int sessionInputBuffer(SessionInput *pIn, int nByte){
2526 int rc = SQLITE_OK;
2527 if( pIn->xInput ){
2528 while( !pIn->bEof && (pIn->iNext+nByte)>=pIn->nData && rc==SQLITE_OK ){
2529 int nNew = SESSIONS_STRM_CHUNK_SIZE;
2531 if( pIn->bNoDiscard==0 ) sessionDiscardData(pIn);
2532 if( SQLITE_OK==sessionBufferGrow(&pIn->buf, nNew, &rc) ){
2533 rc = pIn->xInput(pIn->pIn, &pIn->buf.aBuf[pIn->buf.nBuf], &nNew);
2534 if( nNew==0 ){
2535 pIn->bEof = 1;
2536 }else{
2537 pIn->buf.nBuf += nNew;
2541 pIn->aData = pIn->buf.aBuf;
2542 pIn->nData = pIn->buf.nBuf;
2545 return rc;
2549 ** When this function is called, *ppRec points to the start of a record
2550 ** that contains nCol values. This function advances the pointer *ppRec
2551 ** until it points to the byte immediately following that record.
2553 static void sessionSkipRecord(
2554 u8 **ppRec, /* IN/OUT: Record pointer */
2555 int nCol /* Number of values in record */
2557 u8 *aRec = *ppRec;
2558 int i;
2559 for(i=0; i<nCol; i++){
2560 int eType = *aRec++;
2561 if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
2562 int nByte;
2563 aRec += sessionVarintGet((u8*)aRec, &nByte);
2564 aRec += nByte;
2565 }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
2566 aRec += 8;
2570 *ppRec = aRec;
2574 ** This function sets the value of the sqlite3_value object passed as the
2575 ** first argument to a copy of the string or blob held in the aData[]
2576 ** buffer. SQLITE_OK is returned if successful, or SQLITE_NOMEM if an OOM
2577 ** error occurs.
2579 static int sessionValueSetStr(
2580 sqlite3_value *pVal, /* Set the value of this object */
2581 u8 *aData, /* Buffer containing string or blob data */
2582 int nData, /* Size of buffer aData[] in bytes */
2583 u8 enc /* String encoding (0 for blobs) */
2585 /* In theory this code could just pass SQLITE_TRANSIENT as the final
2586 ** argument to sqlite3ValueSetStr() and have the copy created
2587 ** automatically. But doing so makes it difficult to detect any OOM
2588 ** error. Hence the code to create the copy externally. */
2589 u8 *aCopy = sqlite3_malloc(nData+1);
2590 if( aCopy==0 ) return SQLITE_NOMEM;
2591 memcpy(aCopy, aData, nData);
2592 sqlite3ValueSetStr(pVal, nData, (char*)aCopy, enc, sqlite3_free);
2593 return SQLITE_OK;
2597 ** Deserialize a single record from a buffer in memory. See "RECORD FORMAT"
2598 ** for details.
2600 ** When this function is called, *paChange points to the start of the record
2601 ** to deserialize. Assuming no error occurs, *paChange is set to point to
2602 ** one byte after the end of the same record before this function returns.
2603 ** If the argument abPK is NULL, then the record contains nCol values. Or,
2604 ** if abPK is other than NULL, then the record contains only the PK fields
2605 ** (in other words, it is a patchset DELETE record).
2607 ** If successful, each element of the apOut[] array (allocated by the caller)
2608 ** is set to point to an sqlite3_value object containing the value read
2609 ** from the corresponding position in the record. If that value is not
2610 ** included in the record (i.e. because the record is part of an UPDATE change
2611 ** and the field was not modified), the corresponding element of apOut[] is
2612 ** set to NULL.
2614 ** It is the responsibility of the caller to free all sqlite_value structures
2615 ** using sqlite3_free().
2617 ** If an error occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
2618 ** The apOut[] array may have been partially populated in this case.
2620 static int sessionReadRecord(
2621 SessionInput *pIn, /* Input data */
2622 int nCol, /* Number of values in record */
2623 u8 *abPK, /* Array of primary key flags, or NULL */
2624 sqlite3_value **apOut /* Write values to this array */
2626 int i; /* Used to iterate through columns */
2627 int rc = SQLITE_OK;
2629 for(i=0; i<nCol && rc==SQLITE_OK; i++){
2630 int eType = 0; /* Type of value (SQLITE_NULL, TEXT etc.) */
2631 if( abPK && abPK[i]==0 ) continue;
2632 rc = sessionInputBuffer(pIn, 9);
2633 if( rc==SQLITE_OK ){
2634 eType = pIn->aData[pIn->iNext++];
2637 assert( apOut[i]==0 );
2638 if( eType ){
2639 apOut[i] = sqlite3ValueNew(0);
2640 if( !apOut[i] ) rc = SQLITE_NOMEM;
2643 if( rc==SQLITE_OK ){
2644 u8 *aVal = &pIn->aData[pIn->iNext];
2645 if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
2646 int nByte;
2647 pIn->iNext += sessionVarintGet(aVal, &nByte);
2648 rc = sessionInputBuffer(pIn, nByte);
2649 if( rc==SQLITE_OK ){
2650 u8 enc = (eType==SQLITE_TEXT ? SQLITE_UTF8 : 0);
2651 rc = sessionValueSetStr(apOut[i],&pIn->aData[pIn->iNext],nByte,enc);
2653 pIn->iNext += nByte;
2655 if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
2656 sqlite3_int64 v = sessionGetI64(aVal);
2657 if( eType==SQLITE_INTEGER ){
2658 sqlite3VdbeMemSetInt64(apOut[i], v);
2659 }else{
2660 double d;
2661 memcpy(&d, &v, 8);
2662 sqlite3VdbeMemSetDouble(apOut[i], d);
2664 pIn->iNext += 8;
2669 return rc;
2673 ** The input pointer currently points to the second byte of a table-header.
2674 ** Specifically, to the following:
2676 ** + number of columns in table (varint)
2677 ** + array of PK flags (1 byte per column),
2678 ** + table name (nul terminated).
2680 ** This function ensures that all of the above is present in the input
2681 ** buffer (i.e. that it can be accessed without any calls to xInput()).
2682 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
2683 ** The input pointer is not moved.
2685 static int sessionChangesetBufferTblhdr(SessionInput *pIn, int *pnByte){
2686 int rc = SQLITE_OK;
2687 int nCol = 0;
2688 int nRead = 0;
2690 rc = sessionInputBuffer(pIn, 9);
2691 if( rc==SQLITE_OK ){
2692 nRead += sessionVarintGet(&pIn->aData[pIn->iNext + nRead], &nCol);
2693 rc = sessionInputBuffer(pIn, nRead+nCol+100);
2694 nRead += nCol;
2697 while( rc==SQLITE_OK ){
2698 while( (pIn->iNext + nRead)<pIn->nData && pIn->aData[pIn->iNext + nRead] ){
2699 nRead++;
2701 if( (pIn->iNext + nRead)<pIn->nData ) break;
2702 rc = sessionInputBuffer(pIn, nRead + 100);
2704 *pnByte = nRead+1;
2705 return rc;
2709 ** The input pointer currently points to the first byte of the first field
2710 ** of a record consisting of nCol columns. This function ensures the entire
2711 ** record is buffered. It does not move the input pointer.
2713 ** If successful, SQLITE_OK is returned and *pnByte is set to the size of
2714 ** the record in bytes. Otherwise, an SQLite error code is returned. The
2715 ** final value of *pnByte is undefined in this case.
2717 static int sessionChangesetBufferRecord(
2718 SessionInput *pIn, /* Input data */
2719 int nCol, /* Number of columns in record */
2720 int *pnByte /* OUT: Size of record in bytes */
2722 int rc = SQLITE_OK;
2723 int nByte = 0;
2724 int i;
2725 for(i=0; rc==SQLITE_OK && i<nCol; i++){
2726 int eType;
2727 rc = sessionInputBuffer(pIn, nByte + 10);
2728 if( rc==SQLITE_OK ){
2729 eType = pIn->aData[pIn->iNext + nByte++];
2730 if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
2731 int n;
2732 nByte += sessionVarintGet(&pIn->aData[pIn->iNext+nByte], &n);
2733 nByte += n;
2734 rc = sessionInputBuffer(pIn, nByte);
2735 }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
2736 nByte += 8;
2740 *pnByte = nByte;
2741 return rc;
2745 ** The input pointer currently points to the second byte of a table-header.
2746 ** Specifically, to the following:
2748 ** + number of columns in table (varint)
2749 ** + array of PK flags (1 byte per column),
2750 ** + table name (nul terminated).
2752 ** This function decodes the table-header and populates the p->nCol,
2753 ** p->zTab and p->abPK[] variables accordingly. The p->apValue[] array is
2754 ** also allocated or resized according to the new value of p->nCol. The
2755 ** input pointer is left pointing to the byte following the table header.
2757 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code
2758 ** is returned and the final values of the various fields enumerated above
2759 ** are undefined.
2761 static int sessionChangesetReadTblhdr(sqlite3_changeset_iter *p){
2762 int rc;
2763 int nCopy;
2764 assert( p->rc==SQLITE_OK );
2766 rc = sessionChangesetBufferTblhdr(&p->in, &nCopy);
2767 if( rc==SQLITE_OK ){
2768 int nByte;
2769 int nVarint;
2770 nVarint = sessionVarintGet(&p->in.aData[p->in.iNext], &p->nCol);
2771 nCopy -= nVarint;
2772 p->in.iNext += nVarint;
2773 nByte = p->nCol * sizeof(sqlite3_value*) * 2 + nCopy;
2774 p->tblhdr.nBuf = 0;
2775 sessionBufferGrow(&p->tblhdr, nByte, &rc);
2778 if( rc==SQLITE_OK ){
2779 int iPK = sizeof(sqlite3_value*)*p->nCol*2;
2780 memset(p->tblhdr.aBuf, 0, iPK);
2781 memcpy(&p->tblhdr.aBuf[iPK], &p->in.aData[p->in.iNext], nCopy);
2782 p->in.iNext += nCopy;
2785 p->apValue = (sqlite3_value**)p->tblhdr.aBuf;
2786 p->abPK = (u8*)&p->apValue[p->nCol*2];
2787 p->zTab = (char*)&p->abPK[p->nCol];
2788 return (p->rc = rc);
2792 ** Advance the changeset iterator to the next change.
2794 ** If both paRec and pnRec are NULL, then this function works like the public
2795 ** API sqlite3changeset_next(). If SQLITE_ROW is returned, then the
2796 ** sqlite3changeset_new() and old() APIs may be used to query for values.
2798 ** Otherwise, if paRec and pnRec are not NULL, then a pointer to the change
2799 ** record is written to *paRec before returning and the number of bytes in
2800 ** the record to *pnRec.
2802 ** Either way, this function returns SQLITE_ROW if the iterator is
2803 ** successfully advanced to the next change in the changeset, an SQLite
2804 ** error code if an error occurs, or SQLITE_DONE if there are no further
2805 ** changes in the changeset.
2807 static int sessionChangesetNext(
2808 sqlite3_changeset_iter *p, /* Changeset iterator */
2809 u8 **paRec, /* If non-NULL, store record pointer here */
2810 int *pnRec /* If non-NULL, store size of record here */
2812 int i;
2813 u8 op;
2815 assert( (paRec==0 && pnRec==0) || (paRec && pnRec) );
2817 /* If the iterator is in the error-state, return immediately. */
2818 if( p->rc!=SQLITE_OK ) return p->rc;
2820 /* Free the current contents of p->apValue[], if any. */
2821 if( p->apValue ){
2822 for(i=0; i<p->nCol*2; i++){
2823 sqlite3ValueFree(p->apValue[i]);
2825 memset(p->apValue, 0, sizeof(sqlite3_value*)*p->nCol*2);
2828 /* Make sure the buffer contains at least 10 bytes of input data, or all
2829 ** remaining data if there are less than 10 bytes available. This is
2830 ** sufficient either for the 'T' or 'P' byte and the varint that follows
2831 ** it, or for the two single byte values otherwise. */
2832 p->rc = sessionInputBuffer(&p->in, 2);
2833 if( p->rc!=SQLITE_OK ) return p->rc;
2835 /* If the iterator is already at the end of the changeset, return DONE. */
2836 if( p->in.iNext>=p->in.nData ){
2837 return SQLITE_DONE;
2840 sessionDiscardData(&p->in);
2841 p->in.iCurrent = p->in.iNext;
2843 op = p->in.aData[p->in.iNext++];
2844 while( op=='T' || op=='P' ){
2845 p->bPatchset = (op=='P');
2846 if( sessionChangesetReadTblhdr(p) ) return p->rc;
2847 if( (p->rc = sessionInputBuffer(&p->in, 2)) ) return p->rc;
2848 p->in.iCurrent = p->in.iNext;
2849 if( p->in.iNext>=p->in.nData ) return SQLITE_DONE;
2850 op = p->in.aData[p->in.iNext++];
2853 p->op = op;
2854 p->bIndirect = p->in.aData[p->in.iNext++];
2855 if( p->op!=SQLITE_UPDATE && p->op!=SQLITE_DELETE && p->op!=SQLITE_INSERT ){
2856 return (p->rc = SQLITE_CORRUPT_BKPT);
2859 if( paRec ){
2860 int nVal; /* Number of values to buffer */
2861 if( p->bPatchset==0 && op==SQLITE_UPDATE ){
2862 nVal = p->nCol * 2;
2863 }else if( p->bPatchset && op==SQLITE_DELETE ){
2864 nVal = 0;
2865 for(i=0; i<p->nCol; i++) if( p->abPK[i] ) nVal++;
2866 }else{
2867 nVal = p->nCol;
2869 p->rc = sessionChangesetBufferRecord(&p->in, nVal, pnRec);
2870 if( p->rc!=SQLITE_OK ) return p->rc;
2871 *paRec = &p->in.aData[p->in.iNext];
2872 p->in.iNext += *pnRec;
2873 }else{
2875 /* If this is an UPDATE or DELETE, read the old.* record. */
2876 if( p->op!=SQLITE_INSERT && (p->bPatchset==0 || p->op==SQLITE_DELETE) ){
2877 u8 *abPK = p->bPatchset ? p->abPK : 0;
2878 p->rc = sessionReadRecord(&p->in, p->nCol, abPK, p->apValue);
2879 if( p->rc!=SQLITE_OK ) return p->rc;
2882 /* If this is an INSERT or UPDATE, read the new.* record. */
2883 if( p->op!=SQLITE_DELETE ){
2884 p->rc = sessionReadRecord(&p->in, p->nCol, 0, &p->apValue[p->nCol]);
2885 if( p->rc!=SQLITE_OK ) return p->rc;
2888 if( p->bPatchset && p->op==SQLITE_UPDATE ){
2889 /* If this is an UPDATE that is part of a patchset, then all PK and
2890 ** modified fields are present in the new.* record. The old.* record
2891 ** is currently completely empty. This block shifts the PK fields from
2892 ** new.* to old.*, to accommodate the code that reads these arrays. */
2893 for(i=0; i<p->nCol; i++){
2894 assert( p->apValue[i]==0 );
2895 assert( p->abPK[i]==0 || p->apValue[i+p->nCol] );
2896 if( p->abPK[i] ){
2897 p->apValue[i] = p->apValue[i+p->nCol];
2898 p->apValue[i+p->nCol] = 0;
2904 return SQLITE_ROW;
2908 ** Advance an iterator created by sqlite3changeset_start() to the next
2909 ** change in the changeset. This function may return SQLITE_ROW, SQLITE_DONE
2910 ** or SQLITE_CORRUPT.
2912 ** This function may not be called on iterators passed to a conflict handler
2913 ** callback by changeset_apply().
2915 int sqlite3changeset_next(sqlite3_changeset_iter *p){
2916 return sessionChangesetNext(p, 0, 0);
2920 ** The following function extracts information on the current change
2921 ** from a changeset iterator. It may only be called after changeset_next()
2922 ** has returned SQLITE_ROW.
2924 int sqlite3changeset_op(
2925 sqlite3_changeset_iter *pIter, /* Iterator handle */
2926 const char **pzTab, /* OUT: Pointer to table name */
2927 int *pnCol, /* OUT: Number of columns in table */
2928 int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */
2929 int *pbIndirect /* OUT: True if change is indirect */
2931 *pOp = pIter->op;
2932 *pnCol = pIter->nCol;
2933 *pzTab = pIter->zTab;
2934 if( pbIndirect ) *pbIndirect = pIter->bIndirect;
2935 return SQLITE_OK;
2939 ** Return information regarding the PRIMARY KEY and number of columns in
2940 ** the database table affected by the change that pIter currently points
2941 ** to. This function may only be called after changeset_next() returns
2942 ** SQLITE_ROW.
2944 int sqlite3changeset_pk(
2945 sqlite3_changeset_iter *pIter, /* Iterator object */
2946 unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */
2947 int *pnCol /* OUT: Number of entries in output array */
2949 *pabPK = pIter->abPK;
2950 if( pnCol ) *pnCol = pIter->nCol;
2951 return SQLITE_OK;
2955 ** This function may only be called while the iterator is pointing to an
2956 ** SQLITE_UPDATE or SQLITE_DELETE change (see sqlite3changeset_op()).
2957 ** Otherwise, SQLITE_MISUSE is returned.
2959 ** It sets *ppValue to point to an sqlite3_value structure containing the
2960 ** iVal'th value in the old.* record. Or, if that particular value is not
2961 ** included in the record (because the change is an UPDATE and the field
2962 ** was not modified and is not a PK column), set *ppValue to NULL.
2964 ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
2965 ** not modified. Otherwise, SQLITE_OK.
2967 int sqlite3changeset_old(
2968 sqlite3_changeset_iter *pIter, /* Changeset iterator */
2969 int iVal, /* Index of old.* value to retrieve */
2970 sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */
2972 if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_DELETE ){
2973 return SQLITE_MISUSE;
2975 if( iVal<0 || iVal>=pIter->nCol ){
2976 return SQLITE_RANGE;
2978 *ppValue = pIter->apValue[iVal];
2979 return SQLITE_OK;
2983 ** This function may only be called while the iterator is pointing to an
2984 ** SQLITE_UPDATE or SQLITE_INSERT change (see sqlite3changeset_op()).
2985 ** Otherwise, SQLITE_MISUSE is returned.
2987 ** It sets *ppValue to point to an sqlite3_value structure containing the
2988 ** iVal'th value in the new.* record. Or, if that particular value is not
2989 ** included in the record (because the change is an UPDATE and the field
2990 ** was not modified), set *ppValue to NULL.
2992 ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
2993 ** not modified. Otherwise, SQLITE_OK.
2995 int sqlite3changeset_new(
2996 sqlite3_changeset_iter *pIter, /* Changeset iterator */
2997 int iVal, /* Index of new.* value to retrieve */
2998 sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */
3000 if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_INSERT ){
3001 return SQLITE_MISUSE;
3003 if( iVal<0 || iVal>=pIter->nCol ){
3004 return SQLITE_RANGE;
3006 *ppValue = pIter->apValue[pIter->nCol+iVal];
3007 return SQLITE_OK;
3011 ** The following two macros are used internally. They are similar to the
3012 ** sqlite3changeset_new() and sqlite3changeset_old() functions, except that
3013 ** they omit all error checking and return a pointer to the requested value.
3015 #define sessionChangesetNew(pIter, iVal) (pIter)->apValue[(pIter)->nCol+(iVal)]
3016 #define sessionChangesetOld(pIter, iVal) (pIter)->apValue[(iVal)]
3019 ** This function may only be called with a changeset iterator that has been
3020 ** passed to an SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT
3021 ** conflict-handler function. Otherwise, SQLITE_MISUSE is returned.
3023 ** If successful, *ppValue is set to point to an sqlite3_value structure
3024 ** containing the iVal'th value of the conflicting record.
3026 ** If value iVal is out-of-range or some other error occurs, an SQLite error
3027 ** code is returned. Otherwise, SQLITE_OK.
3029 int sqlite3changeset_conflict(
3030 sqlite3_changeset_iter *pIter, /* Changeset iterator */
3031 int iVal, /* Index of conflict record value to fetch */
3032 sqlite3_value **ppValue /* OUT: Value from conflicting row */
3034 if( !pIter->pConflict ){
3035 return SQLITE_MISUSE;
3037 if( iVal<0 || iVal>=pIter->nCol ){
3038 return SQLITE_RANGE;
3040 *ppValue = sqlite3_column_value(pIter->pConflict, iVal);
3041 return SQLITE_OK;
3045 ** This function may only be called with an iterator passed to an
3046 ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
3047 ** it sets the output variable to the total number of known foreign key
3048 ** violations in the destination database and returns SQLITE_OK.
3050 ** In all other cases this function returns SQLITE_MISUSE.
3052 int sqlite3changeset_fk_conflicts(
3053 sqlite3_changeset_iter *pIter, /* Changeset iterator */
3054 int *pnOut /* OUT: Number of FK violations */
3056 if( pIter->pConflict || pIter->apValue ){
3057 return SQLITE_MISUSE;
3059 *pnOut = pIter->nCol;
3060 return SQLITE_OK;
3065 ** Finalize an iterator allocated with sqlite3changeset_start().
3067 ** This function may not be called on iterators passed to a conflict handler
3068 ** callback by changeset_apply().
3070 int sqlite3changeset_finalize(sqlite3_changeset_iter *p){
3071 int rc = SQLITE_OK;
3072 if( p ){
3073 int i; /* Used to iterate through p->apValue[] */
3074 rc = p->rc;
3075 if( p->apValue ){
3076 for(i=0; i<p->nCol*2; i++) sqlite3ValueFree(p->apValue[i]);
3078 sqlite3_free(p->tblhdr.aBuf);
3079 sqlite3_free(p->in.buf.aBuf);
3080 sqlite3_free(p);
3082 return rc;
3085 static int sessionChangesetInvert(
3086 SessionInput *pInput, /* Input changeset */
3087 int (*xOutput)(void *pOut, const void *pData, int nData),
3088 void *pOut,
3089 int *pnInverted, /* OUT: Number of bytes in output changeset */
3090 void **ppInverted /* OUT: Inverse of pChangeset */
3092 int rc = SQLITE_OK; /* Return value */
3093 SessionBuffer sOut; /* Output buffer */
3094 int nCol = 0; /* Number of cols in current table */
3095 u8 *abPK = 0; /* PK array for current table */
3096 sqlite3_value **apVal = 0; /* Space for values for UPDATE inversion */
3097 SessionBuffer sPK = {0, 0, 0}; /* PK array for current table */
3099 /* Initialize the output buffer */
3100 memset(&sOut, 0, sizeof(SessionBuffer));
3102 /* Zero the output variables in case an error occurs. */
3103 if( ppInverted ){
3104 *ppInverted = 0;
3105 *pnInverted = 0;
3108 while( 1 ){
3109 u8 eType;
3111 /* Test for EOF. */
3112 if( (rc = sessionInputBuffer(pInput, 2)) ) goto finished_invert;
3113 if( pInput->iNext>=pInput->nData ) break;
3114 eType = pInput->aData[pInput->iNext];
3116 switch( eType ){
3117 case 'T': {
3118 /* A 'table' record consists of:
3120 ** * A constant 'T' character,
3121 ** * Number of columns in said table (a varint),
3122 ** * An array of nCol bytes (sPK),
3123 ** * A nul-terminated table name.
3125 int nByte;
3126 int nVar;
3127 pInput->iNext++;
3128 if( (rc = sessionChangesetBufferTblhdr(pInput, &nByte)) ){
3129 goto finished_invert;
3131 nVar = sessionVarintGet(&pInput->aData[pInput->iNext], &nCol);
3132 sPK.nBuf = 0;
3133 sessionAppendBlob(&sPK, &pInput->aData[pInput->iNext+nVar], nCol, &rc);
3134 sessionAppendByte(&sOut, eType, &rc);
3135 sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
3136 if( rc ) goto finished_invert;
3138 pInput->iNext += nByte;
3139 sqlite3_free(apVal);
3140 apVal = 0;
3141 abPK = sPK.aBuf;
3142 break;
3145 case SQLITE_INSERT:
3146 case SQLITE_DELETE: {
3147 int nByte;
3148 int bIndirect = pInput->aData[pInput->iNext+1];
3149 int eType2 = (eType==SQLITE_DELETE ? SQLITE_INSERT : SQLITE_DELETE);
3150 pInput->iNext += 2;
3151 assert( rc==SQLITE_OK );
3152 rc = sessionChangesetBufferRecord(pInput, nCol, &nByte);
3153 sessionAppendByte(&sOut, eType2, &rc);
3154 sessionAppendByte(&sOut, bIndirect, &rc);
3155 sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
3156 pInput->iNext += nByte;
3157 if( rc ) goto finished_invert;
3158 break;
3161 case SQLITE_UPDATE: {
3162 int iCol;
3164 if( 0==apVal ){
3165 apVal = (sqlite3_value **)sqlite3_malloc(sizeof(apVal[0])*nCol*2);
3166 if( 0==apVal ){
3167 rc = SQLITE_NOMEM;
3168 goto finished_invert;
3170 memset(apVal, 0, sizeof(apVal[0])*nCol*2);
3173 /* Write the header for the new UPDATE change. Same as the original. */
3174 sessionAppendByte(&sOut, eType, &rc);
3175 sessionAppendByte(&sOut, pInput->aData[pInput->iNext+1], &rc);
3177 /* Read the old.* and new.* records for the update change. */
3178 pInput->iNext += 2;
3179 rc = sessionReadRecord(pInput, nCol, 0, &apVal[0]);
3180 if( rc==SQLITE_OK ){
3181 rc = sessionReadRecord(pInput, nCol, 0, &apVal[nCol]);
3184 /* Write the new old.* record. Consists of the PK columns from the
3185 ** original old.* record, and the other values from the original
3186 ** new.* record. */
3187 for(iCol=0; iCol<nCol; iCol++){
3188 sqlite3_value *pVal = apVal[iCol + (abPK[iCol] ? 0 : nCol)];
3189 sessionAppendValue(&sOut, pVal, &rc);
3192 /* Write the new new.* record. Consists of a copy of all values
3193 ** from the original old.* record, except for the PK columns, which
3194 ** are set to "undefined". */
3195 for(iCol=0; iCol<nCol; iCol++){
3196 sqlite3_value *pVal = (abPK[iCol] ? 0 : apVal[iCol]);
3197 sessionAppendValue(&sOut, pVal, &rc);
3200 for(iCol=0; iCol<nCol*2; iCol++){
3201 sqlite3ValueFree(apVal[iCol]);
3203 memset(apVal, 0, sizeof(apVal[0])*nCol*2);
3204 if( rc!=SQLITE_OK ){
3205 goto finished_invert;
3208 break;
3211 default:
3212 rc = SQLITE_CORRUPT_BKPT;
3213 goto finished_invert;
3216 assert( rc==SQLITE_OK );
3217 if( xOutput && sOut.nBuf>=SESSIONS_STRM_CHUNK_SIZE ){
3218 rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
3219 sOut.nBuf = 0;
3220 if( rc!=SQLITE_OK ) goto finished_invert;
3224 assert( rc==SQLITE_OK );
3225 if( pnInverted ){
3226 *pnInverted = sOut.nBuf;
3227 *ppInverted = sOut.aBuf;
3228 sOut.aBuf = 0;
3229 }else if( sOut.nBuf>0 ){
3230 rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
3233 finished_invert:
3234 sqlite3_free(sOut.aBuf);
3235 sqlite3_free(apVal);
3236 sqlite3_free(sPK.aBuf);
3237 return rc;
3242 ** Invert a changeset object.
3244 int sqlite3changeset_invert(
3245 int nChangeset, /* Number of bytes in input */
3246 const void *pChangeset, /* Input changeset */
3247 int *pnInverted, /* OUT: Number of bytes in output changeset */
3248 void **ppInverted /* OUT: Inverse of pChangeset */
3250 SessionInput sInput;
3252 /* Set up the input stream */
3253 memset(&sInput, 0, sizeof(SessionInput));
3254 sInput.nData = nChangeset;
3255 sInput.aData = (u8*)pChangeset;
3257 return sessionChangesetInvert(&sInput, 0, 0, pnInverted, ppInverted);
3261 ** Streaming version of sqlite3changeset_invert().
3263 int sqlite3changeset_invert_strm(
3264 int (*xInput)(void *pIn, void *pData, int *pnData),
3265 void *pIn,
3266 int (*xOutput)(void *pOut, const void *pData, int nData),
3267 void *pOut
3269 SessionInput sInput;
3270 int rc;
3272 /* Set up the input stream */
3273 memset(&sInput, 0, sizeof(SessionInput));
3274 sInput.xInput = xInput;
3275 sInput.pIn = pIn;
3277 rc = sessionChangesetInvert(&sInput, xOutput, pOut, 0, 0);
3278 sqlite3_free(sInput.buf.aBuf);
3279 return rc;
3282 typedef struct SessionApplyCtx SessionApplyCtx;
3283 struct SessionApplyCtx {
3284 sqlite3 *db;
3285 sqlite3_stmt *pDelete; /* DELETE statement */
3286 sqlite3_stmt *pUpdate; /* UPDATE statement */
3287 sqlite3_stmt *pInsert; /* INSERT statement */
3288 sqlite3_stmt *pSelect; /* SELECT statement */
3289 int nCol; /* Size of azCol[] and abPK[] arrays */
3290 const char **azCol; /* Array of column names */
3291 u8 *abPK; /* Boolean array - true if column is in PK */
3293 int bDeferConstraints; /* True to defer constraints */
3294 SessionBuffer constraints; /* Deferred constraints are stored here */
3298 ** Formulate a statement to DELETE a row from database db. Assuming a table
3299 ** structure like this:
3301 ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
3303 ** The DELETE statement looks like this:
3305 ** DELETE FROM x WHERE a = :1 AND c = :3 AND (:5 OR b IS :2 AND d IS :4)
3307 ** Variable :5 (nCol+1) is a boolean. It should be set to 0 if we require
3308 ** matching b and d values, or 1 otherwise. The second case comes up if the
3309 ** conflict handler is invoked with NOTFOUND and returns CHANGESET_REPLACE.
3311 ** If successful, SQLITE_OK is returned and SessionApplyCtx.pDelete is left
3312 ** pointing to the prepared version of the SQL statement.
3314 static int sessionDeleteRow(
3315 sqlite3 *db, /* Database handle */
3316 const char *zTab, /* Table name */
3317 SessionApplyCtx *p /* Session changeset-apply context */
3319 int i;
3320 const char *zSep = "";
3321 int rc = SQLITE_OK;
3322 SessionBuffer buf = {0, 0, 0};
3323 int nPk = 0;
3325 sessionAppendStr(&buf, "DELETE FROM ", &rc);
3326 sessionAppendIdent(&buf, zTab, &rc);
3327 sessionAppendStr(&buf, " WHERE ", &rc);
3329 for(i=0; i<p->nCol; i++){
3330 if( p->abPK[i] ){
3331 nPk++;
3332 sessionAppendStr(&buf, zSep, &rc);
3333 sessionAppendIdent(&buf, p->azCol[i], &rc);
3334 sessionAppendStr(&buf, " = ?", &rc);
3335 sessionAppendInteger(&buf, i+1, &rc);
3336 zSep = " AND ";
3340 if( nPk<p->nCol ){
3341 sessionAppendStr(&buf, " AND (?", &rc);
3342 sessionAppendInteger(&buf, p->nCol+1, &rc);
3343 sessionAppendStr(&buf, " OR ", &rc);
3345 zSep = "";
3346 for(i=0; i<p->nCol; i++){
3347 if( !p->abPK[i] ){
3348 sessionAppendStr(&buf, zSep, &rc);
3349 sessionAppendIdent(&buf, p->azCol[i], &rc);
3350 sessionAppendStr(&buf, " IS ?", &rc);
3351 sessionAppendInteger(&buf, i+1, &rc);
3352 zSep = "AND ";
3355 sessionAppendStr(&buf, ")", &rc);
3358 if( rc==SQLITE_OK ){
3359 rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pDelete, 0);
3361 sqlite3_free(buf.aBuf);
3363 return rc;
3367 ** Formulate and prepare a statement to UPDATE a row from database db.
3368 ** Assuming a table structure like this:
3370 ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
3372 ** The UPDATE statement looks like this:
3374 ** UPDATE x SET
3375 ** a = CASE WHEN ?2 THEN ?3 ELSE a END,
3376 ** b = CASE WHEN ?5 THEN ?6 ELSE b END,
3377 ** c = CASE WHEN ?8 THEN ?9 ELSE c END,
3378 ** d = CASE WHEN ?11 THEN ?12 ELSE d END
3379 ** WHERE a = ?1 AND c = ?7 AND (?13 OR
3380 ** (?5==0 OR b IS ?4) AND (?11==0 OR d IS ?10) AND
3381 ** )
3383 ** For each column in the table, there are three variables to bind:
3385 ** ?(i*3+1) The old.* value of the column, if any.
3386 ** ?(i*3+2) A boolean flag indicating that the value is being modified.
3387 ** ?(i*3+3) The new.* value of the column, if any.
3389 ** Also, a boolean flag that, if set to true, causes the statement to update
3390 ** a row even if the non-PK values do not match. This is required if the
3391 ** conflict-handler is invoked with CHANGESET_DATA and returns
3392 ** CHANGESET_REPLACE. This is variable "?(nCol*3+1)".
3394 ** If successful, SQLITE_OK is returned and SessionApplyCtx.pUpdate is left
3395 ** pointing to the prepared version of the SQL statement.
3397 static int sessionUpdateRow(
3398 sqlite3 *db, /* Database handle */
3399 const char *zTab, /* Table name */
3400 SessionApplyCtx *p /* Session changeset-apply context */
3402 int rc = SQLITE_OK;
3403 int i;
3404 const char *zSep = "";
3405 SessionBuffer buf = {0, 0, 0};
3407 /* Append "UPDATE tbl SET " */
3408 sessionAppendStr(&buf, "UPDATE ", &rc);
3409 sessionAppendIdent(&buf, zTab, &rc);
3410 sessionAppendStr(&buf, " SET ", &rc);
3412 /* Append the assignments */
3413 for(i=0; i<p->nCol; i++){
3414 sessionAppendStr(&buf, zSep, &rc);
3415 sessionAppendIdent(&buf, p->azCol[i], &rc);
3416 sessionAppendStr(&buf, " = CASE WHEN ?", &rc);
3417 sessionAppendInteger(&buf, i*3+2, &rc);
3418 sessionAppendStr(&buf, " THEN ?", &rc);
3419 sessionAppendInteger(&buf, i*3+3, &rc);
3420 sessionAppendStr(&buf, " ELSE ", &rc);
3421 sessionAppendIdent(&buf, p->azCol[i], &rc);
3422 sessionAppendStr(&buf, " END", &rc);
3423 zSep = ", ";
3426 /* Append the PK part of the WHERE clause */
3427 sessionAppendStr(&buf, " WHERE ", &rc);
3428 for(i=0; i<p->nCol; i++){
3429 if( p->abPK[i] ){
3430 sessionAppendIdent(&buf, p->azCol[i], &rc);
3431 sessionAppendStr(&buf, " = ?", &rc);
3432 sessionAppendInteger(&buf, i*3+1, &rc);
3433 sessionAppendStr(&buf, " AND ", &rc);
3437 /* Append the non-PK part of the WHERE clause */
3438 sessionAppendStr(&buf, " (?", &rc);
3439 sessionAppendInteger(&buf, p->nCol*3+1, &rc);
3440 sessionAppendStr(&buf, " OR 1", &rc);
3441 for(i=0; i<p->nCol; i++){
3442 if( !p->abPK[i] ){
3443 sessionAppendStr(&buf, " AND (?", &rc);
3444 sessionAppendInteger(&buf, i*3+2, &rc);
3445 sessionAppendStr(&buf, "=0 OR ", &rc);
3446 sessionAppendIdent(&buf, p->azCol[i], &rc);
3447 sessionAppendStr(&buf, " IS ?", &rc);
3448 sessionAppendInteger(&buf, i*3+1, &rc);
3449 sessionAppendStr(&buf, ")", &rc);
3452 sessionAppendStr(&buf, ")", &rc);
3454 if( rc==SQLITE_OK ){
3455 rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pUpdate, 0);
3457 sqlite3_free(buf.aBuf);
3459 return rc;
3463 ** Formulate and prepare an SQL statement to query table zTab by primary
3464 ** key. Assuming the following table structure:
3466 ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
3468 ** The SELECT statement looks like this:
3470 ** SELECT * FROM x WHERE a = ?1 AND c = ?3
3472 ** If successful, SQLITE_OK is returned and SessionApplyCtx.pSelect is left
3473 ** pointing to the prepared version of the SQL statement.
3475 static int sessionSelectRow(
3476 sqlite3 *db, /* Database handle */
3477 const char *zTab, /* Table name */
3478 SessionApplyCtx *p /* Session changeset-apply context */
3480 return sessionSelectStmt(
3481 db, "main", zTab, p->nCol, p->azCol, p->abPK, &p->pSelect);
3485 ** Formulate and prepare an INSERT statement to add a record to table zTab.
3486 ** For example:
3488 ** INSERT INTO main."zTab" VALUES(?1, ?2, ?3 ...);
3490 ** If successful, SQLITE_OK is returned and SessionApplyCtx.pInsert is left
3491 ** pointing to the prepared version of the SQL statement.
3493 static int sessionInsertRow(
3494 sqlite3 *db, /* Database handle */
3495 const char *zTab, /* Table name */
3496 SessionApplyCtx *p /* Session changeset-apply context */
3498 int rc = SQLITE_OK;
3499 int i;
3500 SessionBuffer buf = {0, 0, 0};
3502 sessionAppendStr(&buf, "INSERT INTO main.", &rc);
3503 sessionAppendIdent(&buf, zTab, &rc);
3504 sessionAppendStr(&buf, "(", &rc);
3505 for(i=0; i<p->nCol; i++){
3506 if( i!=0 ) sessionAppendStr(&buf, ", ", &rc);
3507 sessionAppendIdent(&buf, p->azCol[i], &rc);
3510 sessionAppendStr(&buf, ") VALUES(?", &rc);
3511 for(i=1; i<p->nCol; i++){
3512 sessionAppendStr(&buf, ", ?", &rc);
3514 sessionAppendStr(&buf, ")", &rc);
3516 if( rc==SQLITE_OK ){
3517 rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pInsert, 0);
3519 sqlite3_free(buf.aBuf);
3520 return rc;
3524 ** A wrapper around sqlite3_bind_value() that detects an extra problem.
3525 ** See comments in the body of this function for details.
3527 static int sessionBindValue(
3528 sqlite3_stmt *pStmt, /* Statement to bind value to */
3529 int i, /* Parameter number to bind to */
3530 sqlite3_value *pVal /* Value to bind */
3532 int eType = sqlite3_value_type(pVal);
3533 /* COVERAGE: The (pVal->z==0) branch is never true using current versions
3534 ** of SQLite. If a malloc fails in an sqlite3_value_xxx() function, either
3535 ** the (pVal->z) variable remains as it was or the type of the value is
3536 ** set to SQLITE_NULL. */
3537 if( (eType==SQLITE_TEXT || eType==SQLITE_BLOB) && pVal->z==0 ){
3538 /* This condition occurs when an earlier OOM in a call to
3539 ** sqlite3_value_text() or sqlite3_value_blob() (perhaps from within
3540 ** a conflict-handler) has zeroed the pVal->z pointer. Return NOMEM. */
3541 return SQLITE_NOMEM;
3543 return sqlite3_bind_value(pStmt, i, pVal);
3547 ** Iterator pIter must point to an SQLITE_INSERT entry. This function
3548 ** transfers new.* values from the current iterator entry to statement
3549 ** pStmt. The table being inserted into has nCol columns.
3551 ** New.* value $i from the iterator is bound to variable ($i+1) of
3552 ** statement pStmt. If parameter abPK is NULL, all values from 0 to (nCol-1)
3553 ** are transfered to the statement. Otherwise, if abPK is not NULL, it points
3554 ** to an array nCol elements in size. In this case only those values for
3555 ** which abPK[$i] is true are read from the iterator and bound to the
3556 ** statement.
3558 ** An SQLite error code is returned if an error occurs. Otherwise, SQLITE_OK.
3560 static int sessionBindRow(
3561 sqlite3_changeset_iter *pIter, /* Iterator to read values from */
3562 int(*xValue)(sqlite3_changeset_iter *, int, sqlite3_value **),
3563 int nCol, /* Number of columns */
3564 u8 *abPK, /* If not NULL, bind only if true */
3565 sqlite3_stmt *pStmt /* Bind values to this statement */
3567 int i;
3568 int rc = SQLITE_OK;
3570 /* Neither sqlite3changeset_old or sqlite3changeset_new can fail if the
3571 ** argument iterator points to a suitable entry. Make sure that xValue
3572 ** is one of these to guarantee that it is safe to ignore the return
3573 ** in the code below. */
3574 assert( xValue==sqlite3changeset_old || xValue==sqlite3changeset_new );
3576 for(i=0; rc==SQLITE_OK && i<nCol; i++){
3577 if( !abPK || abPK[i] ){
3578 sqlite3_value *pVal;
3579 (void)xValue(pIter, i, &pVal);
3580 rc = sessionBindValue(pStmt, i+1, pVal);
3583 return rc;
3587 ** SQL statement pSelect is as generated by the sessionSelectRow() function.
3588 ** This function binds the primary key values from the change that changeset
3589 ** iterator pIter points to to the SELECT and attempts to seek to the table
3590 ** entry. If a row is found, the SELECT statement left pointing at the row
3591 ** and SQLITE_ROW is returned. Otherwise, if no row is found and no error
3592 ** has occured, the statement is reset and SQLITE_OK is returned. If an
3593 ** error occurs, the statement is reset and an SQLite error code is returned.
3595 ** If this function returns SQLITE_ROW, the caller must eventually reset()
3596 ** statement pSelect. If any other value is returned, the statement does
3597 ** not require a reset().
3599 ** If the iterator currently points to an INSERT record, bind values from the
3600 ** new.* record to the SELECT statement. Or, if it points to a DELETE or
3601 ** UPDATE, bind values from the old.* record.
3603 static int sessionSeekToRow(
3604 sqlite3 *db, /* Database handle */
3605 sqlite3_changeset_iter *pIter, /* Changeset iterator */
3606 u8 *abPK, /* Primary key flags array */
3607 sqlite3_stmt *pSelect /* SELECT statement from sessionSelectRow() */
3609 int rc; /* Return code */
3610 int nCol; /* Number of columns in table */
3611 int op; /* Changset operation (SQLITE_UPDATE etc.) */
3612 const char *zDummy; /* Unused */
3614 sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
3615 rc = sessionBindRow(pIter,
3616 op==SQLITE_INSERT ? sqlite3changeset_new : sqlite3changeset_old,
3617 nCol, abPK, pSelect
3620 if( rc==SQLITE_OK ){
3621 rc = sqlite3_step(pSelect);
3622 if( rc!=SQLITE_ROW ) rc = sqlite3_reset(pSelect);
3625 return rc;
3629 ** Invoke the conflict handler for the change that the changeset iterator
3630 ** currently points to.
3632 ** Argument eType must be either CHANGESET_DATA or CHANGESET_CONFLICT.
3633 ** If argument pbReplace is NULL, then the type of conflict handler invoked
3634 ** depends solely on eType, as follows:
3636 ** eType value Value passed to xConflict
3637 ** -------------------------------------------------
3638 ** CHANGESET_DATA CHANGESET_NOTFOUND
3639 ** CHANGESET_CONFLICT CHANGESET_CONSTRAINT
3641 ** Or, if pbReplace is not NULL, then an attempt is made to find an existing
3642 ** record with the same primary key as the record about to be deleted, updated
3643 ** or inserted. If such a record can be found, it is available to the conflict
3644 ** handler as the "conflicting" record. In this case the type of conflict
3645 ** handler invoked is as follows:
3647 ** eType value PK Record found? Value passed to xConflict
3648 ** ----------------------------------------------------------------
3649 ** CHANGESET_DATA Yes CHANGESET_DATA
3650 ** CHANGESET_DATA No CHANGESET_NOTFOUND
3651 ** CHANGESET_CONFLICT Yes CHANGESET_CONFLICT
3652 ** CHANGESET_CONFLICT No CHANGESET_CONSTRAINT
3654 ** If pbReplace is not NULL, and a record with a matching PK is found, and
3655 ** the conflict handler function returns SQLITE_CHANGESET_REPLACE, *pbReplace
3656 ** is set to non-zero before returning SQLITE_OK.
3658 ** If the conflict handler returns SQLITE_CHANGESET_ABORT, SQLITE_ABORT is
3659 ** returned. Or, if the conflict handler returns an invalid value,
3660 ** SQLITE_MISUSE. If the conflict handler returns SQLITE_CHANGESET_OMIT,
3661 ** this function returns SQLITE_OK.
3663 static int sessionConflictHandler(
3664 int eType, /* Either CHANGESET_DATA or CONFLICT */
3665 SessionApplyCtx *p, /* changeset_apply() context */
3666 sqlite3_changeset_iter *pIter, /* Changeset iterator */
3667 int(*xConflict)(void *, int, sqlite3_changeset_iter*),
3668 void *pCtx, /* First argument for conflict handler */
3669 int *pbReplace /* OUT: Set to true if PK row is found */
3671 int res = 0; /* Value returned by conflict handler */
3672 int rc;
3673 int nCol;
3674 int op;
3675 const char *zDummy;
3677 sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
3679 assert( eType==SQLITE_CHANGESET_CONFLICT || eType==SQLITE_CHANGESET_DATA );
3680 assert( SQLITE_CHANGESET_CONFLICT+1==SQLITE_CHANGESET_CONSTRAINT );
3681 assert( SQLITE_CHANGESET_DATA+1==SQLITE_CHANGESET_NOTFOUND );
3683 /* Bind the new.* PRIMARY KEY values to the SELECT statement. */
3684 if( pbReplace ){
3685 rc = sessionSeekToRow(p->db, pIter, p->abPK, p->pSelect);
3686 }else{
3687 rc = SQLITE_OK;
3690 if( rc==SQLITE_ROW ){
3691 /* There exists another row with the new.* primary key. */
3692 pIter->pConflict = p->pSelect;
3693 res = xConflict(pCtx, eType, pIter);
3694 pIter->pConflict = 0;
3695 rc = sqlite3_reset(p->pSelect);
3696 }else if( rc==SQLITE_OK ){
3697 if( p->bDeferConstraints && eType==SQLITE_CHANGESET_CONFLICT ){
3698 /* Instead of invoking the conflict handler, append the change blob
3699 ** to the SessionApplyCtx.constraints buffer. */
3700 u8 *aBlob = &pIter->in.aData[pIter->in.iCurrent];
3701 int nBlob = pIter->in.iNext - pIter->in.iCurrent;
3702 sessionAppendBlob(&p->constraints, aBlob, nBlob, &rc);
3703 res = SQLITE_CHANGESET_OMIT;
3704 }else{
3705 /* No other row with the new.* primary key. */
3706 res = xConflict(pCtx, eType+1, pIter);
3707 if( res==SQLITE_CHANGESET_REPLACE ) rc = SQLITE_MISUSE;
3711 if( rc==SQLITE_OK ){
3712 switch( res ){
3713 case SQLITE_CHANGESET_REPLACE:
3714 assert( pbReplace );
3715 *pbReplace = 1;
3716 break;
3718 case SQLITE_CHANGESET_OMIT:
3719 break;
3721 case SQLITE_CHANGESET_ABORT:
3722 rc = SQLITE_ABORT;
3723 break;
3725 default:
3726 rc = SQLITE_MISUSE;
3727 break;
3731 return rc;
3735 ** Attempt to apply the change that the iterator passed as the first argument
3736 ** currently points to to the database. If a conflict is encountered, invoke
3737 ** the conflict handler callback.
3739 ** If argument pbRetry is NULL, then ignore any CHANGESET_DATA conflict. If
3740 ** one is encountered, update or delete the row with the matching primary key
3741 ** instead. Or, if pbRetry is not NULL and a CHANGESET_DATA conflict occurs,
3742 ** invoke the conflict handler. If it returns CHANGESET_REPLACE, set *pbRetry
3743 ** to true before returning. In this case the caller will invoke this function
3744 ** again, this time with pbRetry set to NULL.
3746 ** If argument pbReplace is NULL and a CHANGESET_CONFLICT conflict is
3747 ** encountered invoke the conflict handler with CHANGESET_CONSTRAINT instead.
3748 ** Or, if pbReplace is not NULL, invoke it with CHANGESET_CONFLICT. If such
3749 ** an invocation returns SQLITE_CHANGESET_REPLACE, set *pbReplace to true
3750 ** before retrying. In this case the caller attempts to remove the conflicting
3751 ** row before invoking this function again, this time with pbReplace set
3752 ** to NULL.
3754 ** If any conflict handler returns SQLITE_CHANGESET_ABORT, this function
3755 ** returns SQLITE_ABORT. Otherwise, if no error occurs, SQLITE_OK is
3756 ** returned.
3758 static int sessionApplyOneOp(
3759 sqlite3_changeset_iter *pIter, /* Changeset iterator */
3760 SessionApplyCtx *p, /* changeset_apply() context */
3761 int(*xConflict)(void *, int, sqlite3_changeset_iter *),
3762 void *pCtx, /* First argument for the conflict handler */
3763 int *pbReplace, /* OUT: True to remove PK row and retry */
3764 int *pbRetry /* OUT: True to retry. */
3766 const char *zDummy;
3767 int op;
3768 int nCol;
3769 int rc = SQLITE_OK;
3771 assert( p->pDelete && p->pUpdate && p->pInsert && p->pSelect );
3772 assert( p->azCol && p->abPK );
3773 assert( !pbReplace || *pbReplace==0 );
3775 sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
3777 if( op==SQLITE_DELETE ){
3779 /* Bind values to the DELETE statement. If conflict handling is required,
3780 ** bind values for all columns and set bound variable (nCol+1) to true.
3781 ** Or, if conflict handling is not required, bind just the PK column
3782 ** values and, if it exists, set (nCol+1) to false. Conflict handling
3783 ** is not required if:
3785 ** * this is a patchset, or
3786 ** * (pbRetry==0), or
3787 ** * all columns of the table are PK columns (in this case there is
3788 ** no (nCol+1) variable to bind to).
3790 u8 *abPK = (pIter->bPatchset ? p->abPK : 0);
3791 rc = sessionBindRow(pIter, sqlite3changeset_old, nCol, abPK, p->pDelete);
3792 if( rc==SQLITE_OK && sqlite3_bind_parameter_count(p->pDelete)>nCol ){
3793 rc = sqlite3_bind_int(p->pDelete, nCol+1, (pbRetry==0 || abPK));
3795 if( rc!=SQLITE_OK ) return rc;
3797 sqlite3_step(p->pDelete);
3798 rc = sqlite3_reset(p->pDelete);
3799 if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
3800 rc = sessionConflictHandler(
3801 SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
3803 }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
3804 rc = sessionConflictHandler(
3805 SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
3809 }else if( op==SQLITE_UPDATE ){
3810 int i;
3812 /* Bind values to the UPDATE statement. */
3813 for(i=0; rc==SQLITE_OK && i<nCol; i++){
3814 sqlite3_value *pOld = sessionChangesetOld(pIter, i);
3815 sqlite3_value *pNew = sessionChangesetNew(pIter, i);
3817 sqlite3_bind_int(p->pUpdate, i*3+2, !!pNew);
3818 if( pOld ){
3819 rc = sessionBindValue(p->pUpdate, i*3+1, pOld);
3821 if( rc==SQLITE_OK && pNew ){
3822 rc = sessionBindValue(p->pUpdate, i*3+3, pNew);
3825 if( rc==SQLITE_OK ){
3826 sqlite3_bind_int(p->pUpdate, nCol*3+1, pbRetry==0 || pIter->bPatchset);
3828 if( rc!=SQLITE_OK ) return rc;
3830 /* Attempt the UPDATE. In the case of a NOTFOUND or DATA conflict,
3831 ** the result will be SQLITE_OK with 0 rows modified. */
3832 sqlite3_step(p->pUpdate);
3833 rc = sqlite3_reset(p->pUpdate);
3835 if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
3836 /* A NOTFOUND or DATA error. Search the table to see if it contains
3837 ** a row with a matching primary key. If so, this is a DATA conflict.
3838 ** Otherwise, if there is no primary key match, it is a NOTFOUND. */
3840 rc = sessionConflictHandler(
3841 SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
3844 }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
3845 /* This is always a CONSTRAINT conflict. */
3846 rc = sessionConflictHandler(
3847 SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
3851 }else{
3852 assert( op==SQLITE_INSERT );
3853 rc = sessionBindRow(pIter, sqlite3changeset_new, nCol, 0, p->pInsert);
3854 if( rc!=SQLITE_OK ) return rc;
3856 sqlite3_step(p->pInsert);
3857 rc = sqlite3_reset(p->pInsert);
3858 if( (rc&0xff)==SQLITE_CONSTRAINT ){
3859 rc = sessionConflictHandler(
3860 SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, pbReplace
3865 return rc;
3869 ** Attempt to apply the change that the iterator passed as the first argument
3870 ** currently points to to the database. If a conflict is encountered, invoke
3871 ** the conflict handler callback.
3873 ** The difference between this function and sessionApplyOne() is that this
3874 ** function handles the case where the conflict-handler is invoked and
3875 ** returns SQLITE_CHANGESET_REPLACE - indicating that the change should be
3876 ** retried in some manner.
3878 static int sessionApplyOneWithRetry(
3879 sqlite3 *db, /* Apply change to "main" db of this handle */
3880 sqlite3_changeset_iter *pIter, /* Changeset iterator to read change from */
3881 SessionApplyCtx *pApply, /* Apply context */
3882 int(*xConflict)(void*, int, sqlite3_changeset_iter*),
3883 void *pCtx /* First argument passed to xConflict */
3885 int bReplace = 0;
3886 int bRetry = 0;
3887 int rc;
3889 rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, &bReplace, &bRetry);
3890 assert( rc==SQLITE_OK || (bRetry==0 && bReplace==0) );
3892 /* If the bRetry flag is set, the change has not been applied due to an
3893 ** SQLITE_CHANGESET_DATA problem (i.e. this is an UPDATE or DELETE and
3894 ** a row with the correct PK is present in the db, but one or more other
3895 ** fields do not contain the expected values) and the conflict handler
3896 ** returned SQLITE_CHANGESET_REPLACE. In this case retry the operation,
3897 ** but pass NULL as the final argument so that sessionApplyOneOp() ignores
3898 ** the SQLITE_CHANGESET_DATA problem. */
3899 if( bRetry ){
3900 assert( pIter->op==SQLITE_UPDATE || pIter->op==SQLITE_DELETE );
3901 rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
3904 /* If the bReplace flag is set, the change is an INSERT that has not
3905 ** been performed because the database already contains a row with the
3906 ** specified primary key and the conflict handler returned
3907 ** SQLITE_CHANGESET_REPLACE. In this case remove the conflicting row
3908 ** before reattempting the INSERT. */
3909 else if( bReplace ){
3910 assert( pIter->op==SQLITE_INSERT );
3911 rc = sqlite3_exec(db, "SAVEPOINT replace_op", 0, 0, 0);
3912 if( rc==SQLITE_OK ){
3913 rc = sessionBindRow(pIter,
3914 sqlite3changeset_new, pApply->nCol, pApply->abPK, pApply->pDelete);
3915 sqlite3_bind_int(pApply->pDelete, pApply->nCol+1, 1);
3917 if( rc==SQLITE_OK ){
3918 sqlite3_step(pApply->pDelete);
3919 rc = sqlite3_reset(pApply->pDelete);
3921 if( rc==SQLITE_OK ){
3922 rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
3924 if( rc==SQLITE_OK ){
3925 rc = sqlite3_exec(db, "RELEASE replace_op", 0, 0, 0);
3929 return rc;
3933 ** Retry the changes accumulated in the pApply->constraints buffer.
3935 static int sessionRetryConstraints(
3936 sqlite3 *db,
3937 int bPatchset,
3938 const char *zTab,
3939 SessionApplyCtx *pApply,
3940 int(*xConflict)(void*, int, sqlite3_changeset_iter*),
3941 void *pCtx /* First argument passed to xConflict */
3943 int rc = SQLITE_OK;
3945 while( pApply->constraints.nBuf ){
3946 sqlite3_changeset_iter *pIter2 = 0;
3947 SessionBuffer cons = pApply->constraints;
3948 memset(&pApply->constraints, 0, sizeof(SessionBuffer));
3950 rc = sessionChangesetStart(&pIter2, 0, 0, cons.nBuf, cons.aBuf);
3951 if( rc==SQLITE_OK ){
3952 int nByte = 2*pApply->nCol*sizeof(sqlite3_value*);
3953 int rc2;
3954 pIter2->bPatchset = bPatchset;
3955 pIter2->zTab = (char*)zTab;
3956 pIter2->nCol = pApply->nCol;
3957 pIter2->abPK = pApply->abPK;
3958 sessionBufferGrow(&pIter2->tblhdr, nByte, &rc);
3959 pIter2->apValue = (sqlite3_value**)pIter2->tblhdr.aBuf;
3960 if( rc==SQLITE_OK ) memset(pIter2->apValue, 0, nByte);
3962 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter2) ){
3963 rc = sessionApplyOneWithRetry(db, pIter2, pApply, xConflict, pCtx);
3966 rc2 = sqlite3changeset_finalize(pIter2);
3967 if( rc==SQLITE_OK ) rc = rc2;
3969 assert( pApply->bDeferConstraints || pApply->constraints.nBuf==0 );
3971 sqlite3_free(cons.aBuf);
3972 if( rc!=SQLITE_OK ) break;
3973 if( pApply->constraints.nBuf>=cons.nBuf ){
3974 /* No progress was made on the last round. */
3975 pApply->bDeferConstraints = 0;
3979 return rc;
3983 ** Argument pIter is a changeset iterator that has been initialized, but
3984 ** not yet passed to sqlite3changeset_next(). This function applies the
3985 ** changeset to the main database attached to handle "db". The supplied
3986 ** conflict handler callback is invoked to resolve any conflicts encountered
3987 ** while applying the change.
3989 static int sessionChangesetApply(
3990 sqlite3 *db, /* Apply change to "main" db of this handle */
3991 sqlite3_changeset_iter *pIter, /* Changeset to apply */
3992 int(*xFilter)(
3993 void *pCtx, /* Copy of sixth arg to _apply() */
3994 const char *zTab /* Table name */
3996 int(*xConflict)(
3997 void *pCtx, /* Copy of fifth arg to _apply() */
3998 int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
3999 sqlite3_changeset_iter *p /* Handle describing change and conflict */
4001 void *pCtx /* First argument passed to xConflict */
4003 int schemaMismatch = 0;
4004 int rc; /* Return code */
4005 const char *zTab = 0; /* Name of current table */
4006 int nTab = 0; /* Result of sqlite3Strlen30(zTab) */
4007 SessionApplyCtx sApply; /* changeset_apply() context object */
4008 int bPatchset;
4010 assert( xConflict!=0 );
4012 pIter->in.bNoDiscard = 1;
4013 memset(&sApply, 0, sizeof(sApply));
4014 sqlite3_mutex_enter(sqlite3_db_mutex(db));
4015 rc = sqlite3_exec(db, "SAVEPOINT changeset_apply", 0, 0, 0);
4016 if( rc==SQLITE_OK ){
4017 rc = sqlite3_exec(db, "PRAGMA defer_foreign_keys = 1", 0, 0, 0);
4019 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter) ){
4020 int nCol;
4021 int op;
4022 const char *zNew;
4024 sqlite3changeset_op(pIter, &zNew, &nCol, &op, 0);
4026 if( zTab==0 || sqlite3_strnicmp(zNew, zTab, nTab+1) ){
4027 u8 *abPK;
4029 rc = sessionRetryConstraints(
4030 db, pIter->bPatchset, zTab, &sApply, xConflict, pCtx
4032 if( rc!=SQLITE_OK ) break;
4034 sqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */
4035 sqlite3_finalize(sApply.pDelete);
4036 sqlite3_finalize(sApply.pUpdate);
4037 sqlite3_finalize(sApply.pInsert);
4038 sqlite3_finalize(sApply.pSelect);
4039 memset(&sApply, 0, sizeof(sApply));
4040 sApply.db = db;
4041 sApply.bDeferConstraints = 1;
4043 /* If an xFilter() callback was specified, invoke it now. If the
4044 ** xFilter callback returns zero, skip this table. If it returns
4045 ** non-zero, proceed. */
4046 schemaMismatch = (xFilter && (0==xFilter(pCtx, zNew)));
4047 if( schemaMismatch ){
4048 zTab = sqlite3_mprintf("%s", zNew);
4049 if( zTab==0 ){
4050 rc = SQLITE_NOMEM;
4051 break;
4053 nTab = (int)strlen(zTab);
4054 sApply.azCol = (const char **)zTab;
4055 }else{
4056 int nMinCol = 0;
4057 int i;
4059 sqlite3changeset_pk(pIter, &abPK, 0);
4060 rc = sessionTableInfo(
4061 db, "main", zNew, &sApply.nCol, &zTab, &sApply.azCol, &sApply.abPK
4063 if( rc!=SQLITE_OK ) break;
4064 for(i=0; i<sApply.nCol; i++){
4065 if( sApply.abPK[i] ) nMinCol = i+1;
4068 if( sApply.nCol==0 ){
4069 schemaMismatch = 1;
4070 sqlite3_log(SQLITE_SCHEMA,
4071 "sqlite3changeset_apply(): no such table: %s", zTab
4074 else if( sApply.nCol<nCol ){
4075 schemaMismatch = 1;
4076 sqlite3_log(SQLITE_SCHEMA,
4077 "sqlite3changeset_apply(): table %s has %d columns, "
4078 "expected %d or more",
4079 zTab, sApply.nCol, nCol
4082 else if( nCol<nMinCol || memcmp(sApply.abPK, abPK, nCol)!=0 ){
4083 schemaMismatch = 1;
4084 sqlite3_log(SQLITE_SCHEMA, "sqlite3changeset_apply(): "
4085 "primary key mismatch for table %s", zTab
4088 else{
4089 sApply.nCol = nCol;
4090 if((rc = sessionSelectRow(db, zTab, &sApply))
4091 || (rc = sessionUpdateRow(db, zTab, &sApply))
4092 || (rc = sessionDeleteRow(db, zTab, &sApply))
4093 || (rc = sessionInsertRow(db, zTab, &sApply))
4095 break;
4098 nTab = sqlite3Strlen30(zTab);
4102 /* If there is a schema mismatch on the current table, proceed to the
4103 ** next change. A log message has already been issued. */
4104 if( schemaMismatch ) continue;
4106 rc = sessionApplyOneWithRetry(db, pIter, &sApply, xConflict, pCtx);
4109 bPatchset = pIter->bPatchset;
4110 if( rc==SQLITE_OK ){
4111 rc = sqlite3changeset_finalize(pIter);
4112 }else{
4113 sqlite3changeset_finalize(pIter);
4116 if( rc==SQLITE_OK ){
4117 rc = sessionRetryConstraints(db, bPatchset, zTab, &sApply, xConflict, pCtx);
4120 if( rc==SQLITE_OK ){
4121 int nFk, notUsed;
4122 sqlite3_db_status(db, SQLITE_DBSTATUS_DEFERRED_FKS, &nFk, &notUsed, 0);
4123 if( nFk!=0 ){
4124 int res = SQLITE_CHANGESET_ABORT;
4125 sqlite3_changeset_iter sIter;
4126 memset(&sIter, 0, sizeof(sIter));
4127 sIter.nCol = nFk;
4128 res = xConflict(pCtx, SQLITE_CHANGESET_FOREIGN_KEY, &sIter);
4129 if( res!=SQLITE_CHANGESET_OMIT ){
4130 rc = SQLITE_CONSTRAINT;
4134 sqlite3_exec(db, "PRAGMA defer_foreign_keys = 0", 0, 0, 0);
4136 if( rc==SQLITE_OK ){
4137 rc = sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
4138 }else{
4139 sqlite3_exec(db, "ROLLBACK TO changeset_apply", 0, 0, 0);
4140 sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
4143 sqlite3_finalize(sApply.pInsert);
4144 sqlite3_finalize(sApply.pDelete);
4145 sqlite3_finalize(sApply.pUpdate);
4146 sqlite3_finalize(sApply.pSelect);
4147 sqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */
4148 sqlite3_free((char*)sApply.constraints.aBuf);
4149 sqlite3_mutex_leave(sqlite3_db_mutex(db));
4150 return rc;
4154 ** Apply the changeset passed via pChangeset/nChangeset to the main database
4155 ** attached to handle "db". Invoke the supplied conflict handler callback
4156 ** to resolve any conflicts encountered while applying the change.
4158 int sqlite3changeset_apply(
4159 sqlite3 *db, /* Apply change to "main" db of this handle */
4160 int nChangeset, /* Size of changeset in bytes */
4161 void *pChangeset, /* Changeset blob */
4162 int(*xFilter)(
4163 void *pCtx, /* Copy of sixth arg to _apply() */
4164 const char *zTab /* Table name */
4166 int(*xConflict)(
4167 void *pCtx, /* Copy of fifth arg to _apply() */
4168 int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
4169 sqlite3_changeset_iter *p /* Handle describing change and conflict */
4171 void *pCtx /* First argument passed to xConflict */
4173 sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */
4174 int rc = sqlite3changeset_start(&pIter, nChangeset, pChangeset);
4175 if( rc==SQLITE_OK ){
4176 rc = sessionChangesetApply(db, pIter, xFilter, xConflict, pCtx);
4178 return rc;
4182 ** Apply the changeset passed via xInput/pIn to the main database
4183 ** attached to handle "db". Invoke the supplied conflict handler callback
4184 ** to resolve any conflicts encountered while applying the change.
4186 int sqlite3changeset_apply_strm(
4187 sqlite3 *db, /* Apply change to "main" db of this handle */
4188 int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
4189 void *pIn, /* First arg for xInput */
4190 int(*xFilter)(
4191 void *pCtx, /* Copy of sixth arg to _apply() */
4192 const char *zTab /* Table name */
4194 int(*xConflict)(
4195 void *pCtx, /* Copy of sixth arg to _apply() */
4196 int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
4197 sqlite3_changeset_iter *p /* Handle describing change and conflict */
4199 void *pCtx /* First argument passed to xConflict */
4201 sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */
4202 int rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
4203 if( rc==SQLITE_OK ){
4204 rc = sessionChangesetApply(db, pIter, xFilter, xConflict, pCtx);
4206 return rc;
4210 ** sqlite3_changegroup handle.
4212 struct sqlite3_changegroup {
4213 int rc; /* Error code */
4214 int bPatch; /* True to accumulate patchsets */
4215 SessionTable *pList; /* List of tables in current patch */
4219 ** This function is called to merge two changes to the same row together as
4220 ** part of an sqlite3changeset_concat() operation. A new change object is
4221 ** allocated and a pointer to it stored in *ppNew.
4223 static int sessionChangeMerge(
4224 SessionTable *pTab, /* Table structure */
4225 int bPatchset, /* True for patchsets */
4226 SessionChange *pExist, /* Existing change */
4227 int op2, /* Second change operation */
4228 int bIndirect, /* True if second change is indirect */
4229 u8 *aRec, /* Second change record */
4230 int nRec, /* Number of bytes in aRec */
4231 SessionChange **ppNew /* OUT: Merged change */
4233 SessionChange *pNew = 0;
4235 if( !pExist ){
4236 pNew = (SessionChange *)sqlite3_malloc(sizeof(SessionChange) + nRec);
4237 if( !pNew ){
4238 return SQLITE_NOMEM;
4240 memset(pNew, 0, sizeof(SessionChange));
4241 pNew->op = op2;
4242 pNew->bIndirect = bIndirect;
4243 pNew->nRecord = nRec;
4244 pNew->aRecord = (u8*)&pNew[1];
4245 memcpy(pNew->aRecord, aRec, nRec);
4246 }else{
4247 int op1 = pExist->op;
4250 ** op1=INSERT, op2=INSERT -> Unsupported. Discard op2.
4251 ** op1=INSERT, op2=UPDATE -> INSERT.
4252 ** op1=INSERT, op2=DELETE -> (none)
4254 ** op1=UPDATE, op2=INSERT -> Unsupported. Discard op2.
4255 ** op1=UPDATE, op2=UPDATE -> UPDATE.
4256 ** op1=UPDATE, op2=DELETE -> DELETE.
4258 ** op1=DELETE, op2=INSERT -> UPDATE.
4259 ** op1=DELETE, op2=UPDATE -> Unsupported. Discard op2.
4260 ** op1=DELETE, op2=DELETE -> Unsupported. Discard op2.
4262 if( (op1==SQLITE_INSERT && op2==SQLITE_INSERT)
4263 || (op1==SQLITE_UPDATE && op2==SQLITE_INSERT)
4264 || (op1==SQLITE_DELETE && op2==SQLITE_UPDATE)
4265 || (op1==SQLITE_DELETE && op2==SQLITE_DELETE)
4267 pNew = pExist;
4268 }else if( op1==SQLITE_INSERT && op2==SQLITE_DELETE ){
4269 sqlite3_free(pExist);
4270 assert( pNew==0 );
4271 }else{
4272 u8 *aExist = pExist->aRecord;
4273 int nByte;
4274 u8 *aCsr;
4276 /* Allocate a new SessionChange object. Ensure that the aRecord[]
4277 ** buffer of the new object is large enough to hold any record that
4278 ** may be generated by combining the input records. */
4279 nByte = sizeof(SessionChange) + pExist->nRecord + nRec;
4280 pNew = (SessionChange *)sqlite3_malloc(nByte);
4281 if( !pNew ){
4282 sqlite3_free(pExist);
4283 return SQLITE_NOMEM;
4285 memset(pNew, 0, sizeof(SessionChange));
4286 pNew->bIndirect = (bIndirect && pExist->bIndirect);
4287 aCsr = pNew->aRecord = (u8 *)&pNew[1];
4289 if( op1==SQLITE_INSERT ){ /* INSERT + UPDATE */
4290 u8 *a1 = aRec;
4291 assert( op2==SQLITE_UPDATE );
4292 pNew->op = SQLITE_INSERT;
4293 if( bPatchset==0 ) sessionSkipRecord(&a1, pTab->nCol);
4294 sessionMergeRecord(&aCsr, pTab->nCol, aExist, a1);
4295 }else if( op1==SQLITE_DELETE ){ /* DELETE + INSERT */
4296 assert( op2==SQLITE_INSERT );
4297 pNew->op = SQLITE_UPDATE;
4298 if( bPatchset ){
4299 memcpy(aCsr, aRec, nRec);
4300 aCsr += nRec;
4301 }else{
4302 if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aExist, 0,aRec,0) ){
4303 sqlite3_free(pNew);
4304 pNew = 0;
4307 }else if( op2==SQLITE_UPDATE ){ /* UPDATE + UPDATE */
4308 u8 *a1 = aExist;
4309 u8 *a2 = aRec;
4310 assert( op1==SQLITE_UPDATE );
4311 if( bPatchset==0 ){
4312 sessionSkipRecord(&a1, pTab->nCol);
4313 sessionSkipRecord(&a2, pTab->nCol);
4315 pNew->op = SQLITE_UPDATE;
4316 if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aRec, aExist,a1,a2) ){
4317 sqlite3_free(pNew);
4318 pNew = 0;
4320 }else{ /* UPDATE + DELETE */
4321 assert( op1==SQLITE_UPDATE && op2==SQLITE_DELETE );
4322 pNew->op = SQLITE_DELETE;
4323 if( bPatchset ){
4324 memcpy(aCsr, aRec, nRec);
4325 aCsr += nRec;
4326 }else{
4327 sessionMergeRecord(&aCsr, pTab->nCol, aRec, aExist);
4331 if( pNew ){
4332 pNew->nRecord = (int)(aCsr - pNew->aRecord);
4334 sqlite3_free(pExist);
4338 *ppNew = pNew;
4339 return SQLITE_OK;
4343 ** Add all changes in the changeset traversed by the iterator passed as
4344 ** the first argument to the changegroup hash tables.
4346 static int sessionChangesetToHash(
4347 sqlite3_changeset_iter *pIter, /* Iterator to read from */
4348 sqlite3_changegroup *pGrp /* Changegroup object to add changeset to */
4350 u8 *aRec;
4351 int nRec;
4352 int rc = SQLITE_OK;
4353 SessionTable *pTab = 0;
4356 while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec) ){
4357 const char *zNew;
4358 int nCol;
4359 int op;
4360 int iHash;
4361 int bIndirect;
4362 SessionChange *pChange;
4363 SessionChange *pExist = 0;
4364 SessionChange **pp;
4366 if( pGrp->pList==0 ){
4367 pGrp->bPatch = pIter->bPatchset;
4368 }else if( pIter->bPatchset!=pGrp->bPatch ){
4369 rc = SQLITE_ERROR;
4370 break;
4373 sqlite3changeset_op(pIter, &zNew, &nCol, &op, &bIndirect);
4374 if( !pTab || sqlite3_stricmp(zNew, pTab->zName) ){
4375 /* Search the list for a matching table */
4376 int nNew = (int)strlen(zNew);
4377 u8 *abPK;
4379 sqlite3changeset_pk(pIter, &abPK, 0);
4380 for(pTab = pGrp->pList; pTab; pTab=pTab->pNext){
4381 if( 0==sqlite3_strnicmp(pTab->zName, zNew, nNew+1) ) break;
4383 if( !pTab ){
4384 SessionTable **ppTab;
4386 pTab = sqlite3_malloc(sizeof(SessionTable) + nCol + nNew+1);
4387 if( !pTab ){
4388 rc = SQLITE_NOMEM;
4389 break;
4391 memset(pTab, 0, sizeof(SessionTable));
4392 pTab->nCol = nCol;
4393 pTab->abPK = (u8*)&pTab[1];
4394 memcpy(pTab->abPK, abPK, nCol);
4395 pTab->zName = (char*)&pTab->abPK[nCol];
4396 memcpy(pTab->zName, zNew, nNew+1);
4398 /* The new object must be linked on to the end of the list, not
4399 ** simply added to the start of it. This is to ensure that the
4400 ** tables within the output of sqlite3changegroup_output() are in
4401 ** the right order. */
4402 for(ppTab=&pGrp->pList; *ppTab; ppTab=&(*ppTab)->pNext);
4403 *ppTab = pTab;
4404 }else if( pTab->nCol!=nCol || memcmp(pTab->abPK, abPK, nCol) ){
4405 rc = SQLITE_SCHEMA;
4406 break;
4410 if( sessionGrowHash(pIter->bPatchset, pTab) ){
4411 rc = SQLITE_NOMEM;
4412 break;
4414 iHash = sessionChangeHash(
4415 pTab, (pIter->bPatchset && op==SQLITE_DELETE), aRec, pTab->nChange
4418 /* Search for existing entry. If found, remove it from the hash table.
4419 ** Code below may link it back in.
4421 for(pp=&pTab->apChange[iHash]; *pp; pp=&(*pp)->pNext){
4422 int bPkOnly1 = 0;
4423 int bPkOnly2 = 0;
4424 if( pIter->bPatchset ){
4425 bPkOnly1 = (*pp)->op==SQLITE_DELETE;
4426 bPkOnly2 = op==SQLITE_DELETE;
4428 if( sessionChangeEqual(pTab, bPkOnly1, (*pp)->aRecord, bPkOnly2, aRec) ){
4429 pExist = *pp;
4430 *pp = (*pp)->pNext;
4431 pTab->nEntry--;
4432 break;
4436 rc = sessionChangeMerge(pTab,
4437 pIter->bPatchset, pExist, op, bIndirect, aRec, nRec, &pChange
4439 if( rc ) break;
4440 if( pChange ){
4441 pChange->pNext = pTab->apChange[iHash];
4442 pTab->apChange[iHash] = pChange;
4443 pTab->nEntry++;
4447 if( rc==SQLITE_OK ) rc = pIter->rc;
4448 return rc;
4452 ** Serialize a changeset (or patchset) based on all changesets (or patchsets)
4453 ** added to the changegroup object passed as the first argument.
4455 ** If xOutput is not NULL, then the changeset/patchset is returned to the
4456 ** user via one or more calls to xOutput, as with the other streaming
4457 ** interfaces.
4459 ** Or, if xOutput is NULL, then (*ppOut) is populated with a pointer to a
4460 ** buffer containing the output changeset before this function returns. In
4461 ** this case (*pnOut) is set to the size of the output buffer in bytes. It
4462 ** is the responsibility of the caller to free the output buffer using
4463 ** sqlite3_free() when it is no longer required.
4465 ** If successful, SQLITE_OK is returned. Or, if an error occurs, an SQLite
4466 ** error code. If an error occurs and xOutput is NULL, (*ppOut) and (*pnOut)
4467 ** are both set to 0 before returning.
4469 static int sessionChangegroupOutput(
4470 sqlite3_changegroup *pGrp,
4471 int (*xOutput)(void *pOut, const void *pData, int nData),
4472 void *pOut,
4473 int *pnOut,
4474 void **ppOut
4476 int rc = SQLITE_OK;
4477 SessionBuffer buf = {0, 0, 0};
4478 SessionTable *pTab;
4479 assert( xOutput==0 || (ppOut==0 && pnOut==0) );
4481 /* Create the serialized output changeset based on the contents of the
4482 ** hash tables attached to the SessionTable objects in list p->pList.
4484 for(pTab=pGrp->pList; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
4485 int i;
4486 if( pTab->nEntry==0 ) continue;
4488 sessionAppendTableHdr(&buf, pGrp->bPatch, pTab, &rc);
4489 for(i=0; i<pTab->nChange; i++){
4490 SessionChange *p;
4491 for(p=pTab->apChange[i]; p; p=p->pNext){
4492 sessionAppendByte(&buf, p->op, &rc);
4493 sessionAppendByte(&buf, p->bIndirect, &rc);
4494 sessionAppendBlob(&buf, p->aRecord, p->nRecord, &rc);
4498 if( rc==SQLITE_OK && xOutput && buf.nBuf>=SESSIONS_STRM_CHUNK_SIZE ){
4499 rc = xOutput(pOut, buf.aBuf, buf.nBuf);
4500 buf.nBuf = 0;
4504 if( rc==SQLITE_OK ){
4505 if( xOutput ){
4506 if( buf.nBuf>0 ) rc = xOutput(pOut, buf.aBuf, buf.nBuf);
4507 }else{
4508 *ppOut = buf.aBuf;
4509 *pnOut = buf.nBuf;
4510 buf.aBuf = 0;
4513 sqlite3_free(buf.aBuf);
4515 return rc;
4519 ** Allocate a new, empty, sqlite3_changegroup.
4521 int sqlite3changegroup_new(sqlite3_changegroup **pp){
4522 int rc = SQLITE_OK; /* Return code */
4523 sqlite3_changegroup *p; /* New object */
4524 p = (sqlite3_changegroup*)sqlite3_malloc(sizeof(sqlite3_changegroup));
4525 if( p==0 ){
4526 rc = SQLITE_NOMEM;
4527 }else{
4528 memset(p, 0, sizeof(sqlite3_changegroup));
4530 *pp = p;
4531 return rc;
4535 ** Add the changeset currently stored in buffer pData, size nData bytes,
4536 ** to changeset-group p.
4538 int sqlite3changegroup_add(sqlite3_changegroup *pGrp, int nData, void *pData){
4539 sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */
4540 int rc; /* Return code */
4542 rc = sqlite3changeset_start(&pIter, nData, pData);
4543 if( rc==SQLITE_OK ){
4544 rc = sessionChangesetToHash(pIter, pGrp);
4546 sqlite3changeset_finalize(pIter);
4547 return rc;
4551 ** Obtain a buffer containing a changeset representing the concatenation
4552 ** of all changesets added to the group so far.
4554 int sqlite3changegroup_output(
4555 sqlite3_changegroup *pGrp,
4556 int *pnData,
4557 void **ppData
4559 return sessionChangegroupOutput(pGrp, 0, 0, pnData, ppData);
4563 ** Streaming versions of changegroup_add().
4565 int sqlite3changegroup_add_strm(
4566 sqlite3_changegroup *pGrp,
4567 int (*xInput)(void *pIn, void *pData, int *pnData),
4568 void *pIn
4570 sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */
4571 int rc; /* Return code */
4573 rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
4574 if( rc==SQLITE_OK ){
4575 rc = sessionChangesetToHash(pIter, pGrp);
4577 sqlite3changeset_finalize(pIter);
4578 return rc;
4582 ** Streaming versions of changegroup_output().
4584 int sqlite3changegroup_output_strm(
4585 sqlite3_changegroup *pGrp,
4586 int (*xOutput)(void *pOut, const void *pData, int nData),
4587 void *pOut
4589 return sessionChangegroupOutput(pGrp, xOutput, pOut, 0, 0);
4593 ** Delete a changegroup object.
4595 void sqlite3changegroup_delete(sqlite3_changegroup *pGrp){
4596 if( pGrp ){
4597 sessionDeleteTable(pGrp->pList);
4598 sqlite3_free(pGrp);
4603 ** Combine two changesets together.
4605 int sqlite3changeset_concat(
4606 int nLeft, /* Number of bytes in lhs input */
4607 void *pLeft, /* Lhs input changeset */
4608 int nRight /* Number of bytes in rhs input */,
4609 void *pRight, /* Rhs input changeset */
4610 int *pnOut, /* OUT: Number of bytes in output changeset */
4611 void **ppOut /* OUT: changeset (left <concat> right) */
4613 sqlite3_changegroup *pGrp;
4614 int rc;
4616 rc = sqlite3changegroup_new(&pGrp);
4617 if( rc==SQLITE_OK ){
4618 rc = sqlite3changegroup_add(pGrp, nLeft, pLeft);
4620 if( rc==SQLITE_OK ){
4621 rc = sqlite3changegroup_add(pGrp, nRight, pRight);
4623 if( rc==SQLITE_OK ){
4624 rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
4626 sqlite3changegroup_delete(pGrp);
4628 return rc;
4632 ** Streaming version of sqlite3changeset_concat().
4634 int sqlite3changeset_concat_strm(
4635 int (*xInputA)(void *pIn, void *pData, int *pnData),
4636 void *pInA,
4637 int (*xInputB)(void *pIn, void *pData, int *pnData),
4638 void *pInB,
4639 int (*xOutput)(void *pOut, const void *pData, int nData),
4640 void *pOut
4642 sqlite3_changegroup *pGrp;
4643 int rc;
4645 rc = sqlite3changegroup_new(&pGrp);
4646 if( rc==SQLITE_OK ){
4647 rc = sqlite3changegroup_add_strm(pGrp, xInputA, pInA);
4649 if( rc==SQLITE_OK ){
4650 rc = sqlite3changegroup_add_strm(pGrp, xInputB, pInB);
4652 if( rc==SQLITE_OK ){
4653 rc = sqlite3changegroup_output_strm(pGrp, xOutput, pOut);
4655 sqlite3changegroup_delete(pGrp);
4657 return rc;
4660 #endif /* SQLITE_ENABLE_SESSION && SQLITE_ENABLE_PREUPDATE_HOOK */