Enhance the command-line completion extension to return the names of
[sqlite.git] / ext / session / sqlite3session.c
blob9b96c5ca6f01bbf7f0af6303eff3d40162a29c10
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_value *pZeroBlob; /* Value containing X'' */
50 sqlite3_session *pNext; /* Next session object on same db. */
51 SessionTable *pTable; /* List of attached tables */
52 SessionHook hook; /* APIs to grab new and old data with */
56 ** Instances of this structure are used to build strings or binary records.
58 struct SessionBuffer {
59 u8 *aBuf; /* Pointer to changeset buffer */
60 int nBuf; /* Size of buffer aBuf */
61 int nAlloc; /* Size of allocation containing aBuf */
65 ** An object of this type is used internally as an abstraction for
66 ** input data. Input data may be supplied either as a single large buffer
67 ** (e.g. sqlite3changeset_start()) or using a stream function (e.g.
68 ** sqlite3changeset_start_strm()).
70 struct SessionInput {
71 int bNoDiscard; /* If true, discard no data */
72 int iCurrent; /* Offset in aData[] of current change */
73 int iNext; /* Offset in aData[] of next change */
74 u8 *aData; /* Pointer to buffer containing changeset */
75 int nData; /* Number of bytes in aData */
77 SessionBuffer buf; /* Current read buffer */
78 int (*xInput)(void*, void*, int*); /* Input stream call (or NULL) */
79 void *pIn; /* First argument to xInput */
80 int bEof; /* Set to true after xInput finished */
84 ** Structure for changeset iterators.
86 struct sqlite3_changeset_iter {
87 SessionInput in; /* Input buffer or stream */
88 SessionBuffer tblhdr; /* Buffer to hold apValue/zTab/abPK/ */
89 int bPatchset; /* True if this is a patchset */
90 int rc; /* Iterator error code */
91 sqlite3_stmt *pConflict; /* Points to conflicting row, if any */
92 char *zTab; /* Current table */
93 int nCol; /* Number of columns in zTab */
94 int op; /* Current operation */
95 int bIndirect; /* True if current change was indirect */
96 u8 *abPK; /* Primary key array */
97 sqlite3_value **apValue; /* old.* and new.* values */
101 ** Each session object maintains a set of the following structures, one
102 ** for each table the session object is monitoring. The structures are
103 ** stored in a linked list starting at sqlite3_session.pTable.
105 ** The keys of the SessionTable.aChange[] hash table are all rows that have
106 ** been modified in any way since the session object was attached to the
107 ** table.
109 ** The data associated with each hash-table entry is a structure containing
110 ** a subset of the initial values that the modified row contained at the
111 ** start of the session. Or no initial values if the row was inserted.
113 struct SessionTable {
114 SessionTable *pNext;
115 char *zName; /* Local name of table */
116 int nCol; /* Number of columns in table zName */
117 int bStat1; /* True if this is sqlite_stat1 */
118 const char **azCol; /* Column names */
119 u8 *abPK; /* Array of primary key flags */
120 int nEntry; /* Total number of entries in hash table */
121 int nChange; /* Size of apChange[] array */
122 SessionChange **apChange; /* Hash table buckets */
126 ** RECORD FORMAT:
128 ** The following record format is similar to (but not compatible with) that
129 ** used in SQLite database files. This format is used as part of the
130 ** change-set binary format, and so must be architecture independent.
132 ** Unlike the SQLite database record format, each field is self-contained -
133 ** there is no separation of header and data. Each field begins with a
134 ** single byte describing its type, as follows:
136 ** 0x00: Undefined value.
137 ** 0x01: Integer value.
138 ** 0x02: Real value.
139 ** 0x03: Text value.
140 ** 0x04: Blob value.
141 ** 0x05: SQL NULL value.
143 ** Note that the above match the definitions of SQLITE_INTEGER, SQLITE_TEXT
144 ** and so on in sqlite3.h. For undefined and NULL values, the field consists
145 ** only of the single type byte. For other types of values, the type byte
146 ** is followed by:
148 ** Text values:
149 ** A varint containing the number of bytes in the value (encoded using
150 ** UTF-8). Followed by a buffer containing the UTF-8 representation
151 ** of the text value. There is no nul terminator.
153 ** Blob values:
154 ** A varint containing the number of bytes in the value, followed by
155 ** a buffer containing the value itself.
157 ** Integer values:
158 ** An 8-byte big-endian integer value.
160 ** Real values:
161 ** An 8-byte big-endian IEEE 754-2008 real value.
163 ** Varint values are encoded in the same way as varints in the SQLite
164 ** record format.
166 ** CHANGESET FORMAT:
168 ** A changeset is a collection of DELETE, UPDATE and INSERT operations on
169 ** one or more tables. Operations on a single table are grouped together,
170 ** but may occur in any order (i.e. deletes, updates and inserts are all
171 ** mixed together).
173 ** Each group of changes begins with a table header:
175 ** 1 byte: Constant 0x54 (capital 'T')
176 ** Varint: Number of columns in the table.
177 ** nCol bytes: 0x01 for PK columns, 0x00 otherwise.
178 ** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
180 ** Followed by one or more changes to the table.
182 ** 1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
183 ** 1 byte: The "indirect-change" flag.
184 ** old.* record: (delete and update only)
185 ** new.* record: (insert and update only)
187 ** The "old.*" and "new.*" records, if present, are N field records in the
188 ** format described above under "RECORD FORMAT", where N is the number of
189 ** columns in the table. The i'th field of each record is associated with
190 ** the i'th column of the table, counting from left to right in the order
191 ** in which columns were declared in the CREATE TABLE statement.
193 ** The new.* record that is part of each INSERT change contains the values
194 ** that make up the new row. Similarly, the old.* record that is part of each
195 ** DELETE change contains the values that made up the row that was deleted
196 ** from the database. In the changeset format, the records that are part
197 ** of INSERT or DELETE changes never contain any undefined (type byte 0x00)
198 ** fields.
200 ** Within the old.* record associated with an UPDATE change, all fields
201 ** associated with table columns that are not PRIMARY KEY columns and are
202 ** not modified by the UPDATE change are set to "undefined". Other fields
203 ** are set to the values that made up the row before the UPDATE that the
204 ** change records took place. Within the new.* record, fields associated
205 ** with table columns modified by the UPDATE change contain the new
206 ** values. Fields associated with table columns that are not modified
207 ** are set to "undefined".
209 ** PATCHSET FORMAT:
211 ** A patchset is also a collection of changes. It is similar to a changeset,
212 ** but leaves undefined those fields that are not useful if no conflict
213 ** resolution is required when applying the changeset.
215 ** Each group of changes begins with a table header:
217 ** 1 byte: Constant 0x50 (capital 'P')
218 ** Varint: Number of columns in the table.
219 ** nCol bytes: 0x01 for PK columns, 0x00 otherwise.
220 ** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
222 ** Followed by one or more changes to the table.
224 ** 1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
225 ** 1 byte: The "indirect-change" flag.
226 ** single record: (PK fields for DELETE, PK and modified fields for UPDATE,
227 ** full record for INSERT).
229 ** As in the changeset format, each field of the single record that is part
230 ** of a patchset change is associated with the correspondingly positioned
231 ** table column, counting from left to right within the CREATE TABLE
232 ** statement.
234 ** For a DELETE change, all fields within the record except those associated
235 ** with PRIMARY KEY columns are set to "undefined". The PRIMARY KEY fields
236 ** contain the values identifying the row to delete.
238 ** For an UPDATE change, all fields except those associated with PRIMARY KEY
239 ** columns and columns that are modified by the UPDATE are set to "undefined".
240 ** PRIMARY KEY fields contain the values identifying the table row to update,
241 ** and fields associated with modified columns contain the new column values.
243 ** The records associated with INSERT changes are in the same format as for
244 ** changesets. It is not possible for a record associated with an INSERT
245 ** change to contain a field set to "undefined".
249 ** For each row modified during a session, there exists a single instance of
250 ** this structure stored in a SessionTable.aChange[] hash table.
252 struct SessionChange {
253 int op; /* One of UPDATE, DELETE, INSERT */
254 int bIndirect; /* True if this change is "indirect" */
255 int nRecord; /* Number of bytes in buffer aRecord[] */
256 u8 *aRecord; /* Buffer containing old.* record */
257 SessionChange *pNext; /* For hash-table collisions */
261 ** Write a varint with value iVal into the buffer at aBuf. Return the
262 ** number of bytes written.
264 static int sessionVarintPut(u8 *aBuf, int iVal){
265 return putVarint32(aBuf, iVal);
269 ** Return the number of bytes required to store value iVal as a varint.
271 static int sessionVarintLen(int iVal){
272 return sqlite3VarintLen(iVal);
276 ** Read a varint value from aBuf[] into *piVal. Return the number of
277 ** bytes read.
279 static int sessionVarintGet(u8 *aBuf, int *piVal){
280 return getVarint32(aBuf, *piVal);
283 /* Load an unaligned and unsigned 32-bit integer */
284 #define SESSION_UINT32(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
287 ** Read a 64-bit big-endian integer value from buffer aRec[]. Return
288 ** the value read.
290 static sqlite3_int64 sessionGetI64(u8 *aRec){
291 u64 x = SESSION_UINT32(aRec);
292 u32 y = SESSION_UINT32(aRec+4);
293 x = (x<<32) + y;
294 return (sqlite3_int64)x;
298 ** Write a 64-bit big-endian integer value to the buffer aBuf[].
300 static void sessionPutI64(u8 *aBuf, sqlite3_int64 i){
301 aBuf[0] = (i>>56) & 0xFF;
302 aBuf[1] = (i>>48) & 0xFF;
303 aBuf[2] = (i>>40) & 0xFF;
304 aBuf[3] = (i>>32) & 0xFF;
305 aBuf[4] = (i>>24) & 0xFF;
306 aBuf[5] = (i>>16) & 0xFF;
307 aBuf[6] = (i>> 8) & 0xFF;
308 aBuf[7] = (i>> 0) & 0xFF;
312 ** This function is used to serialize the contents of value pValue (see
313 ** comment titled "RECORD FORMAT" above).
315 ** If it is non-NULL, the serialized form of the value is written to
316 ** buffer aBuf. *pnWrite is set to the number of bytes written before
317 ** returning. Or, if aBuf is NULL, the only thing this function does is
318 ** set *pnWrite.
320 ** If no error occurs, SQLITE_OK is returned. Or, if an OOM error occurs
321 ** within a call to sqlite3_value_text() (may fail if the db is utf-16))
322 ** SQLITE_NOMEM is returned.
324 static int sessionSerializeValue(
325 u8 *aBuf, /* If non-NULL, write serialized value here */
326 sqlite3_value *pValue, /* Value to serialize */
327 int *pnWrite /* IN/OUT: Increment by bytes written */
329 int nByte; /* Size of serialized value in bytes */
331 if( pValue ){
332 int eType; /* Value type (SQLITE_NULL, TEXT etc.) */
334 eType = sqlite3_value_type(pValue);
335 if( aBuf ) aBuf[0] = eType;
337 switch( eType ){
338 case SQLITE_NULL:
339 nByte = 1;
340 break;
342 case SQLITE_INTEGER:
343 case SQLITE_FLOAT:
344 if( aBuf ){
345 /* TODO: SQLite does something special to deal with mixed-endian
346 ** floating point values (e.g. ARM7). This code probably should
347 ** too. */
348 u64 i;
349 if( eType==SQLITE_INTEGER ){
350 i = (u64)sqlite3_value_int64(pValue);
351 }else{
352 double r;
353 assert( sizeof(double)==8 && sizeof(u64)==8 );
354 r = sqlite3_value_double(pValue);
355 memcpy(&i, &r, 8);
357 sessionPutI64(&aBuf[1], i);
359 nByte = 9;
360 break;
362 default: {
363 u8 *z;
364 int n;
365 int nVarint;
367 assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
368 if( eType==SQLITE_TEXT ){
369 z = (u8 *)sqlite3_value_text(pValue);
370 }else{
371 z = (u8 *)sqlite3_value_blob(pValue);
373 n = sqlite3_value_bytes(pValue);
374 if( z==0 && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
375 nVarint = sessionVarintLen(n);
377 if( aBuf ){
378 sessionVarintPut(&aBuf[1], n);
379 if( n ) memcpy(&aBuf[nVarint + 1], z, n);
382 nByte = 1 + nVarint + n;
383 break;
386 }else{
387 nByte = 1;
388 if( aBuf ) aBuf[0] = '\0';
391 if( pnWrite ) *pnWrite += nByte;
392 return SQLITE_OK;
397 ** This macro is used to calculate hash key values for data structures. In
398 ** order to use this macro, the entire data structure must be represented
399 ** as a series of unsigned integers. In order to calculate a hash-key value
400 ** for a data structure represented as three such integers, the macro may
401 ** then be used as follows:
403 ** int hash_key_value;
404 ** hash_key_value = HASH_APPEND(0, <value 1>);
405 ** hash_key_value = HASH_APPEND(hash_key_value, <value 2>);
406 ** hash_key_value = HASH_APPEND(hash_key_value, <value 3>);
408 ** In practice, the data structures this macro is used for are the primary
409 ** key values of modified rows.
411 #define HASH_APPEND(hash, add) ((hash) << 3) ^ (hash) ^ (unsigned int)(add)
414 ** Append the hash of the 64-bit integer passed as the second argument to the
415 ** hash-key value passed as the first. Return the new hash-key value.
417 static unsigned int sessionHashAppendI64(unsigned int h, i64 i){
418 h = HASH_APPEND(h, i & 0xFFFFFFFF);
419 return HASH_APPEND(h, (i>>32)&0xFFFFFFFF);
423 ** Append the hash of the blob passed via the second and third arguments to
424 ** the hash-key value passed as the first. Return the new hash-key value.
426 static unsigned int sessionHashAppendBlob(unsigned int h, int n, const u8 *z){
427 int i;
428 for(i=0; i<n; i++) h = HASH_APPEND(h, z[i]);
429 return h;
433 ** Append the hash of the data type passed as the second argument to the
434 ** hash-key value passed as the first. Return the new hash-key value.
436 static unsigned int sessionHashAppendType(unsigned int h, int eType){
437 return HASH_APPEND(h, eType);
441 ** This function may only be called from within a pre-update callback.
442 ** It calculates a hash based on the primary key values of the old.* or
443 ** new.* row currently available and, assuming no error occurs, writes it to
444 ** *piHash before returning. If the primary key contains one or more NULL
445 ** values, *pbNullPK is set to true before returning.
447 ** If an error occurs, an SQLite error code is returned and the final values
448 ** of *piHash asn *pbNullPK are undefined. Otherwise, SQLITE_OK is returned
449 ** and the output variables are set as described above.
451 static int sessionPreupdateHash(
452 sqlite3_session *pSession, /* Session object that owns pTab */
453 SessionTable *pTab, /* Session table handle */
454 int bNew, /* True to hash the new.* PK */
455 int *piHash, /* OUT: Hash value */
456 int *pbNullPK /* OUT: True if there are NULL values in PK */
458 unsigned int h = 0; /* Hash value to return */
459 int i; /* Used to iterate through columns */
461 assert( *pbNullPK==0 );
462 assert( pTab->nCol==pSession->hook.xCount(pSession->hook.pCtx) );
463 for(i=0; i<pTab->nCol; i++){
464 if( pTab->abPK[i] ){
465 int rc;
466 int eType;
467 sqlite3_value *pVal;
469 if( bNew ){
470 rc = pSession->hook.xNew(pSession->hook.pCtx, i, &pVal);
471 }else{
472 rc = pSession->hook.xOld(pSession->hook.pCtx, i, &pVal);
474 if( rc!=SQLITE_OK ) return rc;
476 eType = sqlite3_value_type(pVal);
477 h = sessionHashAppendType(h, eType);
478 if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
479 i64 iVal;
480 if( eType==SQLITE_INTEGER ){
481 iVal = sqlite3_value_int64(pVal);
482 }else{
483 double rVal = sqlite3_value_double(pVal);
484 assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
485 memcpy(&iVal, &rVal, 8);
487 h = sessionHashAppendI64(h, iVal);
488 }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
489 const u8 *z;
490 int n;
491 if( eType==SQLITE_TEXT ){
492 z = (const u8 *)sqlite3_value_text(pVal);
493 }else{
494 z = (const u8 *)sqlite3_value_blob(pVal);
496 n = sqlite3_value_bytes(pVal);
497 if( !z && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
498 h = sessionHashAppendBlob(h, n, z);
499 }else{
500 assert( eType==SQLITE_NULL );
501 assert( pTab->bStat1==0 || i!=1 );
502 *pbNullPK = 1;
507 *piHash = (h % pTab->nChange);
508 return SQLITE_OK;
512 ** The buffer that the argument points to contains a serialized SQL value.
513 ** Return the number of bytes of space occupied by the value (including
514 ** the type byte).
516 static int sessionSerialLen(u8 *a){
517 int e = *a;
518 int n;
519 if( e==0 ) return 1;
520 if( e==SQLITE_NULL ) return 1;
521 if( e==SQLITE_INTEGER || e==SQLITE_FLOAT ) return 9;
522 return sessionVarintGet(&a[1], &n) + 1 + n;
526 ** Based on the primary key values stored in change aRecord, calculate a
527 ** hash key. Assume the has table has nBucket buckets. The hash keys
528 ** calculated by this function are compatible with those calculated by
529 ** sessionPreupdateHash().
531 ** The bPkOnly argument is non-zero if the record at aRecord[] is from
532 ** a patchset DELETE. In this case the non-PK fields are omitted entirely.
534 static unsigned int sessionChangeHash(
535 SessionTable *pTab, /* Table handle */
536 int bPkOnly, /* Record consists of PK fields only */
537 u8 *aRecord, /* Change record */
538 int nBucket /* Assume this many buckets in hash table */
540 unsigned int h = 0; /* Value to return */
541 int i; /* Used to iterate through columns */
542 u8 *a = aRecord; /* Used to iterate through change record */
544 for(i=0; i<pTab->nCol; i++){
545 int eType = *a;
546 int isPK = pTab->abPK[i];
547 if( bPkOnly && isPK==0 ) continue;
549 /* It is not possible for eType to be SQLITE_NULL here. The session
550 ** module does not record changes for rows with NULL values stored in
551 ** primary key columns. */
552 assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
553 || eType==SQLITE_TEXT || eType==SQLITE_BLOB
554 || eType==SQLITE_NULL || eType==0
556 assert( !isPK || (eType!=0 && eType!=SQLITE_NULL) );
558 if( isPK ){
559 a++;
560 h = sessionHashAppendType(h, eType);
561 if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
562 h = sessionHashAppendI64(h, sessionGetI64(a));
563 a += 8;
564 }else{
565 int n;
566 a += sessionVarintGet(a, &n);
567 h = sessionHashAppendBlob(h, n, a);
568 a += n;
570 }else{
571 a += sessionSerialLen(a);
574 return (h % nBucket);
578 ** Arguments aLeft and aRight are pointers to change records for table pTab.
579 ** This function returns true if the two records apply to the same row (i.e.
580 ** have the same values stored in the primary key columns), or false
581 ** otherwise.
583 static int sessionChangeEqual(
584 SessionTable *pTab, /* Table used for PK definition */
585 int bLeftPkOnly, /* True if aLeft[] contains PK fields only */
586 u8 *aLeft, /* Change record */
587 int bRightPkOnly, /* True if aRight[] contains PK fields only */
588 u8 *aRight /* Change record */
590 u8 *a1 = aLeft; /* Cursor to iterate through aLeft */
591 u8 *a2 = aRight; /* Cursor to iterate through aRight */
592 int iCol; /* Used to iterate through table columns */
594 for(iCol=0; iCol<pTab->nCol; iCol++){
595 if( pTab->abPK[iCol] ){
596 int n1 = sessionSerialLen(a1);
597 int n2 = sessionSerialLen(a2);
599 if( pTab->abPK[iCol] && (n1!=n2 || memcmp(a1, a2, n1)) ){
600 return 0;
602 a1 += n1;
603 a2 += n2;
604 }else{
605 if( bLeftPkOnly==0 ) a1 += sessionSerialLen(a1);
606 if( bRightPkOnly==0 ) a2 += sessionSerialLen(a2);
610 return 1;
614 ** Arguments aLeft and aRight both point to buffers containing change
615 ** records with nCol columns. This function "merges" the two records into
616 ** a single records which is written to the buffer at *paOut. *paOut is
617 ** then set to point to one byte after the last byte written before
618 ** returning.
620 ** The merging of records is done as follows: For each column, if the
621 ** aRight record contains a value for the column, copy the value from
622 ** their. Otherwise, if aLeft contains a value, copy it. If neither
623 ** record contains a value for a given column, then neither does the
624 ** output record.
626 static void sessionMergeRecord(
627 u8 **paOut,
628 int nCol,
629 u8 *aLeft,
630 u8 *aRight
632 u8 *a1 = aLeft; /* Cursor used to iterate through aLeft */
633 u8 *a2 = aRight; /* Cursor used to iterate through aRight */
634 u8 *aOut = *paOut; /* Output cursor */
635 int iCol; /* Used to iterate from 0 to nCol */
637 for(iCol=0; iCol<nCol; iCol++){
638 int n1 = sessionSerialLen(a1);
639 int n2 = sessionSerialLen(a2);
640 if( *a2 ){
641 memcpy(aOut, a2, n2);
642 aOut += n2;
643 }else{
644 memcpy(aOut, a1, n1);
645 aOut += n1;
647 a1 += n1;
648 a2 += n2;
651 *paOut = aOut;
655 ** This is a helper function used by sessionMergeUpdate().
657 ** When this function is called, both *paOne and *paTwo point to a value
658 ** within a change record. Before it returns, both have been advanced so
659 ** as to point to the next value in the record.
661 ** If, when this function is called, *paTwo points to a valid value (i.e.
662 ** *paTwo[0] is not 0x00 - the "no value" placeholder), a copy of the *paTwo
663 ** pointer is returned and *pnVal is set to the number of bytes in the
664 ** serialized value. Otherwise, a copy of *paOne is returned and *pnVal
665 ** set to the number of bytes in the value at *paOne. If *paOne points
666 ** to the "no value" placeholder, *pnVal is set to 1. In other words:
668 ** if( *paTwo is valid ) return *paTwo;
669 ** return *paOne;
672 static u8 *sessionMergeValue(
673 u8 **paOne, /* IN/OUT: Left-hand buffer pointer */
674 u8 **paTwo, /* IN/OUT: Right-hand buffer pointer */
675 int *pnVal /* OUT: Bytes in returned value */
677 u8 *a1 = *paOne;
678 u8 *a2 = *paTwo;
679 u8 *pRet = 0;
680 int n1;
682 assert( a1 );
683 if( a2 ){
684 int n2 = sessionSerialLen(a2);
685 if( *a2 ){
686 *pnVal = n2;
687 pRet = a2;
689 *paTwo = &a2[n2];
692 n1 = sessionSerialLen(a1);
693 if( pRet==0 ){
694 *pnVal = n1;
695 pRet = a1;
697 *paOne = &a1[n1];
699 return pRet;
703 ** This function is used by changeset_concat() to merge two UPDATE changes
704 ** on the same row.
706 static int sessionMergeUpdate(
707 u8 **paOut, /* IN/OUT: Pointer to output buffer */
708 SessionTable *pTab, /* Table change pertains to */
709 int bPatchset, /* True if records are patchset records */
710 u8 *aOldRecord1, /* old.* record for first change */
711 u8 *aOldRecord2, /* old.* record for second change */
712 u8 *aNewRecord1, /* new.* record for first change */
713 u8 *aNewRecord2 /* new.* record for second change */
715 u8 *aOld1 = aOldRecord1;
716 u8 *aOld2 = aOldRecord2;
717 u8 *aNew1 = aNewRecord1;
718 u8 *aNew2 = aNewRecord2;
720 u8 *aOut = *paOut;
721 int i;
723 if( bPatchset==0 ){
724 int bRequired = 0;
726 assert( aOldRecord1 && aNewRecord1 );
728 /* Write the old.* vector first. */
729 for(i=0; i<pTab->nCol; i++){
730 int nOld;
731 u8 *aOld;
732 int nNew;
733 u8 *aNew;
735 aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
736 aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
737 if( pTab->abPK[i] || nOld!=nNew || memcmp(aOld, aNew, nNew) ){
738 if( pTab->abPK[i]==0 ) bRequired = 1;
739 memcpy(aOut, aOld, nOld);
740 aOut += nOld;
741 }else{
742 *(aOut++) = '\0';
746 if( !bRequired ) return 0;
749 /* Write the new.* vector */
750 aOld1 = aOldRecord1;
751 aOld2 = aOldRecord2;
752 aNew1 = aNewRecord1;
753 aNew2 = aNewRecord2;
754 for(i=0; i<pTab->nCol; i++){
755 int nOld;
756 u8 *aOld;
757 int nNew;
758 u8 *aNew;
760 aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
761 aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
762 if( bPatchset==0
763 && (pTab->abPK[i] || (nOld==nNew && 0==memcmp(aOld, aNew, nNew)))
765 *(aOut++) = '\0';
766 }else{
767 memcpy(aOut, aNew, nNew);
768 aOut += nNew;
772 *paOut = aOut;
773 return 1;
777 ** This function is only called from within a pre-update-hook callback.
778 ** It determines if the current pre-update-hook change affects the same row
779 ** as the change stored in argument pChange. If so, it returns true. Otherwise
780 ** if the pre-update-hook does not affect the same row as pChange, it returns
781 ** false.
783 static int sessionPreupdateEqual(
784 sqlite3_session *pSession, /* Session object that owns SessionTable */
785 SessionTable *pTab, /* Table associated with change */
786 SessionChange *pChange, /* Change to compare to */
787 int op /* Current pre-update operation */
789 int iCol; /* Used to iterate through columns */
790 u8 *a = pChange->aRecord; /* Cursor used to scan change record */
792 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
793 for(iCol=0; iCol<pTab->nCol; iCol++){
794 if( !pTab->abPK[iCol] ){
795 a += sessionSerialLen(a);
796 }else{
797 sqlite3_value *pVal; /* Value returned by preupdate_new/old */
798 int rc; /* Error code from preupdate_new/old */
799 int eType = *a++; /* Type of value from change record */
801 /* The following calls to preupdate_new() and preupdate_old() can not
802 ** fail. This is because they cache their return values, and by the
803 ** time control flows to here they have already been called once from
804 ** within sessionPreupdateHash(). The first two asserts below verify
805 ** this (that the method has already been called). */
806 if( op==SQLITE_INSERT ){
807 /* assert( db->pPreUpdate->pNewUnpacked || db->pPreUpdate->aNew ); */
808 rc = pSession->hook.xNew(pSession->hook.pCtx, iCol, &pVal);
809 }else{
810 /* assert( db->pPreUpdate->pUnpacked ); */
811 rc = pSession->hook.xOld(pSession->hook.pCtx, iCol, &pVal);
813 assert( rc==SQLITE_OK );
814 if( sqlite3_value_type(pVal)!=eType ) return 0;
816 /* A SessionChange object never has a NULL value in a PK column */
817 assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
818 || eType==SQLITE_BLOB || eType==SQLITE_TEXT
821 if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
822 i64 iVal = sessionGetI64(a);
823 a += 8;
824 if( eType==SQLITE_INTEGER ){
825 if( sqlite3_value_int64(pVal)!=iVal ) return 0;
826 }else{
827 double rVal;
828 assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
829 memcpy(&rVal, &iVal, 8);
830 if( sqlite3_value_double(pVal)!=rVal ) return 0;
832 }else{
833 int n;
834 const u8 *z;
835 a += sessionVarintGet(a, &n);
836 if( sqlite3_value_bytes(pVal)!=n ) return 0;
837 if( eType==SQLITE_TEXT ){
838 z = sqlite3_value_text(pVal);
839 }else{
840 z = sqlite3_value_blob(pVal);
842 if( memcmp(a, z, n) ) return 0;
843 a += n;
848 return 1;
852 ** If required, grow the hash table used to store changes on table pTab
853 ** (part of the session pSession). If a fatal OOM error occurs, set the
854 ** session object to failed and return SQLITE_ERROR. Otherwise, return
855 ** SQLITE_OK.
857 ** It is possible that a non-fatal OOM error occurs in this function. In
858 ** that case the hash-table does not grow, but SQLITE_OK is returned anyway.
859 ** Growing the hash table in this case is a performance optimization only,
860 ** it is not required for correct operation.
862 static int sessionGrowHash(int bPatchset, SessionTable *pTab){
863 if( pTab->nChange==0 || pTab->nEntry>=(pTab->nChange/2) ){
864 int i;
865 SessionChange **apNew;
866 int nNew = (pTab->nChange ? pTab->nChange : 128) * 2;
868 apNew = (SessionChange **)sqlite3_malloc(sizeof(SessionChange *) * nNew);
869 if( apNew==0 ){
870 if( pTab->nChange==0 ){
871 return SQLITE_ERROR;
873 return SQLITE_OK;
875 memset(apNew, 0, sizeof(SessionChange *) * nNew);
877 for(i=0; i<pTab->nChange; i++){
878 SessionChange *p;
879 SessionChange *pNext;
880 for(p=pTab->apChange[i]; p; p=pNext){
881 int bPkOnly = (p->op==SQLITE_DELETE && bPatchset);
882 int iHash = sessionChangeHash(pTab, bPkOnly, p->aRecord, nNew);
883 pNext = p->pNext;
884 p->pNext = apNew[iHash];
885 apNew[iHash] = p;
889 sqlite3_free(pTab->apChange);
890 pTab->nChange = nNew;
891 pTab->apChange = apNew;
894 return SQLITE_OK;
898 ** This function queries the database for the names of the columns of table
899 ** zThis, in schema zDb.
901 ** Otherwise, if they are not NULL, variable *pnCol is set to the number
902 ** of columns in the database table and variable *pzTab is set to point to a
903 ** nul-terminated copy of the table name. *pazCol (if not NULL) is set to
904 ** point to an array of pointers to column names. And *pabPK (again, if not
905 ** NULL) is set to point to an array of booleans - true if the corresponding
906 ** column is part of the primary key.
908 ** For example, if the table is declared as:
910 ** CREATE TABLE tbl1(w, x, y, z, PRIMARY KEY(w, z));
912 ** Then the four output variables are populated as follows:
914 ** *pnCol = 4
915 ** *pzTab = "tbl1"
916 ** *pazCol = {"w", "x", "y", "z"}
917 ** *pabPK = {1, 0, 0, 1}
919 ** All returned buffers are part of the same single allocation, which must
920 ** be freed using sqlite3_free() by the caller
922 static int sessionTableInfo(
923 sqlite3 *db, /* Database connection */
924 const char *zDb, /* Name of attached database (e.g. "main") */
925 const char *zThis, /* Table name */
926 int *pnCol, /* OUT: number of columns */
927 const char **pzTab, /* OUT: Copy of zThis */
928 const char ***pazCol, /* OUT: Array of column names for table */
929 u8 **pabPK /* OUT: Array of booleans - true for PK col */
931 char *zPragma;
932 sqlite3_stmt *pStmt;
933 int rc;
934 int nByte;
935 int nDbCol = 0;
936 int nThis;
937 int i;
938 u8 *pAlloc = 0;
939 char **azCol = 0;
940 u8 *abPK = 0;
942 assert( pazCol && pabPK );
944 nThis = sqlite3Strlen30(zThis);
945 if( nThis==12 && 0==sqlite3_stricmp("sqlite_stat1", zThis) ){
946 rc = sqlite3_table_column_metadata(db, zDb, zThis, 0, 0, 0, 0, 0, 0);
947 if( rc==SQLITE_OK ){
948 /* For sqlite_stat1, pretend that (tbl,idx) is the PRIMARY KEY. */
949 zPragma = sqlite3_mprintf(
950 "SELECT 0, 'tbl', '', 0, '', 1 UNION ALL "
951 "SELECT 1, 'idx', '', 0, '', 2 UNION ALL "
952 "SELECT 2, 'stat', '', 0, '', 0"
954 }else if( rc==SQLITE_ERROR ){
955 zPragma = sqlite3_mprintf("");
956 }else{
957 return rc;
959 }else{
960 zPragma = sqlite3_mprintf("PRAGMA '%q'.table_info('%q')", zDb, zThis);
962 if( !zPragma ) return SQLITE_NOMEM;
964 rc = sqlite3_prepare_v2(db, zPragma, -1, &pStmt, 0);
965 sqlite3_free(zPragma);
966 if( rc!=SQLITE_OK ) return rc;
968 nByte = nThis + 1;
969 while( SQLITE_ROW==sqlite3_step(pStmt) ){
970 nByte += sqlite3_column_bytes(pStmt, 1);
971 nDbCol++;
973 rc = sqlite3_reset(pStmt);
975 if( rc==SQLITE_OK ){
976 nByte += nDbCol * (sizeof(const char *) + sizeof(u8) + 1);
977 pAlloc = sqlite3_malloc(nByte);
978 if( pAlloc==0 ){
979 rc = SQLITE_NOMEM;
982 if( rc==SQLITE_OK ){
983 azCol = (char **)pAlloc;
984 pAlloc = (u8 *)&azCol[nDbCol];
985 abPK = (u8 *)pAlloc;
986 pAlloc = &abPK[nDbCol];
987 if( pzTab ){
988 memcpy(pAlloc, zThis, nThis+1);
989 *pzTab = (char *)pAlloc;
990 pAlloc += nThis+1;
993 i = 0;
994 while( SQLITE_ROW==sqlite3_step(pStmt) ){
995 int nName = sqlite3_column_bytes(pStmt, 1);
996 const unsigned char *zName = sqlite3_column_text(pStmt, 1);
997 if( zName==0 ) break;
998 memcpy(pAlloc, zName, nName+1);
999 azCol[i] = (char *)pAlloc;
1000 pAlloc += nName+1;
1001 abPK[i] = sqlite3_column_int(pStmt, 5);
1002 i++;
1004 rc = sqlite3_reset(pStmt);
1008 /* If successful, populate the output variables. Otherwise, zero them and
1009 ** free any allocation made. An error code will be returned in this case.
1011 if( rc==SQLITE_OK ){
1012 *pazCol = (const char **)azCol;
1013 *pabPK = abPK;
1014 *pnCol = nDbCol;
1015 }else{
1016 *pazCol = 0;
1017 *pabPK = 0;
1018 *pnCol = 0;
1019 if( pzTab ) *pzTab = 0;
1020 sqlite3_free(azCol);
1022 sqlite3_finalize(pStmt);
1023 return rc;
1027 ** This function is only called from within a pre-update handler for a
1028 ** write to table pTab, part of session pSession. If this is the first
1029 ** write to this table, initalize the SessionTable.nCol, azCol[] and
1030 ** abPK[] arrays accordingly.
1032 ** If an error occurs, an error code is stored in sqlite3_session.rc and
1033 ** non-zero returned. Or, if no error occurs but the table has no primary
1034 ** key, sqlite3_session.rc is left set to SQLITE_OK and non-zero returned to
1035 ** indicate that updates on this table should be ignored. SessionTable.abPK
1036 ** is set to NULL in this case.
1038 static int sessionInitTable(sqlite3_session *pSession, SessionTable *pTab){
1039 if( pTab->nCol==0 ){
1040 u8 *abPK;
1041 assert( pTab->azCol==0 || pTab->abPK==0 );
1042 pSession->rc = sessionTableInfo(pSession->db, pSession->zDb,
1043 pTab->zName, &pTab->nCol, 0, &pTab->azCol, &abPK
1045 if( pSession->rc==SQLITE_OK ){
1046 int i;
1047 for(i=0; i<pTab->nCol; i++){
1048 if( abPK[i] ){
1049 pTab->abPK = abPK;
1050 break;
1053 if( 0==sqlite3_stricmp("sqlite_stat1", pTab->zName) ){
1054 pTab->bStat1 = 1;
1058 return (pSession->rc || pTab->abPK==0);
1062 ** Versions of the four methods in object SessionHook for use with the
1063 ** sqlite_stat1 table. The purpose of this is to substitute a zero-length
1064 ** blob each time a NULL value is read from the "idx" column of the
1065 ** sqlite_stat1 table.
1067 typedef struct SessionStat1Ctx SessionStat1Ctx;
1068 struct SessionStat1Ctx {
1069 SessionHook hook;
1070 sqlite3_session *pSession;
1072 static int sessionStat1Old(void *pCtx, int iCol, sqlite3_value **ppVal){
1073 SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
1074 sqlite3_value *pVal = 0;
1075 int rc = p->hook.xOld(p->hook.pCtx, iCol, &pVal);
1076 if( rc==SQLITE_OK && iCol==1 && sqlite3_value_type(pVal)==SQLITE_NULL ){
1077 pVal = p->pSession->pZeroBlob;
1079 *ppVal = pVal;
1080 return rc;
1082 static int sessionStat1New(void *pCtx, int iCol, sqlite3_value **ppVal){
1083 SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
1084 sqlite3_value *pVal = 0;
1085 int rc = p->hook.xNew(p->hook.pCtx, iCol, &pVal);
1086 if( rc==SQLITE_OK && iCol==1 && sqlite3_value_type(pVal)==SQLITE_NULL ){
1087 pVal = p->pSession->pZeroBlob;
1089 *ppVal = pVal;
1090 return rc;
1092 static int sessionStat1Count(void *pCtx){
1093 SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
1094 return p->hook.xCount(p->hook.pCtx);
1096 static int sessionStat1Depth(void *pCtx){
1097 SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
1098 return p->hook.xDepth(p->hook.pCtx);
1103 ** This function is only called from with a pre-update-hook reporting a
1104 ** change on table pTab (attached to session pSession). The type of change
1105 ** (UPDATE, INSERT, DELETE) is specified by the first argument.
1107 ** Unless one is already present or an error occurs, an entry is added
1108 ** to the changed-rows hash table associated with table pTab.
1110 static void sessionPreupdateOneChange(
1111 int op, /* One of SQLITE_UPDATE, INSERT, DELETE */
1112 sqlite3_session *pSession, /* Session object pTab is attached to */
1113 SessionTable *pTab /* Table that change applies to */
1115 int iHash;
1116 int bNull = 0;
1117 int rc = SQLITE_OK;
1118 SessionStat1Ctx stat1 = {0};
1120 if( pSession->rc ) return;
1122 /* Load table details if required */
1123 if( sessionInitTable(pSession, pTab) ) return;
1125 /* Check the number of columns in this xPreUpdate call matches the
1126 ** number of columns in the table. */
1127 if( pTab->nCol!=pSession->hook.xCount(pSession->hook.pCtx) ){
1128 pSession->rc = SQLITE_SCHEMA;
1129 return;
1132 /* Grow the hash table if required */
1133 if( sessionGrowHash(0, pTab) ){
1134 pSession->rc = SQLITE_NOMEM;
1135 return;
1138 if( pTab->bStat1 ){
1139 stat1.hook = pSession->hook;
1140 stat1.pSession = pSession;
1141 pSession->hook.pCtx = (void*)&stat1;
1142 pSession->hook.xNew = sessionStat1New;
1143 pSession->hook.xOld = sessionStat1Old;
1144 pSession->hook.xCount = sessionStat1Count;
1145 pSession->hook.xDepth = sessionStat1Depth;
1146 if( pSession->pZeroBlob==0 ){
1147 sqlite3_value *p = sqlite3ValueNew(0);
1148 if( p==0 ){
1149 rc = SQLITE_NOMEM;
1150 goto error_out;
1152 sqlite3ValueSetStr(p, 0, "", 0, SQLITE_STATIC);
1153 pSession->pZeroBlob = p;
1157 /* Calculate the hash-key for this change. If the primary key of the row
1158 ** includes a NULL value, exit early. Such changes are ignored by the
1159 ** session module. */
1160 rc = sessionPreupdateHash(pSession, pTab, op==SQLITE_INSERT, &iHash, &bNull);
1161 if( rc!=SQLITE_OK ) goto error_out;
1163 if( bNull==0 ){
1164 /* Search the hash table for an existing record for this row. */
1165 SessionChange *pC;
1166 for(pC=pTab->apChange[iHash]; pC; pC=pC->pNext){
1167 if( sessionPreupdateEqual(pSession, pTab, pC, op) ) break;
1170 if( pC==0 ){
1171 /* Create a new change object containing all the old values (if
1172 ** this is an SQLITE_UPDATE or SQLITE_DELETE), or just the PK
1173 ** values (if this is an INSERT). */
1174 SessionChange *pChange; /* New change object */
1175 int nByte; /* Number of bytes to allocate */
1176 int i; /* Used to iterate through columns */
1178 assert( rc==SQLITE_OK );
1179 pTab->nEntry++;
1181 /* Figure out how large an allocation is required */
1182 nByte = sizeof(SessionChange);
1183 for(i=0; i<pTab->nCol; i++){
1184 sqlite3_value *p = 0;
1185 if( op!=SQLITE_INSERT ){
1186 TESTONLY(int trc = ) pSession->hook.xOld(pSession->hook.pCtx, i, &p);
1187 assert( trc==SQLITE_OK );
1188 }else if( pTab->abPK[i] ){
1189 TESTONLY(int trc = ) pSession->hook.xNew(pSession->hook.pCtx, i, &p);
1190 assert( trc==SQLITE_OK );
1193 /* This may fail if SQLite value p contains a utf-16 string that must
1194 ** be converted to utf-8 and an OOM error occurs while doing so. */
1195 rc = sessionSerializeValue(0, p, &nByte);
1196 if( rc!=SQLITE_OK ) goto error_out;
1199 /* Allocate the change object */
1200 pChange = (SessionChange *)sqlite3_malloc(nByte);
1201 if( !pChange ){
1202 rc = SQLITE_NOMEM;
1203 goto error_out;
1204 }else{
1205 memset(pChange, 0, sizeof(SessionChange));
1206 pChange->aRecord = (u8 *)&pChange[1];
1209 /* Populate the change object. None of the preupdate_old(),
1210 ** preupdate_new() or SerializeValue() calls below may fail as all
1211 ** required values and encodings have already been cached in memory.
1212 ** It is not possible for an OOM to occur in this block. */
1213 nByte = 0;
1214 for(i=0; i<pTab->nCol; i++){
1215 sqlite3_value *p = 0;
1216 if( op!=SQLITE_INSERT ){
1217 pSession->hook.xOld(pSession->hook.pCtx, i, &p);
1218 }else if( pTab->abPK[i] ){
1219 pSession->hook.xNew(pSession->hook.pCtx, i, &p);
1221 sessionSerializeValue(&pChange->aRecord[nByte], p, &nByte);
1224 /* Add the change to the hash-table */
1225 if( pSession->bIndirect || pSession->hook.xDepth(pSession->hook.pCtx) ){
1226 pChange->bIndirect = 1;
1228 pChange->nRecord = nByte;
1229 pChange->op = op;
1230 pChange->pNext = pTab->apChange[iHash];
1231 pTab->apChange[iHash] = pChange;
1233 }else if( pC->bIndirect ){
1234 /* If the existing change is considered "indirect", but this current
1235 ** change is "direct", mark the change object as direct. */
1236 if( pSession->hook.xDepth(pSession->hook.pCtx)==0
1237 && pSession->bIndirect==0
1239 pC->bIndirect = 0;
1244 /* If an error has occurred, mark the session object as failed. */
1245 error_out:
1246 if( pTab->bStat1 ){
1247 pSession->hook = stat1.hook;
1249 if( rc!=SQLITE_OK ){
1250 pSession->rc = rc;
1254 static int sessionFindTable(
1255 sqlite3_session *pSession,
1256 const char *zName,
1257 SessionTable **ppTab
1259 int rc = SQLITE_OK;
1260 int nName = sqlite3Strlen30(zName);
1261 SessionTable *pRet;
1263 /* Search for an existing table */
1264 for(pRet=pSession->pTable; pRet; pRet=pRet->pNext){
1265 if( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) ) break;
1268 if( pRet==0 && pSession->bAutoAttach ){
1269 /* If there is a table-filter configured, invoke it. If it returns 0,
1270 ** do not automatically add the new table. */
1271 if( pSession->xTableFilter==0
1272 || pSession->xTableFilter(pSession->pFilterCtx, zName)
1274 rc = sqlite3session_attach(pSession, zName);
1275 if( rc==SQLITE_OK ){
1276 for(pRet=pSession->pTable; pRet->pNext; pRet=pRet->pNext);
1277 assert( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) );
1282 assert( rc==SQLITE_OK || pRet==0 );
1283 *ppTab = pRet;
1284 return rc;
1288 ** The 'pre-update' hook registered by this module with SQLite databases.
1290 static void xPreUpdate(
1291 void *pCtx, /* Copy of third arg to preupdate_hook() */
1292 sqlite3 *db, /* Database handle */
1293 int op, /* SQLITE_UPDATE, DELETE or INSERT */
1294 char const *zDb, /* Database name */
1295 char const *zName, /* Table name */
1296 sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */
1297 sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */
1299 sqlite3_session *pSession;
1300 int nDb = sqlite3Strlen30(zDb);
1302 assert( sqlite3_mutex_held(db->mutex) );
1304 for(pSession=(sqlite3_session *)pCtx; pSession; pSession=pSession->pNext){
1305 SessionTable *pTab;
1307 /* If this session is attached to a different database ("main", "temp"
1308 ** etc.), or if it is not currently enabled, there is nothing to do. Skip
1309 ** to the next session object attached to this database. */
1310 if( pSession->bEnable==0 ) continue;
1311 if( pSession->rc ) continue;
1312 if( sqlite3_strnicmp(zDb, pSession->zDb, nDb+1) ) continue;
1314 pSession->rc = sessionFindTable(pSession, zName, &pTab);
1315 if( pTab ){
1316 assert( pSession->rc==SQLITE_OK );
1317 sessionPreupdateOneChange(op, pSession, pTab);
1318 if( op==SQLITE_UPDATE ){
1319 sessionPreupdateOneChange(SQLITE_INSERT, pSession, pTab);
1326 ** The pre-update hook implementations.
1328 static int sessionPreupdateOld(void *pCtx, int iVal, sqlite3_value **ppVal){
1329 return sqlite3_preupdate_old((sqlite3*)pCtx, iVal, ppVal);
1331 static int sessionPreupdateNew(void *pCtx, int iVal, sqlite3_value **ppVal){
1332 return sqlite3_preupdate_new((sqlite3*)pCtx, iVal, ppVal);
1334 static int sessionPreupdateCount(void *pCtx){
1335 return sqlite3_preupdate_count((sqlite3*)pCtx);
1337 static int sessionPreupdateDepth(void *pCtx){
1338 return sqlite3_preupdate_depth((sqlite3*)pCtx);
1342 ** Install the pre-update hooks on the session object passed as the only
1343 ** argument.
1345 static void sessionPreupdateHooks(
1346 sqlite3_session *pSession
1348 pSession->hook.pCtx = (void*)pSession->db;
1349 pSession->hook.xOld = sessionPreupdateOld;
1350 pSession->hook.xNew = sessionPreupdateNew;
1351 pSession->hook.xCount = sessionPreupdateCount;
1352 pSession->hook.xDepth = sessionPreupdateDepth;
1355 typedef struct SessionDiffCtx SessionDiffCtx;
1356 struct SessionDiffCtx {
1357 sqlite3_stmt *pStmt;
1358 int nOldOff;
1362 ** The diff hook implementations.
1364 static int sessionDiffOld(void *pCtx, int iVal, sqlite3_value **ppVal){
1365 SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
1366 *ppVal = sqlite3_column_value(p->pStmt, iVal+p->nOldOff);
1367 return SQLITE_OK;
1369 static int sessionDiffNew(void *pCtx, int iVal, sqlite3_value **ppVal){
1370 SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
1371 *ppVal = sqlite3_column_value(p->pStmt, iVal);
1372 return SQLITE_OK;
1374 static int sessionDiffCount(void *pCtx){
1375 SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
1376 return p->nOldOff ? p->nOldOff : sqlite3_column_count(p->pStmt);
1378 static int sessionDiffDepth(void *pCtx){
1379 return 0;
1383 ** Install the diff hooks on the session object passed as the only
1384 ** argument.
1386 static void sessionDiffHooks(
1387 sqlite3_session *pSession,
1388 SessionDiffCtx *pDiffCtx
1390 pSession->hook.pCtx = (void*)pDiffCtx;
1391 pSession->hook.xOld = sessionDiffOld;
1392 pSession->hook.xNew = sessionDiffNew;
1393 pSession->hook.xCount = sessionDiffCount;
1394 pSession->hook.xDepth = sessionDiffDepth;
1397 static char *sessionExprComparePK(
1398 int nCol,
1399 const char *zDb1, const char *zDb2,
1400 const char *zTab,
1401 const char **azCol, u8 *abPK
1403 int i;
1404 const char *zSep = "";
1405 char *zRet = 0;
1407 for(i=0; i<nCol; i++){
1408 if( abPK[i] ){
1409 zRet = sqlite3_mprintf("%z%s\"%w\".\"%w\".\"%w\"=\"%w\".\"%w\".\"%w\"",
1410 zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
1412 zSep = " AND ";
1413 if( zRet==0 ) break;
1417 return zRet;
1420 static char *sessionExprCompareOther(
1421 int nCol,
1422 const char *zDb1, const char *zDb2,
1423 const char *zTab,
1424 const char **azCol, u8 *abPK
1426 int i;
1427 const char *zSep = "";
1428 char *zRet = 0;
1429 int bHave = 0;
1431 for(i=0; i<nCol; i++){
1432 if( abPK[i]==0 ){
1433 bHave = 1;
1434 zRet = sqlite3_mprintf(
1435 "%z%s\"%w\".\"%w\".\"%w\" IS NOT \"%w\".\"%w\".\"%w\"",
1436 zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
1438 zSep = " OR ";
1439 if( zRet==0 ) break;
1443 if( bHave==0 ){
1444 assert( zRet==0 );
1445 zRet = sqlite3_mprintf("0");
1448 return zRet;
1451 static char *sessionSelectFindNew(
1452 int nCol,
1453 const char *zDb1, /* Pick rows in this db only */
1454 const char *zDb2, /* But not in this one */
1455 const char *zTbl, /* Table name */
1456 const char *zExpr
1458 char *zRet = sqlite3_mprintf(
1459 "SELECT * FROM \"%w\".\"%w\" WHERE NOT EXISTS ("
1460 " SELECT 1 FROM \"%w\".\"%w\" WHERE %s"
1461 ")",
1462 zDb1, zTbl, zDb2, zTbl, zExpr
1464 return zRet;
1467 static int sessionDiffFindNew(
1468 int op,
1469 sqlite3_session *pSession,
1470 SessionTable *pTab,
1471 const char *zDb1,
1472 const char *zDb2,
1473 char *zExpr
1475 int rc = SQLITE_OK;
1476 char *zStmt = sessionSelectFindNew(pTab->nCol, zDb1, zDb2, pTab->zName,zExpr);
1478 if( zStmt==0 ){
1479 rc = SQLITE_NOMEM;
1480 }else{
1481 sqlite3_stmt *pStmt;
1482 rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
1483 if( rc==SQLITE_OK ){
1484 SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
1485 pDiffCtx->pStmt = pStmt;
1486 pDiffCtx->nOldOff = 0;
1487 while( SQLITE_ROW==sqlite3_step(pStmt) ){
1488 sessionPreupdateOneChange(op, pSession, pTab);
1490 rc = sqlite3_finalize(pStmt);
1492 sqlite3_free(zStmt);
1495 return rc;
1498 static int sessionDiffFindModified(
1499 sqlite3_session *pSession,
1500 SessionTable *pTab,
1501 const char *zFrom,
1502 const char *zExpr
1504 int rc = SQLITE_OK;
1506 char *zExpr2 = sessionExprCompareOther(pTab->nCol,
1507 pSession->zDb, zFrom, pTab->zName, pTab->azCol, pTab->abPK
1509 if( zExpr2==0 ){
1510 rc = SQLITE_NOMEM;
1511 }else{
1512 char *zStmt = sqlite3_mprintf(
1513 "SELECT * FROM \"%w\".\"%w\", \"%w\".\"%w\" WHERE %s AND (%z)",
1514 pSession->zDb, pTab->zName, zFrom, pTab->zName, zExpr, zExpr2
1516 if( zStmt==0 ){
1517 rc = SQLITE_NOMEM;
1518 }else{
1519 sqlite3_stmt *pStmt;
1520 rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
1522 if( rc==SQLITE_OK ){
1523 SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
1524 pDiffCtx->pStmt = pStmt;
1525 pDiffCtx->nOldOff = pTab->nCol;
1526 while( SQLITE_ROW==sqlite3_step(pStmt) ){
1527 sessionPreupdateOneChange(SQLITE_UPDATE, pSession, pTab);
1529 rc = sqlite3_finalize(pStmt);
1531 sqlite3_free(zStmt);
1535 return rc;
1538 int sqlite3session_diff(
1539 sqlite3_session *pSession,
1540 const char *zFrom,
1541 const char *zTbl,
1542 char **pzErrMsg
1544 const char *zDb = pSession->zDb;
1545 int rc = pSession->rc;
1546 SessionDiffCtx d;
1548 memset(&d, 0, sizeof(d));
1549 sessionDiffHooks(pSession, &d);
1551 sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
1552 if( pzErrMsg ) *pzErrMsg = 0;
1553 if( rc==SQLITE_OK ){
1554 char *zExpr = 0;
1555 sqlite3 *db = pSession->db;
1556 SessionTable *pTo; /* Table zTbl */
1558 /* Locate and if necessary initialize the target table object */
1559 rc = sessionFindTable(pSession, zTbl, &pTo);
1560 if( pTo==0 ) goto diff_out;
1561 if( sessionInitTable(pSession, pTo) ){
1562 rc = pSession->rc;
1563 goto diff_out;
1566 /* Check the table schemas match */
1567 if( rc==SQLITE_OK ){
1568 int bHasPk = 0;
1569 int bMismatch = 0;
1570 int nCol; /* Columns in zFrom.zTbl */
1571 u8 *abPK;
1572 const char **azCol = 0;
1573 rc = sessionTableInfo(db, zFrom, zTbl, &nCol, 0, &azCol, &abPK);
1574 if( rc==SQLITE_OK ){
1575 if( pTo->nCol!=nCol ){
1576 bMismatch = 1;
1577 }else{
1578 int i;
1579 for(i=0; i<nCol; i++){
1580 if( pTo->abPK[i]!=abPK[i] ) bMismatch = 1;
1581 if( sqlite3_stricmp(azCol[i], pTo->azCol[i]) ) bMismatch = 1;
1582 if( abPK[i] ) bHasPk = 1;
1586 sqlite3_free((char*)azCol);
1587 if( bMismatch ){
1588 *pzErrMsg = sqlite3_mprintf("table schemas do not match");
1589 rc = SQLITE_SCHEMA;
1591 if( bHasPk==0 ){
1592 /* Ignore tables with no primary keys */
1593 goto diff_out;
1597 if( rc==SQLITE_OK ){
1598 zExpr = sessionExprComparePK(pTo->nCol,
1599 zDb, zFrom, pTo->zName, pTo->azCol, pTo->abPK
1603 /* Find new rows */
1604 if( rc==SQLITE_OK ){
1605 rc = sessionDiffFindNew(SQLITE_INSERT, pSession, pTo, zDb, zFrom, zExpr);
1608 /* Find old rows */
1609 if( rc==SQLITE_OK ){
1610 rc = sessionDiffFindNew(SQLITE_DELETE, pSession, pTo, zFrom, zDb, zExpr);
1613 /* Find modified rows */
1614 if( rc==SQLITE_OK ){
1615 rc = sessionDiffFindModified(pSession, pTo, zFrom, zExpr);
1618 sqlite3_free(zExpr);
1621 diff_out:
1622 sessionPreupdateHooks(pSession);
1623 sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
1624 return rc;
1628 ** Create a session object. This session object will record changes to
1629 ** database zDb attached to connection db.
1631 int sqlite3session_create(
1632 sqlite3 *db, /* Database handle */
1633 const char *zDb, /* Name of db (e.g. "main") */
1634 sqlite3_session **ppSession /* OUT: New session object */
1636 sqlite3_session *pNew; /* Newly allocated session object */
1637 sqlite3_session *pOld; /* Session object already attached to db */
1638 int nDb = sqlite3Strlen30(zDb); /* Length of zDb in bytes */
1640 /* Zero the output value in case an error occurs. */
1641 *ppSession = 0;
1643 /* Allocate and populate the new session object. */
1644 pNew = (sqlite3_session *)sqlite3_malloc(sizeof(sqlite3_session) + nDb + 1);
1645 if( !pNew ) return SQLITE_NOMEM;
1646 memset(pNew, 0, sizeof(sqlite3_session));
1647 pNew->db = db;
1648 pNew->zDb = (char *)&pNew[1];
1649 pNew->bEnable = 1;
1650 memcpy(pNew->zDb, zDb, nDb+1);
1651 sessionPreupdateHooks(pNew);
1653 /* Add the new session object to the linked list of session objects
1654 ** attached to database handle $db. Do this under the cover of the db
1655 ** handle mutex. */
1656 sqlite3_mutex_enter(sqlite3_db_mutex(db));
1657 pOld = (sqlite3_session*)sqlite3_preupdate_hook(db, xPreUpdate, (void*)pNew);
1658 pNew->pNext = pOld;
1659 sqlite3_mutex_leave(sqlite3_db_mutex(db));
1661 *ppSession = pNew;
1662 return SQLITE_OK;
1666 ** Free the list of table objects passed as the first argument. The contents
1667 ** of the changed-rows hash tables are also deleted.
1669 static void sessionDeleteTable(SessionTable *pList){
1670 SessionTable *pNext;
1671 SessionTable *pTab;
1673 for(pTab=pList; pTab; pTab=pNext){
1674 int i;
1675 pNext = pTab->pNext;
1676 for(i=0; i<pTab->nChange; i++){
1677 SessionChange *p;
1678 SessionChange *pNextChange;
1679 for(p=pTab->apChange[i]; p; p=pNextChange){
1680 pNextChange = p->pNext;
1681 sqlite3_free(p);
1684 sqlite3_free((char*)pTab->azCol); /* cast works around VC++ bug */
1685 sqlite3_free(pTab->apChange);
1686 sqlite3_free(pTab);
1691 ** Delete a session object previously allocated using sqlite3session_create().
1693 void sqlite3session_delete(sqlite3_session *pSession){
1694 sqlite3 *db = pSession->db;
1695 sqlite3_session *pHead;
1696 sqlite3_session **pp;
1698 /* Unlink the session from the linked list of sessions attached to the
1699 ** database handle. Hold the db mutex while doing so. */
1700 sqlite3_mutex_enter(sqlite3_db_mutex(db));
1701 pHead = (sqlite3_session*)sqlite3_preupdate_hook(db, 0, 0);
1702 for(pp=&pHead; ALWAYS((*pp)!=0); pp=&((*pp)->pNext)){
1703 if( (*pp)==pSession ){
1704 *pp = (*pp)->pNext;
1705 if( pHead ) sqlite3_preupdate_hook(db, xPreUpdate, (void*)pHead);
1706 break;
1709 sqlite3_mutex_leave(sqlite3_db_mutex(db));
1710 sqlite3ValueFree(pSession->pZeroBlob);
1712 /* Delete all attached table objects. And the contents of their
1713 ** associated hash-tables. */
1714 sessionDeleteTable(pSession->pTable);
1716 /* Free the session object itself. */
1717 sqlite3_free(pSession);
1721 ** Set a table filter on a Session Object.
1723 void sqlite3session_table_filter(
1724 sqlite3_session *pSession,
1725 int(*xFilter)(void*, const char*),
1726 void *pCtx /* First argument passed to xFilter */
1728 pSession->bAutoAttach = 1;
1729 pSession->pFilterCtx = pCtx;
1730 pSession->xTableFilter = xFilter;
1734 ** Attach a table to a session. All subsequent changes made to the table
1735 ** while the session object is enabled will be recorded.
1737 ** Only tables that have a PRIMARY KEY defined may be attached. It does
1738 ** not matter if the PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias)
1739 ** or not.
1741 int sqlite3session_attach(
1742 sqlite3_session *pSession, /* Session object */
1743 const char *zName /* Table name */
1745 int rc = SQLITE_OK;
1746 sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
1748 if( !zName ){
1749 pSession->bAutoAttach = 1;
1750 }else{
1751 SessionTable *pTab; /* New table object (if required) */
1752 int nName; /* Number of bytes in string zName */
1754 /* First search for an existing entry. If one is found, this call is
1755 ** a no-op. Return early. */
1756 nName = sqlite3Strlen30(zName);
1757 for(pTab=pSession->pTable; pTab; pTab=pTab->pNext){
1758 if( 0==sqlite3_strnicmp(pTab->zName, zName, nName+1) ) break;
1761 if( !pTab ){
1762 /* Allocate new SessionTable object. */
1763 pTab = (SessionTable *)sqlite3_malloc(sizeof(SessionTable) + nName + 1);
1764 if( !pTab ){
1765 rc = SQLITE_NOMEM;
1766 }else{
1767 /* Populate the new SessionTable object and link it into the list.
1768 ** The new object must be linked onto the end of the list, not
1769 ** simply added to the start of it in order to ensure that tables
1770 ** appear in the correct order when a changeset or patchset is
1771 ** eventually generated. */
1772 SessionTable **ppTab;
1773 memset(pTab, 0, sizeof(SessionTable));
1774 pTab->zName = (char *)&pTab[1];
1775 memcpy(pTab->zName, zName, nName+1);
1776 for(ppTab=&pSession->pTable; *ppTab; ppTab=&(*ppTab)->pNext);
1777 *ppTab = pTab;
1782 sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
1783 return rc;
1787 ** Ensure that there is room in the buffer to append nByte bytes of data.
1788 ** If not, use sqlite3_realloc() to grow the buffer so that there is.
1790 ** If successful, return zero. Otherwise, if an OOM condition is encountered,
1791 ** set *pRc to SQLITE_NOMEM and return non-zero.
1793 static int sessionBufferGrow(SessionBuffer *p, int nByte, int *pRc){
1794 if( *pRc==SQLITE_OK && p->nAlloc-p->nBuf<nByte ){
1795 u8 *aNew;
1796 int nNew = p->nAlloc ? p->nAlloc : 128;
1797 do {
1798 nNew = nNew*2;
1799 }while( nNew<(p->nBuf+nByte) );
1801 aNew = (u8 *)sqlite3_realloc(p->aBuf, nNew);
1802 if( 0==aNew ){
1803 *pRc = SQLITE_NOMEM;
1804 }else{
1805 p->aBuf = aNew;
1806 p->nAlloc = nNew;
1809 return (*pRc!=SQLITE_OK);
1813 ** Append the value passed as the second argument to the buffer passed
1814 ** as the first.
1816 ** This function is a no-op if *pRc is non-zero when it is called.
1817 ** Otherwise, if an error occurs, *pRc is set to an SQLite error code
1818 ** before returning.
1820 static void sessionAppendValue(SessionBuffer *p, sqlite3_value *pVal, int *pRc){
1821 int rc = *pRc;
1822 if( rc==SQLITE_OK ){
1823 int nByte = 0;
1824 rc = sessionSerializeValue(0, pVal, &nByte);
1825 sessionBufferGrow(p, nByte, &rc);
1826 if( rc==SQLITE_OK ){
1827 rc = sessionSerializeValue(&p->aBuf[p->nBuf], pVal, 0);
1828 p->nBuf += nByte;
1829 }else{
1830 *pRc = rc;
1836 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
1837 ** called. Otherwise, append a single byte to the buffer.
1839 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
1840 ** returning.
1842 static void sessionAppendByte(SessionBuffer *p, u8 v, int *pRc){
1843 if( 0==sessionBufferGrow(p, 1, pRc) ){
1844 p->aBuf[p->nBuf++] = v;
1849 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
1850 ** called. Otherwise, append a single varint to the buffer.
1852 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
1853 ** returning.
1855 static void sessionAppendVarint(SessionBuffer *p, int v, int *pRc){
1856 if( 0==sessionBufferGrow(p, 9, pRc) ){
1857 p->nBuf += sessionVarintPut(&p->aBuf[p->nBuf], v);
1862 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
1863 ** called. Otherwise, append a blob of data to the buffer.
1865 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
1866 ** returning.
1868 static void sessionAppendBlob(
1869 SessionBuffer *p,
1870 const u8 *aBlob,
1871 int nBlob,
1872 int *pRc
1874 if( nBlob>0 && 0==sessionBufferGrow(p, nBlob, pRc) ){
1875 memcpy(&p->aBuf[p->nBuf], aBlob, nBlob);
1876 p->nBuf += nBlob;
1881 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
1882 ** called. Otherwise, append a string to the buffer. All bytes in the string
1883 ** up to (but not including) the nul-terminator are written to the buffer.
1885 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
1886 ** returning.
1888 static void sessionAppendStr(
1889 SessionBuffer *p,
1890 const char *zStr,
1891 int *pRc
1893 int nStr = sqlite3Strlen30(zStr);
1894 if( 0==sessionBufferGrow(p, nStr, pRc) ){
1895 memcpy(&p->aBuf[p->nBuf], zStr, nStr);
1896 p->nBuf += nStr;
1901 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
1902 ** called. Otherwise, append the string representation of integer iVal
1903 ** to the buffer. No nul-terminator is written.
1905 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
1906 ** returning.
1908 static void sessionAppendInteger(
1909 SessionBuffer *p, /* Buffer to append to */
1910 int iVal, /* Value to write the string rep. of */
1911 int *pRc /* IN/OUT: Error code */
1913 char aBuf[24];
1914 sqlite3_snprintf(sizeof(aBuf)-1, aBuf, "%d", iVal);
1915 sessionAppendStr(p, aBuf, pRc);
1919 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
1920 ** called. Otherwise, append the string zStr enclosed in quotes (") and
1921 ** with any embedded quote characters escaped to the buffer. No
1922 ** nul-terminator byte is written.
1924 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
1925 ** returning.
1927 static void sessionAppendIdent(
1928 SessionBuffer *p, /* Buffer to a append to */
1929 const char *zStr, /* String to quote, escape and append */
1930 int *pRc /* IN/OUT: Error code */
1932 int nStr = sqlite3Strlen30(zStr)*2 + 2 + 1;
1933 if( 0==sessionBufferGrow(p, nStr, pRc) ){
1934 char *zOut = (char *)&p->aBuf[p->nBuf];
1935 const char *zIn = zStr;
1936 *zOut++ = '"';
1937 while( *zIn ){
1938 if( *zIn=='"' ) *zOut++ = '"';
1939 *zOut++ = *(zIn++);
1941 *zOut++ = '"';
1942 p->nBuf = (int)((u8 *)zOut - p->aBuf);
1947 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
1948 ** called. Otherwse, it appends the serialized version of the value stored
1949 ** in column iCol of the row that SQL statement pStmt currently points
1950 ** to to the buffer.
1952 static void sessionAppendCol(
1953 SessionBuffer *p, /* Buffer to append to */
1954 sqlite3_stmt *pStmt, /* Handle pointing to row containing value */
1955 int iCol, /* Column to read value from */
1956 int *pRc /* IN/OUT: Error code */
1958 if( *pRc==SQLITE_OK ){
1959 int eType = sqlite3_column_type(pStmt, iCol);
1960 sessionAppendByte(p, (u8)eType, pRc);
1961 if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
1962 sqlite3_int64 i;
1963 u8 aBuf[8];
1964 if( eType==SQLITE_INTEGER ){
1965 i = sqlite3_column_int64(pStmt, iCol);
1966 }else{
1967 double r = sqlite3_column_double(pStmt, iCol);
1968 memcpy(&i, &r, 8);
1970 sessionPutI64(aBuf, i);
1971 sessionAppendBlob(p, aBuf, 8, pRc);
1973 if( eType==SQLITE_BLOB || eType==SQLITE_TEXT ){
1974 u8 *z;
1975 int nByte;
1976 if( eType==SQLITE_BLOB ){
1977 z = (u8 *)sqlite3_column_blob(pStmt, iCol);
1978 }else{
1979 z = (u8 *)sqlite3_column_text(pStmt, iCol);
1981 nByte = sqlite3_column_bytes(pStmt, iCol);
1982 if( z || (eType==SQLITE_BLOB && nByte==0) ){
1983 sessionAppendVarint(p, nByte, pRc);
1984 sessionAppendBlob(p, z, nByte, pRc);
1985 }else{
1986 *pRc = SQLITE_NOMEM;
1994 ** This function appends an update change to the buffer (see the comments
1995 ** under "CHANGESET FORMAT" at the top of the file). An update change
1996 ** consists of:
1998 ** 1 byte: SQLITE_UPDATE (0x17)
1999 ** n bytes: old.* record (see RECORD FORMAT)
2000 ** m bytes: new.* record (see RECORD FORMAT)
2002 ** The SessionChange object passed as the third argument contains the
2003 ** values that were stored in the row when the session began (the old.*
2004 ** values). The statement handle passed as the second argument points
2005 ** at the current version of the row (the new.* values).
2007 ** If all of the old.* values are equal to their corresponding new.* value
2008 ** (i.e. nothing has changed), then no data at all is appended to the buffer.
2010 ** Otherwise, the old.* record contains all primary key values and the
2011 ** original values of any fields that have been modified. The new.* record
2012 ** contains the new values of only those fields that have been modified.
2014 static int sessionAppendUpdate(
2015 SessionBuffer *pBuf, /* Buffer to append to */
2016 int bPatchset, /* True for "patchset", 0 for "changeset" */
2017 sqlite3_stmt *pStmt, /* Statement handle pointing at new row */
2018 SessionChange *p, /* Object containing old values */
2019 u8 *abPK /* Boolean array - true for PK columns */
2021 int rc = SQLITE_OK;
2022 SessionBuffer buf2 = {0,0,0}; /* Buffer to accumulate new.* record in */
2023 int bNoop = 1; /* Set to zero if any values are modified */
2024 int nRewind = pBuf->nBuf; /* Set to zero if any values are modified */
2025 int i; /* Used to iterate through columns */
2026 u8 *pCsr = p->aRecord; /* Used to iterate through old.* values */
2028 sessionAppendByte(pBuf, SQLITE_UPDATE, &rc);
2029 sessionAppendByte(pBuf, p->bIndirect, &rc);
2030 for(i=0; i<sqlite3_column_count(pStmt); i++){
2031 int bChanged = 0;
2032 int nAdvance;
2033 int eType = *pCsr;
2034 switch( eType ){
2035 case SQLITE_NULL:
2036 nAdvance = 1;
2037 if( sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
2038 bChanged = 1;
2040 break;
2042 case SQLITE_FLOAT:
2043 case SQLITE_INTEGER: {
2044 nAdvance = 9;
2045 if( eType==sqlite3_column_type(pStmt, i) ){
2046 sqlite3_int64 iVal = sessionGetI64(&pCsr[1]);
2047 if( eType==SQLITE_INTEGER ){
2048 if( iVal==sqlite3_column_int64(pStmt, i) ) break;
2049 }else{
2050 double dVal;
2051 memcpy(&dVal, &iVal, 8);
2052 if( dVal==sqlite3_column_double(pStmt, i) ) break;
2055 bChanged = 1;
2056 break;
2059 default: {
2060 int n;
2061 int nHdr = 1 + sessionVarintGet(&pCsr[1], &n);
2062 assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
2063 nAdvance = nHdr + n;
2064 if( eType==sqlite3_column_type(pStmt, i)
2065 && n==sqlite3_column_bytes(pStmt, i)
2066 && (n==0 || 0==memcmp(&pCsr[nHdr], sqlite3_column_blob(pStmt, i), n))
2068 break;
2070 bChanged = 1;
2074 /* If at least one field has been modified, this is not a no-op. */
2075 if( bChanged ) bNoop = 0;
2077 /* Add a field to the old.* record. This is omitted if this modules is
2078 ** currently generating a patchset. */
2079 if( bPatchset==0 ){
2080 if( bChanged || abPK[i] ){
2081 sessionAppendBlob(pBuf, pCsr, nAdvance, &rc);
2082 }else{
2083 sessionAppendByte(pBuf, 0, &rc);
2087 /* Add a field to the new.* record. Or the only record if currently
2088 ** generating a patchset. */
2089 if( bChanged || (bPatchset && abPK[i]) ){
2090 sessionAppendCol(&buf2, pStmt, i, &rc);
2091 }else{
2092 sessionAppendByte(&buf2, 0, &rc);
2095 pCsr += nAdvance;
2098 if( bNoop ){
2099 pBuf->nBuf = nRewind;
2100 }else{
2101 sessionAppendBlob(pBuf, buf2.aBuf, buf2.nBuf, &rc);
2103 sqlite3_free(buf2.aBuf);
2105 return rc;
2109 ** Append a DELETE change to the buffer passed as the first argument. Use
2110 ** the changeset format if argument bPatchset is zero, or the patchset
2111 ** format otherwise.
2113 static int sessionAppendDelete(
2114 SessionBuffer *pBuf, /* Buffer to append to */
2115 int bPatchset, /* True for "patchset", 0 for "changeset" */
2116 SessionChange *p, /* Object containing old values */
2117 int nCol, /* Number of columns in table */
2118 u8 *abPK /* Boolean array - true for PK columns */
2120 int rc = SQLITE_OK;
2122 sessionAppendByte(pBuf, SQLITE_DELETE, &rc);
2123 sessionAppendByte(pBuf, p->bIndirect, &rc);
2125 if( bPatchset==0 ){
2126 sessionAppendBlob(pBuf, p->aRecord, p->nRecord, &rc);
2127 }else{
2128 int i;
2129 u8 *a = p->aRecord;
2130 for(i=0; i<nCol; i++){
2131 u8 *pStart = a;
2132 int eType = *a++;
2134 switch( eType ){
2135 case 0:
2136 case SQLITE_NULL:
2137 assert( abPK[i]==0 );
2138 break;
2140 case SQLITE_FLOAT:
2141 case SQLITE_INTEGER:
2142 a += 8;
2143 break;
2145 default: {
2146 int n;
2147 a += sessionVarintGet(a, &n);
2148 a += n;
2149 break;
2152 if( abPK[i] ){
2153 sessionAppendBlob(pBuf, pStart, (int)(a-pStart), &rc);
2156 assert( (a - p->aRecord)==p->nRecord );
2159 return rc;
2163 ** Formulate and prepare a SELECT statement to retrieve a row from table
2164 ** zTab in database zDb based on its primary key. i.e.
2166 ** SELECT * FROM zDb.zTab WHERE pk1 = ? AND pk2 = ? AND ...
2168 static int sessionSelectStmt(
2169 sqlite3 *db, /* Database handle */
2170 const char *zDb, /* Database name */
2171 const char *zTab, /* Table name */
2172 int nCol, /* Number of columns in table */
2173 const char **azCol, /* Names of table columns */
2174 u8 *abPK, /* PRIMARY KEY array */
2175 sqlite3_stmt **ppStmt /* OUT: Prepared SELECT statement */
2177 int rc = SQLITE_OK;
2178 char *zSql = 0;
2179 int nSql = -1;
2181 if( 0==sqlite3_stricmp("sqlite_stat1", zTab) ){
2182 zSql = sqlite3_mprintf(
2183 "SELECT tbl, ?2, stat FROM %Q.sqlite_stat1 WHERE tbl IS ?1 AND "
2184 "idx IS (CASE WHEN ?2=X'' THEN NULL ELSE ?2 END)", zDb
2186 }else{
2187 int i;
2188 const char *zSep = "";
2189 SessionBuffer buf = {0, 0, 0};
2191 sessionAppendStr(&buf, "SELECT * FROM ", &rc);
2192 sessionAppendIdent(&buf, zDb, &rc);
2193 sessionAppendStr(&buf, ".", &rc);
2194 sessionAppendIdent(&buf, zTab, &rc);
2195 sessionAppendStr(&buf, " WHERE ", &rc);
2196 for(i=0; i<nCol; i++){
2197 if( abPK[i] ){
2198 sessionAppendStr(&buf, zSep, &rc);
2199 sessionAppendIdent(&buf, azCol[i], &rc);
2200 sessionAppendStr(&buf, " IS ?", &rc);
2201 sessionAppendInteger(&buf, i+1, &rc);
2202 zSep = " AND ";
2205 zSql = (char*)buf.aBuf;
2206 nSql = buf.nBuf;
2209 if( rc==SQLITE_OK ){
2210 rc = sqlite3_prepare_v2(db, zSql, nSql, ppStmt, 0);
2212 sqlite3_free(zSql);
2213 return rc;
2217 ** Bind the PRIMARY KEY values from the change passed in argument pChange
2218 ** to the SELECT statement passed as the first argument. The SELECT statement
2219 ** is as prepared by function sessionSelectStmt().
2221 ** Return SQLITE_OK if all PK values are successfully bound, or an SQLite
2222 ** error code (e.g. SQLITE_NOMEM) otherwise.
2224 static int sessionSelectBind(
2225 sqlite3_stmt *pSelect, /* SELECT from sessionSelectStmt() */
2226 int nCol, /* Number of columns in table */
2227 u8 *abPK, /* PRIMARY KEY array */
2228 SessionChange *pChange /* Change structure */
2230 int i;
2231 int rc = SQLITE_OK;
2232 u8 *a = pChange->aRecord;
2234 for(i=0; i<nCol && rc==SQLITE_OK; i++){
2235 int eType = *a++;
2237 switch( eType ){
2238 case 0:
2239 case SQLITE_NULL:
2240 assert( abPK[i]==0 );
2241 break;
2243 case SQLITE_INTEGER: {
2244 if( abPK[i] ){
2245 i64 iVal = sessionGetI64(a);
2246 rc = sqlite3_bind_int64(pSelect, i+1, iVal);
2248 a += 8;
2249 break;
2252 case SQLITE_FLOAT: {
2253 if( abPK[i] ){
2254 double rVal;
2255 i64 iVal = sessionGetI64(a);
2256 memcpy(&rVal, &iVal, 8);
2257 rc = sqlite3_bind_double(pSelect, i+1, rVal);
2259 a += 8;
2260 break;
2263 case SQLITE_TEXT: {
2264 int n;
2265 a += sessionVarintGet(a, &n);
2266 if( abPK[i] ){
2267 rc = sqlite3_bind_text(pSelect, i+1, (char *)a, n, SQLITE_TRANSIENT);
2269 a += n;
2270 break;
2273 default: {
2274 int n;
2275 assert( eType==SQLITE_BLOB );
2276 a += sessionVarintGet(a, &n);
2277 if( abPK[i] ){
2278 rc = sqlite3_bind_blob(pSelect, i+1, a, n, SQLITE_TRANSIENT);
2280 a += n;
2281 break;
2286 return rc;
2290 ** This function is a no-op if *pRc is set to other than SQLITE_OK when it
2291 ** is called. Otherwise, append a serialized table header (part of the binary
2292 ** changeset format) to buffer *pBuf. If an error occurs, set *pRc to an
2293 ** SQLite error code before returning.
2295 static void sessionAppendTableHdr(
2296 SessionBuffer *pBuf, /* Append header to this buffer */
2297 int bPatchset, /* Use the patchset format if true */
2298 SessionTable *pTab, /* Table object to append header for */
2299 int *pRc /* IN/OUT: Error code */
2301 /* Write a table header */
2302 sessionAppendByte(pBuf, (bPatchset ? 'P' : 'T'), pRc);
2303 sessionAppendVarint(pBuf, pTab->nCol, pRc);
2304 sessionAppendBlob(pBuf, pTab->abPK, pTab->nCol, pRc);
2305 sessionAppendBlob(pBuf, (u8 *)pTab->zName, (int)strlen(pTab->zName)+1, pRc);
2309 ** Generate either a changeset (if argument bPatchset is zero) or a patchset
2310 ** (if it is non-zero) based on the current contents of the session object
2311 ** passed as the first argument.
2313 ** If no error occurs, SQLITE_OK is returned and the new changeset/patchset
2314 ** stored in output variables *pnChangeset and *ppChangeset. Or, if an error
2315 ** occurs, an SQLite error code is returned and both output variables set
2316 ** to 0.
2318 static int sessionGenerateChangeset(
2319 sqlite3_session *pSession, /* Session object */
2320 int bPatchset, /* True for patchset, false for changeset */
2321 int (*xOutput)(void *pOut, const void *pData, int nData),
2322 void *pOut, /* First argument for xOutput */
2323 int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
2324 void **ppChangeset /* OUT: Buffer containing changeset */
2326 sqlite3 *db = pSession->db; /* Source database handle */
2327 SessionTable *pTab; /* Used to iterate through attached tables */
2328 SessionBuffer buf = {0,0,0}; /* Buffer in which to accumlate changeset */
2329 int rc; /* Return code */
2331 assert( xOutput==0 || (pnChangeset==0 && ppChangeset==0 ) );
2333 /* Zero the output variables in case an error occurs. If this session
2334 ** object is already in the error state (sqlite3_session.rc != SQLITE_OK),
2335 ** this call will be a no-op. */
2336 if( xOutput==0 ){
2337 *pnChangeset = 0;
2338 *ppChangeset = 0;
2341 if( pSession->rc ) return pSession->rc;
2342 rc = sqlite3_exec(pSession->db, "SAVEPOINT changeset", 0, 0, 0);
2343 if( rc!=SQLITE_OK ) return rc;
2345 sqlite3_mutex_enter(sqlite3_db_mutex(db));
2347 for(pTab=pSession->pTable; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
2348 if( pTab->nEntry ){
2349 const char *zName = pTab->zName;
2350 int nCol; /* Number of columns in table */
2351 u8 *abPK; /* Primary key array */
2352 const char **azCol = 0; /* Table columns */
2353 int i; /* Used to iterate through hash buckets */
2354 sqlite3_stmt *pSel = 0; /* SELECT statement to query table pTab */
2355 int nRewind = buf.nBuf; /* Initial size of write buffer */
2356 int nNoop; /* Size of buffer after writing tbl header */
2358 /* Check the table schema is still Ok. */
2359 rc = sessionTableInfo(db, pSession->zDb, zName, &nCol, 0, &azCol, &abPK);
2360 if( !rc && (pTab->nCol!=nCol || memcmp(abPK, pTab->abPK, nCol)) ){
2361 rc = SQLITE_SCHEMA;
2364 /* Write a table header */
2365 sessionAppendTableHdr(&buf, bPatchset, pTab, &rc);
2367 /* Build and compile a statement to execute: */
2368 if( rc==SQLITE_OK ){
2369 rc = sessionSelectStmt(
2370 db, pSession->zDb, zName, nCol, azCol, abPK, &pSel);
2373 nNoop = buf.nBuf;
2374 for(i=0; i<pTab->nChange && rc==SQLITE_OK; i++){
2375 SessionChange *p; /* Used to iterate through changes */
2377 for(p=pTab->apChange[i]; rc==SQLITE_OK && p; p=p->pNext){
2378 rc = sessionSelectBind(pSel, nCol, abPK, p);
2379 if( rc!=SQLITE_OK ) continue;
2380 if( sqlite3_step(pSel)==SQLITE_ROW ){
2381 if( p->op==SQLITE_INSERT ){
2382 int iCol;
2383 sessionAppendByte(&buf, SQLITE_INSERT, &rc);
2384 sessionAppendByte(&buf, p->bIndirect, &rc);
2385 for(iCol=0; iCol<nCol; iCol++){
2386 sessionAppendCol(&buf, pSel, iCol, &rc);
2388 }else{
2389 rc = sessionAppendUpdate(&buf, bPatchset, pSel, p, abPK);
2391 }else if( p->op!=SQLITE_INSERT ){
2392 rc = sessionAppendDelete(&buf, bPatchset, p, nCol, abPK);
2394 if( rc==SQLITE_OK ){
2395 rc = sqlite3_reset(pSel);
2398 /* If the buffer is now larger than SESSIONS_STRM_CHUNK_SIZE, pass
2399 ** its contents to the xOutput() callback. */
2400 if( xOutput
2401 && rc==SQLITE_OK
2402 && buf.nBuf>nNoop
2403 && buf.nBuf>SESSIONS_STRM_CHUNK_SIZE
2405 rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
2406 nNoop = -1;
2407 buf.nBuf = 0;
2413 sqlite3_finalize(pSel);
2414 if( buf.nBuf==nNoop ){
2415 buf.nBuf = nRewind;
2417 sqlite3_free((char*)azCol); /* cast works around VC++ bug */
2421 if( rc==SQLITE_OK ){
2422 if( xOutput==0 ){
2423 *pnChangeset = buf.nBuf;
2424 *ppChangeset = buf.aBuf;
2425 buf.aBuf = 0;
2426 }else if( buf.nBuf>0 ){
2427 rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
2431 sqlite3_free(buf.aBuf);
2432 sqlite3_exec(db, "RELEASE changeset", 0, 0, 0);
2433 sqlite3_mutex_leave(sqlite3_db_mutex(db));
2434 return rc;
2438 ** Obtain a changeset object containing all changes recorded by the
2439 ** session object passed as the first argument.
2441 ** It is the responsibility of the caller to eventually free the buffer
2442 ** using sqlite3_free().
2444 int sqlite3session_changeset(
2445 sqlite3_session *pSession, /* Session object */
2446 int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
2447 void **ppChangeset /* OUT: Buffer containing changeset */
2449 return sessionGenerateChangeset(pSession, 0, 0, 0, pnChangeset, ppChangeset);
2453 ** Streaming version of sqlite3session_changeset().
2455 int sqlite3session_changeset_strm(
2456 sqlite3_session *pSession,
2457 int (*xOutput)(void *pOut, const void *pData, int nData),
2458 void *pOut
2460 return sessionGenerateChangeset(pSession, 0, xOutput, pOut, 0, 0);
2464 ** Streaming version of sqlite3session_patchset().
2466 int sqlite3session_patchset_strm(
2467 sqlite3_session *pSession,
2468 int (*xOutput)(void *pOut, const void *pData, int nData),
2469 void *pOut
2471 return sessionGenerateChangeset(pSession, 1, xOutput, pOut, 0, 0);
2475 ** Obtain a patchset object containing all changes recorded by the
2476 ** session object passed as the first argument.
2478 ** It is the responsibility of the caller to eventually free the buffer
2479 ** using sqlite3_free().
2481 int sqlite3session_patchset(
2482 sqlite3_session *pSession, /* Session object */
2483 int *pnPatchset, /* OUT: Size of buffer at *ppChangeset */
2484 void **ppPatchset /* OUT: Buffer containing changeset */
2486 return sessionGenerateChangeset(pSession, 1, 0, 0, pnPatchset, ppPatchset);
2490 ** Enable or disable the session object passed as the first argument.
2492 int sqlite3session_enable(sqlite3_session *pSession, int bEnable){
2493 int ret;
2494 sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
2495 if( bEnable>=0 ){
2496 pSession->bEnable = bEnable;
2498 ret = pSession->bEnable;
2499 sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
2500 return ret;
2504 ** Enable or disable the session object passed as the first argument.
2506 int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect){
2507 int ret;
2508 sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
2509 if( bIndirect>=0 ){
2510 pSession->bIndirect = bIndirect;
2512 ret = pSession->bIndirect;
2513 sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
2514 return ret;
2518 ** Return true if there have been no changes to monitored tables recorded
2519 ** by the session object passed as the only argument.
2521 int sqlite3session_isempty(sqlite3_session *pSession){
2522 int ret = 0;
2523 SessionTable *pTab;
2525 sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
2526 for(pTab=pSession->pTable; pTab && ret==0; pTab=pTab->pNext){
2527 ret = (pTab->nEntry>0);
2529 sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
2531 return (ret==0);
2535 ** Do the work for either sqlite3changeset_start() or start_strm().
2537 static int sessionChangesetStart(
2538 sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
2539 int (*xInput)(void *pIn, void *pData, int *pnData),
2540 void *pIn,
2541 int nChangeset, /* Size of buffer pChangeset in bytes */
2542 void *pChangeset /* Pointer to buffer containing changeset */
2544 sqlite3_changeset_iter *pRet; /* Iterator to return */
2545 int nByte; /* Number of bytes to allocate for iterator */
2547 assert( xInput==0 || (pChangeset==0 && nChangeset==0) );
2549 /* Zero the output variable in case an error occurs. */
2550 *pp = 0;
2552 /* Allocate and initialize the iterator structure. */
2553 nByte = sizeof(sqlite3_changeset_iter);
2554 pRet = (sqlite3_changeset_iter *)sqlite3_malloc(nByte);
2555 if( !pRet ) return SQLITE_NOMEM;
2556 memset(pRet, 0, sizeof(sqlite3_changeset_iter));
2557 pRet->in.aData = (u8 *)pChangeset;
2558 pRet->in.nData = nChangeset;
2559 pRet->in.xInput = xInput;
2560 pRet->in.pIn = pIn;
2561 pRet->in.bEof = (xInput ? 0 : 1);
2563 /* Populate the output variable and return success. */
2564 *pp = pRet;
2565 return SQLITE_OK;
2569 ** Create an iterator used to iterate through the contents of a changeset.
2571 int sqlite3changeset_start(
2572 sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
2573 int nChangeset, /* Size of buffer pChangeset in bytes */
2574 void *pChangeset /* Pointer to buffer containing changeset */
2576 return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset);
2580 ** Streaming version of sqlite3changeset_start().
2582 int sqlite3changeset_start_strm(
2583 sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
2584 int (*xInput)(void *pIn, void *pData, int *pnData),
2585 void *pIn
2587 return sessionChangesetStart(pp, xInput, pIn, 0, 0);
2591 ** If the SessionInput object passed as the only argument is a streaming
2592 ** object and the buffer is full, discard some data to free up space.
2594 static void sessionDiscardData(SessionInput *pIn){
2595 if( pIn->bEof && pIn->xInput && pIn->iNext>=SESSIONS_STRM_CHUNK_SIZE ){
2596 int nMove = pIn->buf.nBuf - pIn->iNext;
2597 assert( nMove>=0 );
2598 if( nMove>0 ){
2599 memmove(pIn->buf.aBuf, &pIn->buf.aBuf[pIn->iNext], nMove);
2601 pIn->buf.nBuf -= pIn->iNext;
2602 pIn->iNext = 0;
2603 pIn->nData = pIn->buf.nBuf;
2608 ** Ensure that there are at least nByte bytes available in the buffer. Or,
2609 ** if there are not nByte bytes remaining in the input, that all available
2610 ** data is in the buffer.
2612 ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
2614 static int sessionInputBuffer(SessionInput *pIn, int nByte){
2615 int rc = SQLITE_OK;
2616 if( pIn->xInput ){
2617 while( !pIn->bEof && (pIn->iNext+nByte)>=pIn->nData && rc==SQLITE_OK ){
2618 int nNew = SESSIONS_STRM_CHUNK_SIZE;
2620 if( pIn->bNoDiscard==0 ) sessionDiscardData(pIn);
2621 if( SQLITE_OK==sessionBufferGrow(&pIn->buf, nNew, &rc) ){
2622 rc = pIn->xInput(pIn->pIn, &pIn->buf.aBuf[pIn->buf.nBuf], &nNew);
2623 if( nNew==0 ){
2624 pIn->bEof = 1;
2625 }else{
2626 pIn->buf.nBuf += nNew;
2630 pIn->aData = pIn->buf.aBuf;
2631 pIn->nData = pIn->buf.nBuf;
2634 return rc;
2638 ** When this function is called, *ppRec points to the start of a record
2639 ** that contains nCol values. This function advances the pointer *ppRec
2640 ** until it points to the byte immediately following that record.
2642 static void sessionSkipRecord(
2643 u8 **ppRec, /* IN/OUT: Record pointer */
2644 int nCol /* Number of values in record */
2646 u8 *aRec = *ppRec;
2647 int i;
2648 for(i=0; i<nCol; i++){
2649 int eType = *aRec++;
2650 if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
2651 int nByte;
2652 aRec += sessionVarintGet((u8*)aRec, &nByte);
2653 aRec += nByte;
2654 }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
2655 aRec += 8;
2659 *ppRec = aRec;
2663 ** This function sets the value of the sqlite3_value object passed as the
2664 ** first argument to a copy of the string or blob held in the aData[]
2665 ** buffer. SQLITE_OK is returned if successful, or SQLITE_NOMEM if an OOM
2666 ** error occurs.
2668 static int sessionValueSetStr(
2669 sqlite3_value *pVal, /* Set the value of this object */
2670 u8 *aData, /* Buffer containing string or blob data */
2671 int nData, /* Size of buffer aData[] in bytes */
2672 u8 enc /* String encoding (0 for blobs) */
2674 /* In theory this code could just pass SQLITE_TRANSIENT as the final
2675 ** argument to sqlite3ValueSetStr() and have the copy created
2676 ** automatically. But doing so makes it difficult to detect any OOM
2677 ** error. Hence the code to create the copy externally. */
2678 u8 *aCopy = sqlite3_malloc(nData+1);
2679 if( aCopy==0 ) return SQLITE_NOMEM;
2680 memcpy(aCopy, aData, nData);
2681 sqlite3ValueSetStr(pVal, nData, (char*)aCopy, enc, sqlite3_free);
2682 return SQLITE_OK;
2686 ** Deserialize a single record from a buffer in memory. See "RECORD FORMAT"
2687 ** for details.
2689 ** When this function is called, *paChange points to the start of the record
2690 ** to deserialize. Assuming no error occurs, *paChange is set to point to
2691 ** one byte after the end of the same record before this function returns.
2692 ** If the argument abPK is NULL, then the record contains nCol values. Or,
2693 ** if abPK is other than NULL, then the record contains only the PK fields
2694 ** (in other words, it is a patchset DELETE record).
2696 ** If successful, each element of the apOut[] array (allocated by the caller)
2697 ** is set to point to an sqlite3_value object containing the value read
2698 ** from the corresponding position in the record. If that value is not
2699 ** included in the record (i.e. because the record is part of an UPDATE change
2700 ** and the field was not modified), the corresponding element of apOut[] is
2701 ** set to NULL.
2703 ** It is the responsibility of the caller to free all sqlite_value structures
2704 ** using sqlite3_free().
2706 ** If an error occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
2707 ** The apOut[] array may have been partially populated in this case.
2709 static int sessionReadRecord(
2710 SessionInput *pIn, /* Input data */
2711 int nCol, /* Number of values in record */
2712 u8 *abPK, /* Array of primary key flags, or NULL */
2713 sqlite3_value **apOut /* Write values to this array */
2715 int i; /* Used to iterate through columns */
2716 int rc = SQLITE_OK;
2718 for(i=0; i<nCol && rc==SQLITE_OK; i++){
2719 int eType = 0; /* Type of value (SQLITE_NULL, TEXT etc.) */
2720 if( abPK && abPK[i]==0 ) continue;
2721 rc = sessionInputBuffer(pIn, 9);
2722 if( rc==SQLITE_OK ){
2723 if( pIn->iNext>=pIn->nData ){
2724 rc = SQLITE_CORRUPT_BKPT;
2725 }else{
2726 eType = pIn->aData[pIn->iNext++];
2727 assert( apOut[i]==0 );
2728 if( eType ){
2729 apOut[i] = sqlite3ValueNew(0);
2730 if( !apOut[i] ) rc = SQLITE_NOMEM;
2735 if( rc==SQLITE_OK ){
2736 u8 *aVal = &pIn->aData[pIn->iNext];
2737 if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
2738 int nByte;
2739 pIn->iNext += sessionVarintGet(aVal, &nByte);
2740 rc = sessionInputBuffer(pIn, nByte);
2741 if( rc==SQLITE_OK ){
2742 if( nByte<0 || nByte>pIn->nData-pIn->iNext ){
2743 rc = SQLITE_CORRUPT_BKPT;
2744 }else{
2745 u8 enc = (eType==SQLITE_TEXT ? SQLITE_UTF8 : 0);
2746 rc = sessionValueSetStr(apOut[i],&pIn->aData[pIn->iNext],nByte,enc);
2747 pIn->iNext += nByte;
2751 if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
2752 sqlite3_int64 v = sessionGetI64(aVal);
2753 if( eType==SQLITE_INTEGER ){
2754 sqlite3VdbeMemSetInt64(apOut[i], v);
2755 }else{
2756 double d;
2757 memcpy(&d, &v, 8);
2758 sqlite3VdbeMemSetDouble(apOut[i], d);
2760 pIn->iNext += 8;
2765 return rc;
2769 ** The input pointer currently points to the second byte of a table-header.
2770 ** Specifically, to the following:
2772 ** + number of columns in table (varint)
2773 ** + array of PK flags (1 byte per column),
2774 ** + table name (nul terminated).
2776 ** This function ensures that all of the above is present in the input
2777 ** buffer (i.e. that it can be accessed without any calls to xInput()).
2778 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
2779 ** The input pointer is not moved.
2781 static int sessionChangesetBufferTblhdr(SessionInput *pIn, int *pnByte){
2782 int rc = SQLITE_OK;
2783 int nCol = 0;
2784 int nRead = 0;
2786 rc = sessionInputBuffer(pIn, 9);
2787 if( rc==SQLITE_OK ){
2788 nRead += sessionVarintGet(&pIn->aData[pIn->iNext + nRead], &nCol);
2789 /* The hard upper limit for the number of columns in an SQLite
2790 ** database table is, according to sqliteLimit.h, 32676. So
2791 ** consider any table-header that purports to have more than 65536
2792 ** columns to be corrupt. This is convenient because otherwise,
2793 ** if the (nCol>65536) condition below were omitted, a sufficiently
2794 ** large value for nCol may cause nRead to wrap around and become
2795 ** negative. Leading to a crash. */
2796 if( nCol<0 || nCol>65536 ){
2797 rc = SQLITE_CORRUPT_BKPT;
2798 }else{
2799 rc = sessionInputBuffer(pIn, nRead+nCol+100);
2800 nRead += nCol;
2804 while( rc==SQLITE_OK ){
2805 while( (pIn->iNext + nRead)<pIn->nData && pIn->aData[pIn->iNext + nRead] ){
2806 nRead++;
2808 if( (pIn->iNext + nRead)<pIn->nData ) break;
2809 rc = sessionInputBuffer(pIn, nRead + 100);
2811 *pnByte = nRead+1;
2812 return rc;
2816 ** The input pointer currently points to the first byte of the first field
2817 ** of a record consisting of nCol columns. This function ensures the entire
2818 ** record is buffered. It does not move the input pointer.
2820 ** If successful, SQLITE_OK is returned and *pnByte is set to the size of
2821 ** the record in bytes. Otherwise, an SQLite error code is returned. The
2822 ** final value of *pnByte is undefined in this case.
2824 static int sessionChangesetBufferRecord(
2825 SessionInput *pIn, /* Input data */
2826 int nCol, /* Number of columns in record */
2827 int *pnByte /* OUT: Size of record in bytes */
2829 int rc = SQLITE_OK;
2830 int nByte = 0;
2831 int i;
2832 for(i=0; rc==SQLITE_OK && i<nCol; i++){
2833 int eType;
2834 rc = sessionInputBuffer(pIn, nByte + 10);
2835 if( rc==SQLITE_OK ){
2836 eType = pIn->aData[pIn->iNext + nByte++];
2837 if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
2838 int n;
2839 nByte += sessionVarintGet(&pIn->aData[pIn->iNext+nByte], &n);
2840 nByte += n;
2841 rc = sessionInputBuffer(pIn, nByte);
2842 }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
2843 nByte += 8;
2847 *pnByte = nByte;
2848 return rc;
2852 ** The input pointer currently points to the second byte of a table-header.
2853 ** Specifically, to the following:
2855 ** + number of columns in table (varint)
2856 ** + array of PK flags (1 byte per column),
2857 ** + table name (nul terminated).
2859 ** This function decodes the table-header and populates the p->nCol,
2860 ** p->zTab and p->abPK[] variables accordingly. The p->apValue[] array is
2861 ** also allocated or resized according to the new value of p->nCol. The
2862 ** input pointer is left pointing to the byte following the table header.
2864 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code
2865 ** is returned and the final values of the various fields enumerated above
2866 ** are undefined.
2868 static int sessionChangesetReadTblhdr(sqlite3_changeset_iter *p){
2869 int rc;
2870 int nCopy;
2871 assert( p->rc==SQLITE_OK );
2873 rc = sessionChangesetBufferTblhdr(&p->in, &nCopy);
2874 if( rc==SQLITE_OK ){
2875 int nByte;
2876 int nVarint;
2877 nVarint = sessionVarintGet(&p->in.aData[p->in.iNext], &p->nCol);
2878 if( p->nCol>0 ){
2879 nCopy -= nVarint;
2880 p->in.iNext += nVarint;
2881 nByte = p->nCol * sizeof(sqlite3_value*) * 2 + nCopy;
2882 p->tblhdr.nBuf = 0;
2883 sessionBufferGrow(&p->tblhdr, nByte, &rc);
2884 }else{
2885 rc = SQLITE_CORRUPT_BKPT;
2889 if( rc==SQLITE_OK ){
2890 int iPK = sizeof(sqlite3_value*)*p->nCol*2;
2891 memset(p->tblhdr.aBuf, 0, iPK);
2892 memcpy(&p->tblhdr.aBuf[iPK], &p->in.aData[p->in.iNext], nCopy);
2893 p->in.iNext += nCopy;
2896 p->apValue = (sqlite3_value**)p->tblhdr.aBuf;
2897 p->abPK = (u8*)&p->apValue[p->nCol*2];
2898 p->zTab = (char*)&p->abPK[p->nCol];
2899 return (p->rc = rc);
2903 ** Advance the changeset iterator to the next change.
2905 ** If both paRec and pnRec are NULL, then this function works like the public
2906 ** API sqlite3changeset_next(). If SQLITE_ROW is returned, then the
2907 ** sqlite3changeset_new() and old() APIs may be used to query for values.
2909 ** Otherwise, if paRec and pnRec are not NULL, then a pointer to the change
2910 ** record is written to *paRec before returning and the number of bytes in
2911 ** the record to *pnRec.
2913 ** Either way, this function returns SQLITE_ROW if the iterator is
2914 ** successfully advanced to the next change in the changeset, an SQLite
2915 ** error code if an error occurs, or SQLITE_DONE if there are no further
2916 ** changes in the changeset.
2918 static int sessionChangesetNext(
2919 sqlite3_changeset_iter *p, /* Changeset iterator */
2920 u8 **paRec, /* If non-NULL, store record pointer here */
2921 int *pnRec /* If non-NULL, store size of record here */
2923 int i;
2924 u8 op;
2926 assert( (paRec==0 && pnRec==0) || (paRec && pnRec) );
2928 /* If the iterator is in the error-state, return immediately. */
2929 if( p->rc!=SQLITE_OK ) return p->rc;
2931 /* Free the current contents of p->apValue[], if any. */
2932 if( p->apValue ){
2933 for(i=0; i<p->nCol*2; i++){
2934 sqlite3ValueFree(p->apValue[i]);
2936 memset(p->apValue, 0, sizeof(sqlite3_value*)*p->nCol*2);
2939 /* Make sure the buffer contains at least 10 bytes of input data, or all
2940 ** remaining data if there are less than 10 bytes available. This is
2941 ** sufficient either for the 'T' or 'P' byte and the varint that follows
2942 ** it, or for the two single byte values otherwise. */
2943 p->rc = sessionInputBuffer(&p->in, 2);
2944 if( p->rc!=SQLITE_OK ) return p->rc;
2946 /* If the iterator is already at the end of the changeset, return DONE. */
2947 if( p->in.iNext>=p->in.nData ){
2948 return SQLITE_DONE;
2951 sessionDiscardData(&p->in);
2952 p->in.iCurrent = p->in.iNext;
2954 op = p->in.aData[p->in.iNext++];
2955 while( op=='T' || op=='P' ){
2956 p->bPatchset = (op=='P');
2957 if( sessionChangesetReadTblhdr(p) ) return p->rc;
2958 if( (p->rc = sessionInputBuffer(&p->in, 2)) ) return p->rc;
2959 p->in.iCurrent = p->in.iNext;
2960 if( p->in.iNext>=p->in.nData ) return SQLITE_DONE;
2961 op = p->in.aData[p->in.iNext++];
2964 if( p->zTab==0 ){
2965 /* The first record in the changeset is not a table header. Must be a
2966 ** corrupt changeset. */
2967 assert( p->in.iNext==1 );
2968 return (p->rc = SQLITE_CORRUPT_BKPT);
2971 p->op = op;
2972 p->bIndirect = p->in.aData[p->in.iNext++];
2973 if( p->op!=SQLITE_UPDATE && p->op!=SQLITE_DELETE && p->op!=SQLITE_INSERT ){
2974 return (p->rc = SQLITE_CORRUPT_BKPT);
2977 if( paRec ){
2978 int nVal; /* Number of values to buffer */
2979 if( p->bPatchset==0 && op==SQLITE_UPDATE ){
2980 nVal = p->nCol * 2;
2981 }else if( p->bPatchset && op==SQLITE_DELETE ){
2982 nVal = 0;
2983 for(i=0; i<p->nCol; i++) if( p->abPK[i] ) nVal++;
2984 }else{
2985 nVal = p->nCol;
2987 p->rc = sessionChangesetBufferRecord(&p->in, nVal, pnRec);
2988 if( p->rc!=SQLITE_OK ) return p->rc;
2989 *paRec = &p->in.aData[p->in.iNext];
2990 p->in.iNext += *pnRec;
2991 }else{
2993 /* If this is an UPDATE or DELETE, read the old.* record. */
2994 if( p->op!=SQLITE_INSERT && (p->bPatchset==0 || p->op==SQLITE_DELETE) ){
2995 u8 *abPK = p->bPatchset ? p->abPK : 0;
2996 p->rc = sessionReadRecord(&p->in, p->nCol, abPK, p->apValue);
2997 if( p->rc!=SQLITE_OK ) return p->rc;
3000 /* If this is an INSERT or UPDATE, read the new.* record. */
3001 if( p->op!=SQLITE_DELETE ){
3002 p->rc = sessionReadRecord(&p->in, p->nCol, 0, &p->apValue[p->nCol]);
3003 if( p->rc!=SQLITE_OK ) return p->rc;
3006 if( p->bPatchset && p->op==SQLITE_UPDATE ){
3007 /* If this is an UPDATE that is part of a patchset, then all PK and
3008 ** modified fields are present in the new.* record. The old.* record
3009 ** is currently completely empty. This block shifts the PK fields from
3010 ** new.* to old.*, to accommodate the code that reads these arrays. */
3011 for(i=0; i<p->nCol; i++){
3012 assert( p->apValue[i]==0 );
3013 if( p->abPK[i] ){
3014 p->apValue[i] = p->apValue[i+p->nCol];
3015 if( p->apValue[i]==0 ) return (p->rc = SQLITE_CORRUPT_BKPT);
3016 p->apValue[i+p->nCol] = 0;
3022 return SQLITE_ROW;
3026 ** Advance an iterator created by sqlite3changeset_start() to the next
3027 ** change in the changeset. This function may return SQLITE_ROW, SQLITE_DONE
3028 ** or SQLITE_CORRUPT.
3030 ** This function may not be called on iterators passed to a conflict handler
3031 ** callback by changeset_apply().
3033 int sqlite3changeset_next(sqlite3_changeset_iter *p){
3034 return sessionChangesetNext(p, 0, 0);
3038 ** The following function extracts information on the current change
3039 ** from a changeset iterator. It may only be called after changeset_next()
3040 ** has returned SQLITE_ROW.
3042 int sqlite3changeset_op(
3043 sqlite3_changeset_iter *pIter, /* Iterator handle */
3044 const char **pzTab, /* OUT: Pointer to table name */
3045 int *pnCol, /* OUT: Number of columns in table */
3046 int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */
3047 int *pbIndirect /* OUT: True if change is indirect */
3049 *pOp = pIter->op;
3050 *pnCol = pIter->nCol;
3051 *pzTab = pIter->zTab;
3052 if( pbIndirect ) *pbIndirect = pIter->bIndirect;
3053 return SQLITE_OK;
3057 ** Return information regarding the PRIMARY KEY and number of columns in
3058 ** the database table affected by the change that pIter currently points
3059 ** to. This function may only be called after changeset_next() returns
3060 ** SQLITE_ROW.
3062 int sqlite3changeset_pk(
3063 sqlite3_changeset_iter *pIter, /* Iterator object */
3064 unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */
3065 int *pnCol /* OUT: Number of entries in output array */
3067 *pabPK = pIter->abPK;
3068 if( pnCol ) *pnCol = pIter->nCol;
3069 return SQLITE_OK;
3073 ** This function may only be called while the iterator is pointing to an
3074 ** SQLITE_UPDATE or SQLITE_DELETE change (see sqlite3changeset_op()).
3075 ** Otherwise, SQLITE_MISUSE is returned.
3077 ** It sets *ppValue to point to an sqlite3_value structure containing the
3078 ** iVal'th value in the old.* record. Or, if that particular value is not
3079 ** included in the record (because the change is an UPDATE and the field
3080 ** was not modified and is not a PK column), set *ppValue to NULL.
3082 ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
3083 ** not modified. Otherwise, SQLITE_OK.
3085 int sqlite3changeset_old(
3086 sqlite3_changeset_iter *pIter, /* Changeset iterator */
3087 int iVal, /* Index of old.* value to retrieve */
3088 sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */
3090 if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_DELETE ){
3091 return SQLITE_MISUSE;
3093 if( iVal<0 || iVal>=pIter->nCol ){
3094 return SQLITE_RANGE;
3096 *ppValue = pIter->apValue[iVal];
3097 return SQLITE_OK;
3101 ** This function may only be called while the iterator is pointing to an
3102 ** SQLITE_UPDATE or SQLITE_INSERT change (see sqlite3changeset_op()).
3103 ** Otherwise, SQLITE_MISUSE is returned.
3105 ** It sets *ppValue to point to an sqlite3_value structure containing the
3106 ** iVal'th value in the new.* record. Or, if that particular value is not
3107 ** included in the record (because the change is an UPDATE and the field
3108 ** was not modified), set *ppValue to NULL.
3110 ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
3111 ** not modified. Otherwise, SQLITE_OK.
3113 int sqlite3changeset_new(
3114 sqlite3_changeset_iter *pIter, /* Changeset iterator */
3115 int iVal, /* Index of new.* value to retrieve */
3116 sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */
3118 if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_INSERT ){
3119 return SQLITE_MISUSE;
3121 if( iVal<0 || iVal>=pIter->nCol ){
3122 return SQLITE_RANGE;
3124 *ppValue = pIter->apValue[pIter->nCol+iVal];
3125 return SQLITE_OK;
3129 ** The following two macros are used internally. They are similar to the
3130 ** sqlite3changeset_new() and sqlite3changeset_old() functions, except that
3131 ** they omit all error checking and return a pointer to the requested value.
3133 #define sessionChangesetNew(pIter, iVal) (pIter)->apValue[(pIter)->nCol+(iVal)]
3134 #define sessionChangesetOld(pIter, iVal) (pIter)->apValue[(iVal)]
3137 ** This function may only be called with a changeset iterator that has been
3138 ** passed to an SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT
3139 ** conflict-handler function. Otherwise, SQLITE_MISUSE is returned.
3141 ** If successful, *ppValue is set to point to an sqlite3_value structure
3142 ** containing the iVal'th value of the conflicting record.
3144 ** If value iVal is out-of-range or some other error occurs, an SQLite error
3145 ** code is returned. Otherwise, SQLITE_OK.
3147 int sqlite3changeset_conflict(
3148 sqlite3_changeset_iter *pIter, /* Changeset iterator */
3149 int iVal, /* Index of conflict record value to fetch */
3150 sqlite3_value **ppValue /* OUT: Value from conflicting row */
3152 if( !pIter->pConflict ){
3153 return SQLITE_MISUSE;
3155 if( iVal<0 || iVal>=pIter->nCol ){
3156 return SQLITE_RANGE;
3158 *ppValue = sqlite3_column_value(pIter->pConflict, iVal);
3159 return SQLITE_OK;
3163 ** This function may only be called with an iterator passed to an
3164 ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
3165 ** it sets the output variable to the total number of known foreign key
3166 ** violations in the destination database and returns SQLITE_OK.
3168 ** In all other cases this function returns SQLITE_MISUSE.
3170 int sqlite3changeset_fk_conflicts(
3171 sqlite3_changeset_iter *pIter, /* Changeset iterator */
3172 int *pnOut /* OUT: Number of FK violations */
3174 if( pIter->pConflict || pIter->apValue ){
3175 return SQLITE_MISUSE;
3177 *pnOut = pIter->nCol;
3178 return SQLITE_OK;
3183 ** Finalize an iterator allocated with sqlite3changeset_start().
3185 ** This function may not be called on iterators passed to a conflict handler
3186 ** callback by changeset_apply().
3188 int sqlite3changeset_finalize(sqlite3_changeset_iter *p){
3189 int rc = SQLITE_OK;
3190 if( p ){
3191 int i; /* Used to iterate through p->apValue[] */
3192 rc = p->rc;
3193 if( p->apValue ){
3194 for(i=0; i<p->nCol*2; i++) sqlite3ValueFree(p->apValue[i]);
3196 sqlite3_free(p->tblhdr.aBuf);
3197 sqlite3_free(p->in.buf.aBuf);
3198 sqlite3_free(p);
3200 return rc;
3203 static int sessionChangesetInvert(
3204 SessionInput *pInput, /* Input changeset */
3205 int (*xOutput)(void *pOut, const void *pData, int nData),
3206 void *pOut,
3207 int *pnInverted, /* OUT: Number of bytes in output changeset */
3208 void **ppInverted /* OUT: Inverse of pChangeset */
3210 int rc = SQLITE_OK; /* Return value */
3211 SessionBuffer sOut; /* Output buffer */
3212 int nCol = 0; /* Number of cols in current table */
3213 u8 *abPK = 0; /* PK array for current table */
3214 sqlite3_value **apVal = 0; /* Space for values for UPDATE inversion */
3215 SessionBuffer sPK = {0, 0, 0}; /* PK array for current table */
3217 /* Initialize the output buffer */
3218 memset(&sOut, 0, sizeof(SessionBuffer));
3220 /* Zero the output variables in case an error occurs. */
3221 if( ppInverted ){
3222 *ppInverted = 0;
3223 *pnInverted = 0;
3226 while( 1 ){
3227 u8 eType;
3229 /* Test for EOF. */
3230 if( (rc = sessionInputBuffer(pInput, 2)) ) goto finished_invert;
3231 if( pInput->iNext>=pInput->nData ) break;
3232 eType = pInput->aData[pInput->iNext];
3234 switch( eType ){
3235 case 'T': {
3236 /* A 'table' record consists of:
3238 ** * A constant 'T' character,
3239 ** * Number of columns in said table (a varint),
3240 ** * An array of nCol bytes (sPK),
3241 ** * A nul-terminated table name.
3243 int nByte;
3244 int nVar;
3245 pInput->iNext++;
3246 if( (rc = sessionChangesetBufferTblhdr(pInput, &nByte)) ){
3247 goto finished_invert;
3249 nVar = sessionVarintGet(&pInput->aData[pInput->iNext], &nCol);
3250 sPK.nBuf = 0;
3251 sessionAppendBlob(&sPK, &pInput->aData[pInput->iNext+nVar], nCol, &rc);
3252 sessionAppendByte(&sOut, eType, &rc);
3253 sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
3254 if( rc ) goto finished_invert;
3256 pInput->iNext += nByte;
3257 sqlite3_free(apVal);
3258 apVal = 0;
3259 abPK = sPK.aBuf;
3260 break;
3263 case SQLITE_INSERT:
3264 case SQLITE_DELETE: {
3265 int nByte;
3266 int bIndirect = pInput->aData[pInput->iNext+1];
3267 int eType2 = (eType==SQLITE_DELETE ? SQLITE_INSERT : SQLITE_DELETE);
3268 pInput->iNext += 2;
3269 assert( rc==SQLITE_OK );
3270 rc = sessionChangesetBufferRecord(pInput, nCol, &nByte);
3271 sessionAppendByte(&sOut, eType2, &rc);
3272 sessionAppendByte(&sOut, bIndirect, &rc);
3273 sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
3274 pInput->iNext += nByte;
3275 if( rc ) goto finished_invert;
3276 break;
3279 case SQLITE_UPDATE: {
3280 int iCol;
3282 if( 0==apVal ){
3283 apVal = (sqlite3_value **)sqlite3_malloc(sizeof(apVal[0])*nCol*2);
3284 if( 0==apVal ){
3285 rc = SQLITE_NOMEM;
3286 goto finished_invert;
3288 memset(apVal, 0, sizeof(apVal[0])*nCol*2);
3291 /* Write the header for the new UPDATE change. Same as the original. */
3292 sessionAppendByte(&sOut, eType, &rc);
3293 sessionAppendByte(&sOut, pInput->aData[pInput->iNext+1], &rc);
3295 /* Read the old.* and new.* records for the update change. */
3296 pInput->iNext += 2;
3297 rc = sessionReadRecord(pInput, nCol, 0, &apVal[0]);
3298 if( rc==SQLITE_OK ){
3299 rc = sessionReadRecord(pInput, nCol, 0, &apVal[nCol]);
3302 /* Write the new old.* record. Consists of the PK columns from the
3303 ** original old.* record, and the other values from the original
3304 ** new.* record. */
3305 for(iCol=0; iCol<nCol; iCol++){
3306 sqlite3_value *pVal = apVal[iCol + (abPK[iCol] ? 0 : nCol)];
3307 sessionAppendValue(&sOut, pVal, &rc);
3310 /* Write the new new.* record. Consists of a copy of all values
3311 ** from the original old.* record, except for the PK columns, which
3312 ** are set to "undefined". */
3313 for(iCol=0; iCol<nCol; iCol++){
3314 sqlite3_value *pVal = (abPK[iCol] ? 0 : apVal[iCol]);
3315 sessionAppendValue(&sOut, pVal, &rc);
3318 for(iCol=0; iCol<nCol*2; iCol++){
3319 sqlite3ValueFree(apVal[iCol]);
3321 memset(apVal, 0, sizeof(apVal[0])*nCol*2);
3322 if( rc!=SQLITE_OK ){
3323 goto finished_invert;
3326 break;
3329 default:
3330 rc = SQLITE_CORRUPT_BKPT;
3331 goto finished_invert;
3334 assert( rc==SQLITE_OK );
3335 if( xOutput && sOut.nBuf>=SESSIONS_STRM_CHUNK_SIZE ){
3336 rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
3337 sOut.nBuf = 0;
3338 if( rc!=SQLITE_OK ) goto finished_invert;
3342 assert( rc==SQLITE_OK );
3343 if( pnInverted ){
3344 *pnInverted = sOut.nBuf;
3345 *ppInverted = sOut.aBuf;
3346 sOut.aBuf = 0;
3347 }else if( sOut.nBuf>0 ){
3348 rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
3351 finished_invert:
3352 sqlite3_free(sOut.aBuf);
3353 sqlite3_free(apVal);
3354 sqlite3_free(sPK.aBuf);
3355 return rc;
3360 ** Invert a changeset object.
3362 int sqlite3changeset_invert(
3363 int nChangeset, /* Number of bytes in input */
3364 const void *pChangeset, /* Input changeset */
3365 int *pnInverted, /* OUT: Number of bytes in output changeset */
3366 void **ppInverted /* OUT: Inverse of pChangeset */
3368 SessionInput sInput;
3370 /* Set up the input stream */
3371 memset(&sInput, 0, sizeof(SessionInput));
3372 sInput.nData = nChangeset;
3373 sInput.aData = (u8*)pChangeset;
3375 return sessionChangesetInvert(&sInput, 0, 0, pnInverted, ppInverted);
3379 ** Streaming version of sqlite3changeset_invert().
3381 int sqlite3changeset_invert_strm(
3382 int (*xInput)(void *pIn, void *pData, int *pnData),
3383 void *pIn,
3384 int (*xOutput)(void *pOut, const void *pData, int nData),
3385 void *pOut
3387 SessionInput sInput;
3388 int rc;
3390 /* Set up the input stream */
3391 memset(&sInput, 0, sizeof(SessionInput));
3392 sInput.xInput = xInput;
3393 sInput.pIn = pIn;
3395 rc = sessionChangesetInvert(&sInput, xOutput, pOut, 0, 0);
3396 sqlite3_free(sInput.buf.aBuf);
3397 return rc;
3400 typedef struct SessionApplyCtx SessionApplyCtx;
3401 struct SessionApplyCtx {
3402 sqlite3 *db;
3403 sqlite3_stmt *pDelete; /* DELETE statement */
3404 sqlite3_stmt *pUpdate; /* UPDATE statement */
3405 sqlite3_stmt *pInsert; /* INSERT statement */
3406 sqlite3_stmt *pSelect; /* SELECT statement */
3407 int nCol; /* Size of azCol[] and abPK[] arrays */
3408 const char **azCol; /* Array of column names */
3409 u8 *abPK; /* Boolean array - true if column is in PK */
3410 int bStat1; /* True if table is sqlite_stat1 */
3411 int bDeferConstraints; /* True to defer constraints */
3412 SessionBuffer constraints; /* Deferred constraints are stored here */
3416 ** Formulate a statement to DELETE a row from database db. Assuming a table
3417 ** structure like this:
3419 ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
3421 ** The DELETE statement looks like this:
3423 ** DELETE FROM x WHERE a = :1 AND c = :3 AND (:5 OR b IS :2 AND d IS :4)
3425 ** Variable :5 (nCol+1) is a boolean. It should be set to 0 if we require
3426 ** matching b and d values, or 1 otherwise. The second case comes up if the
3427 ** conflict handler is invoked with NOTFOUND and returns CHANGESET_REPLACE.
3429 ** If successful, SQLITE_OK is returned and SessionApplyCtx.pDelete is left
3430 ** pointing to the prepared version of the SQL statement.
3432 static int sessionDeleteRow(
3433 sqlite3 *db, /* Database handle */
3434 const char *zTab, /* Table name */
3435 SessionApplyCtx *p /* Session changeset-apply context */
3437 int i;
3438 const char *zSep = "";
3439 int rc = SQLITE_OK;
3440 SessionBuffer buf = {0, 0, 0};
3441 int nPk = 0;
3443 sessionAppendStr(&buf, "DELETE FROM ", &rc);
3444 sessionAppendIdent(&buf, zTab, &rc);
3445 sessionAppendStr(&buf, " WHERE ", &rc);
3447 for(i=0; i<p->nCol; i++){
3448 if( p->abPK[i] ){
3449 nPk++;
3450 sessionAppendStr(&buf, zSep, &rc);
3451 sessionAppendIdent(&buf, p->azCol[i], &rc);
3452 sessionAppendStr(&buf, " = ?", &rc);
3453 sessionAppendInteger(&buf, i+1, &rc);
3454 zSep = " AND ";
3458 if( nPk<p->nCol ){
3459 sessionAppendStr(&buf, " AND (?", &rc);
3460 sessionAppendInteger(&buf, p->nCol+1, &rc);
3461 sessionAppendStr(&buf, " OR ", &rc);
3463 zSep = "";
3464 for(i=0; i<p->nCol; i++){
3465 if( !p->abPK[i] ){
3466 sessionAppendStr(&buf, zSep, &rc);
3467 sessionAppendIdent(&buf, p->azCol[i], &rc);
3468 sessionAppendStr(&buf, " IS ?", &rc);
3469 sessionAppendInteger(&buf, i+1, &rc);
3470 zSep = "AND ";
3473 sessionAppendStr(&buf, ")", &rc);
3476 if( rc==SQLITE_OK ){
3477 rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pDelete, 0);
3479 sqlite3_free(buf.aBuf);
3481 return rc;
3485 ** Formulate and prepare a statement to UPDATE a row from database db.
3486 ** Assuming a table structure like this:
3488 ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
3490 ** The UPDATE statement looks like this:
3492 ** UPDATE x SET
3493 ** a = CASE WHEN ?2 THEN ?3 ELSE a END,
3494 ** b = CASE WHEN ?5 THEN ?6 ELSE b END,
3495 ** c = CASE WHEN ?8 THEN ?9 ELSE c END,
3496 ** d = CASE WHEN ?11 THEN ?12 ELSE d END
3497 ** WHERE a = ?1 AND c = ?7 AND (?13 OR
3498 ** (?5==0 OR b IS ?4) AND (?11==0 OR d IS ?10) AND
3499 ** )
3501 ** For each column in the table, there are three variables to bind:
3503 ** ?(i*3+1) The old.* value of the column, if any.
3504 ** ?(i*3+2) A boolean flag indicating that the value is being modified.
3505 ** ?(i*3+3) The new.* value of the column, if any.
3507 ** Also, a boolean flag that, if set to true, causes the statement to update
3508 ** a row even if the non-PK values do not match. This is required if the
3509 ** conflict-handler is invoked with CHANGESET_DATA and returns
3510 ** CHANGESET_REPLACE. This is variable "?(nCol*3+1)".
3512 ** If successful, SQLITE_OK is returned and SessionApplyCtx.pUpdate is left
3513 ** pointing to the prepared version of the SQL statement.
3515 static int sessionUpdateRow(
3516 sqlite3 *db, /* Database handle */
3517 const char *zTab, /* Table name */
3518 SessionApplyCtx *p /* Session changeset-apply context */
3520 int rc = SQLITE_OK;
3521 int i;
3522 const char *zSep = "";
3523 SessionBuffer buf = {0, 0, 0};
3525 /* Append "UPDATE tbl SET " */
3526 sessionAppendStr(&buf, "UPDATE ", &rc);
3527 sessionAppendIdent(&buf, zTab, &rc);
3528 sessionAppendStr(&buf, " SET ", &rc);
3530 /* Append the assignments */
3531 for(i=0; i<p->nCol; i++){
3532 sessionAppendStr(&buf, zSep, &rc);
3533 sessionAppendIdent(&buf, p->azCol[i], &rc);
3534 sessionAppendStr(&buf, " = CASE WHEN ?", &rc);
3535 sessionAppendInteger(&buf, i*3+2, &rc);
3536 sessionAppendStr(&buf, " THEN ?", &rc);
3537 sessionAppendInteger(&buf, i*3+3, &rc);
3538 sessionAppendStr(&buf, " ELSE ", &rc);
3539 sessionAppendIdent(&buf, p->azCol[i], &rc);
3540 sessionAppendStr(&buf, " END", &rc);
3541 zSep = ", ";
3544 /* Append the PK part of the WHERE clause */
3545 sessionAppendStr(&buf, " WHERE ", &rc);
3546 for(i=0; i<p->nCol; i++){
3547 if( p->abPK[i] ){
3548 sessionAppendIdent(&buf, p->azCol[i], &rc);
3549 sessionAppendStr(&buf, " = ?", &rc);
3550 sessionAppendInteger(&buf, i*3+1, &rc);
3551 sessionAppendStr(&buf, " AND ", &rc);
3555 /* Append the non-PK part of the WHERE clause */
3556 sessionAppendStr(&buf, " (?", &rc);
3557 sessionAppendInteger(&buf, p->nCol*3+1, &rc);
3558 sessionAppendStr(&buf, " OR 1", &rc);
3559 for(i=0; i<p->nCol; i++){
3560 if( !p->abPK[i] ){
3561 sessionAppendStr(&buf, " AND (?", &rc);
3562 sessionAppendInteger(&buf, i*3+2, &rc);
3563 sessionAppendStr(&buf, "=0 OR ", &rc);
3564 sessionAppendIdent(&buf, p->azCol[i], &rc);
3565 sessionAppendStr(&buf, " IS ?", &rc);
3566 sessionAppendInteger(&buf, i*3+1, &rc);
3567 sessionAppendStr(&buf, ")", &rc);
3570 sessionAppendStr(&buf, ")", &rc);
3572 if( rc==SQLITE_OK ){
3573 rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pUpdate, 0);
3575 sqlite3_free(buf.aBuf);
3577 return rc;
3582 ** Formulate and prepare an SQL statement to query table zTab by primary
3583 ** key. Assuming the following table structure:
3585 ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
3587 ** The SELECT statement looks like this:
3589 ** SELECT * FROM x WHERE a = ?1 AND c = ?3
3591 ** If successful, SQLITE_OK is returned and SessionApplyCtx.pSelect is left
3592 ** pointing to the prepared version of the SQL statement.
3594 static int sessionSelectRow(
3595 sqlite3 *db, /* Database handle */
3596 const char *zTab, /* Table name */
3597 SessionApplyCtx *p /* Session changeset-apply context */
3599 return sessionSelectStmt(
3600 db, "main", zTab, p->nCol, p->azCol, p->abPK, &p->pSelect);
3604 ** Formulate and prepare an INSERT statement to add a record to table zTab.
3605 ** For example:
3607 ** INSERT INTO main."zTab" VALUES(?1, ?2, ?3 ...);
3609 ** If successful, SQLITE_OK is returned and SessionApplyCtx.pInsert is left
3610 ** pointing to the prepared version of the SQL statement.
3612 static int sessionInsertRow(
3613 sqlite3 *db, /* Database handle */
3614 const char *zTab, /* Table name */
3615 SessionApplyCtx *p /* Session changeset-apply context */
3617 int rc = SQLITE_OK;
3618 int i;
3619 SessionBuffer buf = {0, 0, 0};
3621 sessionAppendStr(&buf, "INSERT INTO main.", &rc);
3622 sessionAppendIdent(&buf, zTab, &rc);
3623 sessionAppendStr(&buf, "(", &rc);
3624 for(i=0; i<p->nCol; i++){
3625 if( i!=0 ) sessionAppendStr(&buf, ", ", &rc);
3626 sessionAppendIdent(&buf, p->azCol[i], &rc);
3629 sessionAppendStr(&buf, ") VALUES(?", &rc);
3630 for(i=1; i<p->nCol; i++){
3631 sessionAppendStr(&buf, ", ?", &rc);
3633 sessionAppendStr(&buf, ")", &rc);
3635 if( rc==SQLITE_OK ){
3636 rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pInsert, 0);
3638 sqlite3_free(buf.aBuf);
3639 return rc;
3642 static int sessionPrepare(sqlite3 *db, sqlite3_stmt **pp, const char *zSql){
3643 return sqlite3_prepare_v2(db, zSql, -1, pp, 0);
3647 ** Prepare statements for applying changes to the sqlite_stat1 table.
3648 ** These are similar to those created by sessionSelectRow(),
3649 ** sessionInsertRow(), sessionUpdateRow() and sessionDeleteRow() for
3650 ** other tables.
3652 static int sessionStat1Sql(sqlite3 *db, SessionApplyCtx *p){
3653 int rc = sessionSelectRow(db, "sqlite_stat1", p);
3654 if( rc==SQLITE_OK ){
3655 rc = sessionPrepare(db, &p->pInsert,
3656 "INSERT INTO main.sqlite_stat1 VALUES(?1, "
3657 "CASE WHEN length(?2)=0 AND typeof(?2)='blob' THEN NULL ELSE ?2 END, "
3658 "?3)"
3661 if( rc==SQLITE_OK ){
3662 rc = sessionPrepare(db, &p->pUpdate,
3663 "UPDATE main.sqlite_stat1 SET "
3664 "tbl = CASE WHEN ?2 THEN ?3 ELSE tbl END, "
3665 "idx = CASE WHEN ?5 THEN ?6 ELSE idx END, "
3666 "stat = CASE WHEN ?8 THEN ?9 ELSE stat END "
3667 "WHERE tbl=?1 AND idx IS "
3668 "CASE WHEN length(?4)=0 AND typeof(?4)='blob' THEN NULL ELSE ?4 END "
3669 "AND (?10 OR ?8=0 OR stat IS ?7)"
3672 if( rc==SQLITE_OK ){
3673 rc = sessionPrepare(db, &p->pDelete,
3674 "DELETE FROM main.sqlite_stat1 WHERE tbl=?1 AND idx IS "
3675 "CASE WHEN length(?2)=0 AND typeof(?2)='blob' THEN NULL ELSE ?2 END "
3676 "AND (?4 OR stat IS ?3)"
3679 assert( rc==SQLITE_OK );
3680 return rc;
3684 ** A wrapper around sqlite3_bind_value() that detects an extra problem.
3685 ** See comments in the body of this function for details.
3687 static int sessionBindValue(
3688 sqlite3_stmt *pStmt, /* Statement to bind value to */
3689 int i, /* Parameter number to bind to */
3690 sqlite3_value *pVal /* Value to bind */
3692 int eType = sqlite3_value_type(pVal);
3693 /* COVERAGE: The (pVal->z==0) branch is never true using current versions
3694 ** of SQLite. If a malloc fails in an sqlite3_value_xxx() function, either
3695 ** the (pVal->z) variable remains as it was or the type of the value is
3696 ** set to SQLITE_NULL. */
3697 if( (eType==SQLITE_TEXT || eType==SQLITE_BLOB) && pVal->z==0 ){
3698 /* This condition occurs when an earlier OOM in a call to
3699 ** sqlite3_value_text() or sqlite3_value_blob() (perhaps from within
3700 ** a conflict-handler) has zeroed the pVal->z pointer. Return NOMEM. */
3701 return SQLITE_NOMEM;
3703 return sqlite3_bind_value(pStmt, i, pVal);
3707 ** Iterator pIter must point to an SQLITE_INSERT entry. This function
3708 ** transfers new.* values from the current iterator entry to statement
3709 ** pStmt. The table being inserted into has nCol columns.
3711 ** New.* value $i from the iterator is bound to variable ($i+1) of
3712 ** statement pStmt. If parameter abPK is NULL, all values from 0 to (nCol-1)
3713 ** are transfered to the statement. Otherwise, if abPK is not NULL, it points
3714 ** to an array nCol elements in size. In this case only those values for
3715 ** which abPK[$i] is true are read from the iterator and bound to the
3716 ** statement.
3718 ** An SQLite error code is returned if an error occurs. Otherwise, SQLITE_OK.
3720 static int sessionBindRow(
3721 sqlite3_changeset_iter *pIter, /* Iterator to read values from */
3722 int(*xValue)(sqlite3_changeset_iter *, int, sqlite3_value **),
3723 int nCol, /* Number of columns */
3724 u8 *abPK, /* If not NULL, bind only if true */
3725 sqlite3_stmt *pStmt /* Bind values to this statement */
3727 int i;
3728 int rc = SQLITE_OK;
3730 /* Neither sqlite3changeset_old or sqlite3changeset_new can fail if the
3731 ** argument iterator points to a suitable entry. Make sure that xValue
3732 ** is one of these to guarantee that it is safe to ignore the return
3733 ** in the code below. */
3734 assert( xValue==sqlite3changeset_old || xValue==sqlite3changeset_new );
3736 for(i=0; rc==SQLITE_OK && i<nCol; i++){
3737 if( !abPK || abPK[i] ){
3738 sqlite3_value *pVal;
3739 (void)xValue(pIter, i, &pVal);
3740 if( pVal==0 ){
3741 /* The value in the changeset was "undefined". This indicates a
3742 ** corrupt changeset blob. */
3743 rc = SQLITE_CORRUPT_BKPT;
3744 }else{
3745 rc = sessionBindValue(pStmt, i+1, pVal);
3749 return rc;
3753 ** SQL statement pSelect is as generated by the sessionSelectRow() function.
3754 ** This function binds the primary key values from the change that changeset
3755 ** iterator pIter points to to the SELECT and attempts to seek to the table
3756 ** entry. If a row is found, the SELECT statement left pointing at the row
3757 ** and SQLITE_ROW is returned. Otherwise, if no row is found and no error
3758 ** has occured, the statement is reset and SQLITE_OK is returned. If an
3759 ** error occurs, the statement is reset and an SQLite error code is returned.
3761 ** If this function returns SQLITE_ROW, the caller must eventually reset()
3762 ** statement pSelect. If any other value is returned, the statement does
3763 ** not require a reset().
3765 ** If the iterator currently points to an INSERT record, bind values from the
3766 ** new.* record to the SELECT statement. Or, if it points to a DELETE or
3767 ** UPDATE, bind values from the old.* record.
3769 static int sessionSeekToRow(
3770 sqlite3 *db, /* Database handle */
3771 sqlite3_changeset_iter *pIter, /* Changeset iterator */
3772 u8 *abPK, /* Primary key flags array */
3773 sqlite3_stmt *pSelect /* SELECT statement from sessionSelectRow() */
3775 int rc; /* Return code */
3776 int nCol; /* Number of columns in table */
3777 int op; /* Changset operation (SQLITE_UPDATE etc.) */
3778 const char *zDummy; /* Unused */
3780 sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
3781 rc = sessionBindRow(pIter,
3782 op==SQLITE_INSERT ? sqlite3changeset_new : sqlite3changeset_old,
3783 nCol, abPK, pSelect
3786 if( rc==SQLITE_OK ){
3787 rc = sqlite3_step(pSelect);
3788 if( rc!=SQLITE_ROW ) rc = sqlite3_reset(pSelect);
3791 return rc;
3795 ** Invoke the conflict handler for the change that the changeset iterator
3796 ** currently points to.
3798 ** Argument eType must be either CHANGESET_DATA or CHANGESET_CONFLICT.
3799 ** If argument pbReplace is NULL, then the type of conflict handler invoked
3800 ** depends solely on eType, as follows:
3802 ** eType value Value passed to xConflict
3803 ** -------------------------------------------------
3804 ** CHANGESET_DATA CHANGESET_NOTFOUND
3805 ** CHANGESET_CONFLICT CHANGESET_CONSTRAINT
3807 ** Or, if pbReplace is not NULL, then an attempt is made to find an existing
3808 ** record with the same primary key as the record about to be deleted, updated
3809 ** or inserted. If such a record can be found, it is available to the conflict
3810 ** handler as the "conflicting" record. In this case the type of conflict
3811 ** handler invoked is as follows:
3813 ** eType value PK Record found? Value passed to xConflict
3814 ** ----------------------------------------------------------------
3815 ** CHANGESET_DATA Yes CHANGESET_DATA
3816 ** CHANGESET_DATA No CHANGESET_NOTFOUND
3817 ** CHANGESET_CONFLICT Yes CHANGESET_CONFLICT
3818 ** CHANGESET_CONFLICT No CHANGESET_CONSTRAINT
3820 ** If pbReplace is not NULL, and a record with a matching PK is found, and
3821 ** the conflict handler function returns SQLITE_CHANGESET_REPLACE, *pbReplace
3822 ** is set to non-zero before returning SQLITE_OK.
3824 ** If the conflict handler returns SQLITE_CHANGESET_ABORT, SQLITE_ABORT is
3825 ** returned. Or, if the conflict handler returns an invalid value,
3826 ** SQLITE_MISUSE. If the conflict handler returns SQLITE_CHANGESET_OMIT,
3827 ** this function returns SQLITE_OK.
3829 static int sessionConflictHandler(
3830 int eType, /* Either CHANGESET_DATA or CONFLICT */
3831 SessionApplyCtx *p, /* changeset_apply() context */
3832 sqlite3_changeset_iter *pIter, /* Changeset iterator */
3833 int(*xConflict)(void *, int, sqlite3_changeset_iter*),
3834 void *pCtx, /* First argument for conflict handler */
3835 int *pbReplace /* OUT: Set to true if PK row is found */
3837 int res = 0; /* Value returned by conflict handler */
3838 int rc;
3839 int nCol;
3840 int op;
3841 const char *zDummy;
3843 sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
3845 assert( eType==SQLITE_CHANGESET_CONFLICT || eType==SQLITE_CHANGESET_DATA );
3846 assert( SQLITE_CHANGESET_CONFLICT+1==SQLITE_CHANGESET_CONSTRAINT );
3847 assert( SQLITE_CHANGESET_DATA+1==SQLITE_CHANGESET_NOTFOUND );
3849 /* Bind the new.* PRIMARY KEY values to the SELECT statement. */
3850 if( pbReplace ){
3851 rc = sessionSeekToRow(p->db, pIter, p->abPK, p->pSelect);
3852 }else{
3853 rc = SQLITE_OK;
3856 if( rc==SQLITE_ROW ){
3857 /* There exists another row with the new.* primary key. */
3858 pIter->pConflict = p->pSelect;
3859 res = xConflict(pCtx, eType, pIter);
3860 pIter->pConflict = 0;
3861 rc = sqlite3_reset(p->pSelect);
3862 }else if( rc==SQLITE_OK ){
3863 if( p->bDeferConstraints && eType==SQLITE_CHANGESET_CONFLICT ){
3864 /* Instead of invoking the conflict handler, append the change blob
3865 ** to the SessionApplyCtx.constraints buffer. */
3866 u8 *aBlob = &pIter->in.aData[pIter->in.iCurrent];
3867 int nBlob = pIter->in.iNext - pIter->in.iCurrent;
3868 sessionAppendBlob(&p->constraints, aBlob, nBlob, &rc);
3869 res = SQLITE_CHANGESET_OMIT;
3870 }else{
3871 /* No other row with the new.* primary key. */
3872 res = xConflict(pCtx, eType+1, pIter);
3873 if( res==SQLITE_CHANGESET_REPLACE ) rc = SQLITE_MISUSE;
3877 if( rc==SQLITE_OK ){
3878 switch( res ){
3879 case SQLITE_CHANGESET_REPLACE:
3880 assert( pbReplace );
3881 *pbReplace = 1;
3882 break;
3884 case SQLITE_CHANGESET_OMIT:
3885 break;
3887 case SQLITE_CHANGESET_ABORT:
3888 rc = SQLITE_ABORT;
3889 break;
3891 default:
3892 rc = SQLITE_MISUSE;
3893 break;
3897 return rc;
3901 ** Attempt to apply the change that the iterator passed as the first argument
3902 ** currently points to to the database. If a conflict is encountered, invoke
3903 ** the conflict handler callback.
3905 ** If argument pbRetry is NULL, then ignore any CHANGESET_DATA conflict. If
3906 ** one is encountered, update or delete the row with the matching primary key
3907 ** instead. Or, if pbRetry is not NULL and a CHANGESET_DATA conflict occurs,
3908 ** invoke the conflict handler. If it returns CHANGESET_REPLACE, set *pbRetry
3909 ** to true before returning. In this case the caller will invoke this function
3910 ** again, this time with pbRetry set to NULL.
3912 ** If argument pbReplace is NULL and a CHANGESET_CONFLICT conflict is
3913 ** encountered invoke the conflict handler with CHANGESET_CONSTRAINT instead.
3914 ** Or, if pbReplace is not NULL, invoke it with CHANGESET_CONFLICT. If such
3915 ** an invocation returns SQLITE_CHANGESET_REPLACE, set *pbReplace to true
3916 ** before retrying. In this case the caller attempts to remove the conflicting
3917 ** row before invoking this function again, this time with pbReplace set
3918 ** to NULL.
3920 ** If any conflict handler returns SQLITE_CHANGESET_ABORT, this function
3921 ** returns SQLITE_ABORT. Otherwise, if no error occurs, SQLITE_OK is
3922 ** returned.
3924 static int sessionApplyOneOp(
3925 sqlite3_changeset_iter *pIter, /* Changeset iterator */
3926 SessionApplyCtx *p, /* changeset_apply() context */
3927 int(*xConflict)(void *, int, sqlite3_changeset_iter *),
3928 void *pCtx, /* First argument for the conflict handler */
3929 int *pbReplace, /* OUT: True to remove PK row and retry */
3930 int *pbRetry /* OUT: True to retry. */
3932 const char *zDummy;
3933 int op;
3934 int nCol;
3935 int rc = SQLITE_OK;
3937 assert( p->pDelete && p->pUpdate && p->pInsert && p->pSelect );
3938 assert( p->azCol && p->abPK );
3939 assert( !pbReplace || *pbReplace==0 );
3941 sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
3943 if( op==SQLITE_DELETE ){
3945 /* Bind values to the DELETE statement. If conflict handling is required,
3946 ** bind values for all columns and set bound variable (nCol+1) to true.
3947 ** Or, if conflict handling is not required, bind just the PK column
3948 ** values and, if it exists, set (nCol+1) to false. Conflict handling
3949 ** is not required if:
3951 ** * this is a patchset, or
3952 ** * (pbRetry==0), or
3953 ** * all columns of the table are PK columns (in this case there is
3954 ** no (nCol+1) variable to bind to).
3956 u8 *abPK = (pIter->bPatchset ? p->abPK : 0);
3957 rc = sessionBindRow(pIter, sqlite3changeset_old, nCol, abPK, p->pDelete);
3958 if( rc==SQLITE_OK && sqlite3_bind_parameter_count(p->pDelete)>nCol ){
3959 rc = sqlite3_bind_int(p->pDelete, nCol+1, (pbRetry==0 || abPK));
3961 if( rc!=SQLITE_OK ) return rc;
3963 sqlite3_step(p->pDelete);
3964 rc = sqlite3_reset(p->pDelete);
3965 if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
3966 rc = sessionConflictHandler(
3967 SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
3969 }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
3970 rc = sessionConflictHandler(
3971 SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
3975 }else if( op==SQLITE_UPDATE ){
3976 int i;
3978 /* Bind values to the UPDATE statement. */
3979 for(i=0; rc==SQLITE_OK && i<nCol; i++){
3980 sqlite3_value *pOld = sessionChangesetOld(pIter, i);
3981 sqlite3_value *pNew = sessionChangesetNew(pIter, i);
3983 sqlite3_bind_int(p->pUpdate, i*3+2, !!pNew);
3984 if( pOld ){
3985 rc = sessionBindValue(p->pUpdate, i*3+1, pOld);
3987 if( rc==SQLITE_OK && pNew ){
3988 rc = sessionBindValue(p->pUpdate, i*3+3, pNew);
3991 if( rc==SQLITE_OK ){
3992 sqlite3_bind_int(p->pUpdate, nCol*3+1, pbRetry==0 || pIter->bPatchset);
3994 if( rc!=SQLITE_OK ) return rc;
3996 /* Attempt the UPDATE. In the case of a NOTFOUND or DATA conflict,
3997 ** the result will be SQLITE_OK with 0 rows modified. */
3998 sqlite3_step(p->pUpdate);
3999 rc = sqlite3_reset(p->pUpdate);
4001 if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
4002 /* A NOTFOUND or DATA error. Search the table to see if it contains
4003 ** a row with a matching primary key. If so, this is a DATA conflict.
4004 ** Otherwise, if there is no primary key match, it is a NOTFOUND. */
4006 rc = sessionConflictHandler(
4007 SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
4010 }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
4011 /* This is always a CONSTRAINT conflict. */
4012 rc = sessionConflictHandler(
4013 SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
4017 }else{
4018 assert( op==SQLITE_INSERT );
4019 if( p->bStat1 ){
4020 /* Check if there is a conflicting row. For sqlite_stat1, this needs
4021 ** to be done using a SELECT, as there is no PRIMARY KEY in the
4022 ** database schema to throw an exception if a duplicate is inserted. */
4023 rc = sessionSeekToRow(p->db, pIter, p->abPK, p->pSelect);
4024 if( rc==SQLITE_ROW ){
4025 rc = SQLITE_CONSTRAINT;
4026 sqlite3_reset(p->pSelect);
4030 if( rc==SQLITE_OK ){
4031 rc = sessionBindRow(pIter, sqlite3changeset_new, nCol, 0, p->pInsert);
4032 if( rc!=SQLITE_OK ) return rc;
4034 sqlite3_step(p->pInsert);
4035 rc = sqlite3_reset(p->pInsert);
4038 if( (rc&0xff)==SQLITE_CONSTRAINT ){
4039 rc = sessionConflictHandler(
4040 SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, pbReplace
4045 return rc;
4049 ** Attempt to apply the change that the iterator passed as the first argument
4050 ** currently points to to the database. If a conflict is encountered, invoke
4051 ** the conflict handler callback.
4053 ** The difference between this function and sessionApplyOne() is that this
4054 ** function handles the case where the conflict-handler is invoked and
4055 ** returns SQLITE_CHANGESET_REPLACE - indicating that the change should be
4056 ** retried in some manner.
4058 static int sessionApplyOneWithRetry(
4059 sqlite3 *db, /* Apply change to "main" db of this handle */
4060 sqlite3_changeset_iter *pIter, /* Changeset iterator to read change from */
4061 SessionApplyCtx *pApply, /* Apply context */
4062 int(*xConflict)(void*, int, sqlite3_changeset_iter*),
4063 void *pCtx /* First argument passed to xConflict */
4065 int bReplace = 0;
4066 int bRetry = 0;
4067 int rc;
4069 rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, &bReplace, &bRetry);
4070 assert( rc==SQLITE_OK || (bRetry==0 && bReplace==0) );
4072 /* If the bRetry flag is set, the change has not been applied due to an
4073 ** SQLITE_CHANGESET_DATA problem (i.e. this is an UPDATE or DELETE and
4074 ** a row with the correct PK is present in the db, but one or more other
4075 ** fields do not contain the expected values) and the conflict handler
4076 ** returned SQLITE_CHANGESET_REPLACE. In this case retry the operation,
4077 ** but pass NULL as the final argument so that sessionApplyOneOp() ignores
4078 ** the SQLITE_CHANGESET_DATA problem. */
4079 if( bRetry ){
4080 assert( pIter->op==SQLITE_UPDATE || pIter->op==SQLITE_DELETE );
4081 rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
4084 /* If the bReplace flag is set, the change is an INSERT that has not
4085 ** been performed because the database already contains a row with the
4086 ** specified primary key and the conflict handler returned
4087 ** SQLITE_CHANGESET_REPLACE. In this case remove the conflicting row
4088 ** before reattempting the INSERT. */
4089 else if( bReplace ){
4090 assert( pIter->op==SQLITE_INSERT );
4091 rc = sqlite3_exec(db, "SAVEPOINT replace_op", 0, 0, 0);
4092 if( rc==SQLITE_OK ){
4093 rc = sessionBindRow(pIter,
4094 sqlite3changeset_new, pApply->nCol, pApply->abPK, pApply->pDelete);
4095 sqlite3_bind_int(pApply->pDelete, pApply->nCol+1, 1);
4097 if( rc==SQLITE_OK ){
4098 sqlite3_step(pApply->pDelete);
4099 rc = sqlite3_reset(pApply->pDelete);
4101 if( rc==SQLITE_OK ){
4102 rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
4104 if( rc==SQLITE_OK ){
4105 rc = sqlite3_exec(db, "RELEASE replace_op", 0, 0, 0);
4109 return rc;
4113 ** Retry the changes accumulated in the pApply->constraints buffer.
4115 static int sessionRetryConstraints(
4116 sqlite3 *db,
4117 int bPatchset,
4118 const char *zTab,
4119 SessionApplyCtx *pApply,
4120 int(*xConflict)(void*, int, sqlite3_changeset_iter*),
4121 void *pCtx /* First argument passed to xConflict */
4123 int rc = SQLITE_OK;
4125 while( pApply->constraints.nBuf ){
4126 sqlite3_changeset_iter *pIter2 = 0;
4127 SessionBuffer cons = pApply->constraints;
4128 memset(&pApply->constraints, 0, sizeof(SessionBuffer));
4130 rc = sessionChangesetStart(&pIter2, 0, 0, cons.nBuf, cons.aBuf);
4131 if( rc==SQLITE_OK ){
4132 int nByte = 2*pApply->nCol*sizeof(sqlite3_value*);
4133 int rc2;
4134 pIter2->bPatchset = bPatchset;
4135 pIter2->zTab = (char*)zTab;
4136 pIter2->nCol = pApply->nCol;
4137 pIter2->abPK = pApply->abPK;
4138 sessionBufferGrow(&pIter2->tblhdr, nByte, &rc);
4139 pIter2->apValue = (sqlite3_value**)pIter2->tblhdr.aBuf;
4140 if( rc==SQLITE_OK ) memset(pIter2->apValue, 0, nByte);
4142 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter2) ){
4143 rc = sessionApplyOneWithRetry(db, pIter2, pApply, xConflict, pCtx);
4146 rc2 = sqlite3changeset_finalize(pIter2);
4147 if( rc==SQLITE_OK ) rc = rc2;
4149 assert( pApply->bDeferConstraints || pApply->constraints.nBuf==0 );
4151 sqlite3_free(cons.aBuf);
4152 if( rc!=SQLITE_OK ) break;
4153 if( pApply->constraints.nBuf>=cons.nBuf ){
4154 /* No progress was made on the last round. */
4155 pApply->bDeferConstraints = 0;
4159 return rc;
4163 ** Argument pIter is a changeset iterator that has been initialized, but
4164 ** not yet passed to sqlite3changeset_next(). This function applies the
4165 ** changeset to the main database attached to handle "db". The supplied
4166 ** conflict handler callback is invoked to resolve any conflicts encountered
4167 ** while applying the change.
4169 static int sessionChangesetApply(
4170 sqlite3 *db, /* Apply change to "main" db of this handle */
4171 sqlite3_changeset_iter *pIter, /* Changeset to apply */
4172 int(*xFilter)(
4173 void *pCtx, /* Copy of sixth arg to _apply() */
4174 const char *zTab /* Table name */
4176 int(*xConflict)(
4177 void *pCtx, /* Copy of fifth arg to _apply() */
4178 int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
4179 sqlite3_changeset_iter *p /* Handle describing change and conflict */
4181 void *pCtx /* First argument passed to xConflict */
4183 int schemaMismatch = 0;
4184 int rc; /* Return code */
4185 const char *zTab = 0; /* Name of current table */
4186 int nTab = 0; /* Result of sqlite3Strlen30(zTab) */
4187 SessionApplyCtx sApply; /* changeset_apply() context object */
4188 int bPatchset;
4190 assert( xConflict!=0 );
4192 pIter->in.bNoDiscard = 1;
4193 memset(&sApply, 0, sizeof(sApply));
4194 sqlite3_mutex_enter(sqlite3_db_mutex(db));
4195 rc = sqlite3_exec(db, "SAVEPOINT changeset_apply", 0, 0, 0);
4196 if( rc==SQLITE_OK ){
4197 rc = sqlite3_exec(db, "PRAGMA defer_foreign_keys = 1", 0, 0, 0);
4199 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter) ){
4200 int nCol;
4201 int op;
4202 const char *zNew;
4204 sqlite3changeset_op(pIter, &zNew, &nCol, &op, 0);
4206 if( zTab==0 || sqlite3_strnicmp(zNew, zTab, nTab+1) ){
4207 u8 *abPK;
4209 rc = sessionRetryConstraints(
4210 db, pIter->bPatchset, zTab, &sApply, xConflict, pCtx
4212 if( rc!=SQLITE_OK ) break;
4214 sqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */
4215 sqlite3_finalize(sApply.pDelete);
4216 sqlite3_finalize(sApply.pUpdate);
4217 sqlite3_finalize(sApply.pInsert);
4218 sqlite3_finalize(sApply.pSelect);
4219 memset(&sApply, 0, sizeof(sApply));
4220 sApply.db = db;
4221 sApply.bDeferConstraints = 1;
4223 /* If an xFilter() callback was specified, invoke it now. If the
4224 ** xFilter callback returns zero, skip this table. If it returns
4225 ** non-zero, proceed. */
4226 schemaMismatch = (xFilter && (0==xFilter(pCtx, zNew)));
4227 if( schemaMismatch ){
4228 zTab = sqlite3_mprintf("%s", zNew);
4229 if( zTab==0 ){
4230 rc = SQLITE_NOMEM;
4231 break;
4233 nTab = (int)strlen(zTab);
4234 sApply.azCol = (const char **)zTab;
4235 }else{
4236 int nMinCol = 0;
4237 int i;
4239 sqlite3changeset_pk(pIter, &abPK, 0);
4240 rc = sessionTableInfo(
4241 db, "main", zNew, &sApply.nCol, &zTab, &sApply.azCol, &sApply.abPK
4243 if( rc!=SQLITE_OK ) break;
4244 for(i=0; i<sApply.nCol; i++){
4245 if( sApply.abPK[i] ) nMinCol = i+1;
4248 if( sApply.nCol==0 ){
4249 schemaMismatch = 1;
4250 sqlite3_log(SQLITE_SCHEMA,
4251 "sqlite3changeset_apply(): no such table: %s", zTab
4254 else if( sApply.nCol<nCol ){
4255 schemaMismatch = 1;
4256 sqlite3_log(SQLITE_SCHEMA,
4257 "sqlite3changeset_apply(): table %s has %d columns, "
4258 "expected %d or more",
4259 zTab, sApply.nCol, nCol
4262 else if( nCol<nMinCol || memcmp(sApply.abPK, abPK, nCol)!=0 ){
4263 schemaMismatch = 1;
4264 sqlite3_log(SQLITE_SCHEMA, "sqlite3changeset_apply(): "
4265 "primary key mismatch for table %s", zTab
4268 else{
4269 sApply.nCol = nCol;
4270 if( 0==sqlite3_stricmp(zTab, "sqlite_stat1") ){
4271 if( (rc = sessionStat1Sql(db, &sApply) ) ){
4272 break;
4274 sApply.bStat1 = 1;
4275 }else{
4276 if((rc = sessionSelectRow(db, zTab, &sApply))
4277 || (rc = sessionUpdateRow(db, zTab, &sApply))
4278 || (rc = sessionDeleteRow(db, zTab, &sApply))
4279 || (rc = sessionInsertRow(db, zTab, &sApply))
4281 break;
4283 sApply.bStat1 = 0;
4286 nTab = sqlite3Strlen30(zTab);
4290 /* If there is a schema mismatch on the current table, proceed to the
4291 ** next change. A log message has already been issued. */
4292 if( schemaMismatch ) continue;
4294 rc = sessionApplyOneWithRetry(db, pIter, &sApply, xConflict, pCtx);
4297 bPatchset = pIter->bPatchset;
4298 if( rc==SQLITE_OK ){
4299 rc = sqlite3changeset_finalize(pIter);
4300 }else{
4301 sqlite3changeset_finalize(pIter);
4304 if( rc==SQLITE_OK ){
4305 rc = sessionRetryConstraints(db, bPatchset, zTab, &sApply, xConflict, pCtx);
4308 if( rc==SQLITE_OK ){
4309 int nFk, notUsed;
4310 sqlite3_db_status(db, SQLITE_DBSTATUS_DEFERRED_FKS, &nFk, &notUsed, 0);
4311 if( nFk!=0 ){
4312 int res = SQLITE_CHANGESET_ABORT;
4313 sqlite3_changeset_iter sIter;
4314 memset(&sIter, 0, sizeof(sIter));
4315 sIter.nCol = nFk;
4316 res = xConflict(pCtx, SQLITE_CHANGESET_FOREIGN_KEY, &sIter);
4317 if( res!=SQLITE_CHANGESET_OMIT ){
4318 rc = SQLITE_CONSTRAINT;
4322 sqlite3_exec(db, "PRAGMA defer_foreign_keys = 0", 0, 0, 0);
4324 if( rc==SQLITE_OK ){
4325 rc = sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
4326 }else{
4327 sqlite3_exec(db, "ROLLBACK TO changeset_apply", 0, 0, 0);
4328 sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
4331 sqlite3_finalize(sApply.pInsert);
4332 sqlite3_finalize(sApply.pDelete);
4333 sqlite3_finalize(sApply.pUpdate);
4334 sqlite3_finalize(sApply.pSelect);
4335 sqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */
4336 sqlite3_free((char*)sApply.constraints.aBuf);
4337 sqlite3_mutex_leave(sqlite3_db_mutex(db));
4338 return rc;
4342 ** Apply the changeset passed via pChangeset/nChangeset to the main database
4343 ** attached to handle "db". Invoke the supplied conflict handler callback
4344 ** to resolve any conflicts encountered while applying the change.
4346 int sqlite3changeset_apply(
4347 sqlite3 *db, /* Apply change to "main" db of this handle */
4348 int nChangeset, /* Size of changeset in bytes */
4349 void *pChangeset, /* Changeset blob */
4350 int(*xFilter)(
4351 void *pCtx, /* Copy of sixth arg to _apply() */
4352 const char *zTab /* Table name */
4354 int(*xConflict)(
4355 void *pCtx, /* Copy of fifth arg to _apply() */
4356 int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
4357 sqlite3_changeset_iter *p /* Handle describing change and conflict */
4359 void *pCtx /* First argument passed to xConflict */
4361 sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */
4362 int rc = sqlite3changeset_start(&pIter, nChangeset, pChangeset);
4363 if( rc==SQLITE_OK ){
4364 rc = sessionChangesetApply(db, pIter, xFilter, xConflict, pCtx);
4366 return rc;
4370 ** Apply the changeset passed via xInput/pIn to the main database
4371 ** attached to handle "db". Invoke the supplied conflict handler callback
4372 ** to resolve any conflicts encountered while applying the change.
4374 int sqlite3changeset_apply_strm(
4375 sqlite3 *db, /* Apply change to "main" db of this handle */
4376 int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
4377 void *pIn, /* First arg for xInput */
4378 int(*xFilter)(
4379 void *pCtx, /* Copy of sixth arg to _apply() */
4380 const char *zTab /* Table name */
4382 int(*xConflict)(
4383 void *pCtx, /* Copy of sixth arg to _apply() */
4384 int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
4385 sqlite3_changeset_iter *p /* Handle describing change and conflict */
4387 void *pCtx /* First argument passed to xConflict */
4389 sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */
4390 int rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
4391 if( rc==SQLITE_OK ){
4392 rc = sessionChangesetApply(db, pIter, xFilter, xConflict, pCtx);
4394 return rc;
4398 ** sqlite3_changegroup handle.
4400 struct sqlite3_changegroup {
4401 int rc; /* Error code */
4402 int bPatch; /* True to accumulate patchsets */
4403 SessionTable *pList; /* List of tables in current patch */
4407 ** This function is called to merge two changes to the same row together as
4408 ** part of an sqlite3changeset_concat() operation. A new change object is
4409 ** allocated and a pointer to it stored in *ppNew.
4411 static int sessionChangeMerge(
4412 SessionTable *pTab, /* Table structure */
4413 int bPatchset, /* True for patchsets */
4414 SessionChange *pExist, /* Existing change */
4415 int op2, /* Second change operation */
4416 int bIndirect, /* True if second change is indirect */
4417 u8 *aRec, /* Second change record */
4418 int nRec, /* Number of bytes in aRec */
4419 SessionChange **ppNew /* OUT: Merged change */
4421 SessionChange *pNew = 0;
4423 if( !pExist ){
4424 pNew = (SessionChange *)sqlite3_malloc(sizeof(SessionChange) + nRec);
4425 if( !pNew ){
4426 return SQLITE_NOMEM;
4428 memset(pNew, 0, sizeof(SessionChange));
4429 pNew->op = op2;
4430 pNew->bIndirect = bIndirect;
4431 pNew->nRecord = nRec;
4432 pNew->aRecord = (u8*)&pNew[1];
4433 memcpy(pNew->aRecord, aRec, nRec);
4434 }else{
4435 int op1 = pExist->op;
4438 ** op1=INSERT, op2=INSERT -> Unsupported. Discard op2.
4439 ** op1=INSERT, op2=UPDATE -> INSERT.
4440 ** op1=INSERT, op2=DELETE -> (none)
4442 ** op1=UPDATE, op2=INSERT -> Unsupported. Discard op2.
4443 ** op1=UPDATE, op2=UPDATE -> UPDATE.
4444 ** op1=UPDATE, op2=DELETE -> DELETE.
4446 ** op1=DELETE, op2=INSERT -> UPDATE.
4447 ** op1=DELETE, op2=UPDATE -> Unsupported. Discard op2.
4448 ** op1=DELETE, op2=DELETE -> Unsupported. Discard op2.
4450 if( (op1==SQLITE_INSERT && op2==SQLITE_INSERT)
4451 || (op1==SQLITE_UPDATE && op2==SQLITE_INSERT)
4452 || (op1==SQLITE_DELETE && op2==SQLITE_UPDATE)
4453 || (op1==SQLITE_DELETE && op2==SQLITE_DELETE)
4455 pNew = pExist;
4456 }else if( op1==SQLITE_INSERT && op2==SQLITE_DELETE ){
4457 sqlite3_free(pExist);
4458 assert( pNew==0 );
4459 }else{
4460 u8 *aExist = pExist->aRecord;
4461 int nByte;
4462 u8 *aCsr;
4464 /* Allocate a new SessionChange object. Ensure that the aRecord[]
4465 ** buffer of the new object is large enough to hold any record that
4466 ** may be generated by combining the input records. */
4467 nByte = sizeof(SessionChange) + pExist->nRecord + nRec;
4468 pNew = (SessionChange *)sqlite3_malloc(nByte);
4469 if( !pNew ){
4470 sqlite3_free(pExist);
4471 return SQLITE_NOMEM;
4473 memset(pNew, 0, sizeof(SessionChange));
4474 pNew->bIndirect = (bIndirect && pExist->bIndirect);
4475 aCsr = pNew->aRecord = (u8 *)&pNew[1];
4477 if( op1==SQLITE_INSERT ){ /* INSERT + UPDATE */
4478 u8 *a1 = aRec;
4479 assert( op2==SQLITE_UPDATE );
4480 pNew->op = SQLITE_INSERT;
4481 if( bPatchset==0 ) sessionSkipRecord(&a1, pTab->nCol);
4482 sessionMergeRecord(&aCsr, pTab->nCol, aExist, a1);
4483 }else if( op1==SQLITE_DELETE ){ /* DELETE + INSERT */
4484 assert( op2==SQLITE_INSERT );
4485 pNew->op = SQLITE_UPDATE;
4486 if( bPatchset ){
4487 memcpy(aCsr, aRec, nRec);
4488 aCsr += nRec;
4489 }else{
4490 if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aExist, 0,aRec,0) ){
4491 sqlite3_free(pNew);
4492 pNew = 0;
4495 }else if( op2==SQLITE_UPDATE ){ /* UPDATE + UPDATE */
4496 u8 *a1 = aExist;
4497 u8 *a2 = aRec;
4498 assert( op1==SQLITE_UPDATE );
4499 if( bPatchset==0 ){
4500 sessionSkipRecord(&a1, pTab->nCol);
4501 sessionSkipRecord(&a2, pTab->nCol);
4503 pNew->op = SQLITE_UPDATE;
4504 if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aRec, aExist,a1,a2) ){
4505 sqlite3_free(pNew);
4506 pNew = 0;
4508 }else{ /* UPDATE + DELETE */
4509 assert( op1==SQLITE_UPDATE && op2==SQLITE_DELETE );
4510 pNew->op = SQLITE_DELETE;
4511 if( bPatchset ){
4512 memcpy(aCsr, aRec, nRec);
4513 aCsr += nRec;
4514 }else{
4515 sessionMergeRecord(&aCsr, pTab->nCol, aRec, aExist);
4519 if( pNew ){
4520 pNew->nRecord = (int)(aCsr - pNew->aRecord);
4522 sqlite3_free(pExist);
4526 *ppNew = pNew;
4527 return SQLITE_OK;
4531 ** Add all changes in the changeset traversed by the iterator passed as
4532 ** the first argument to the changegroup hash tables.
4534 static int sessionChangesetToHash(
4535 sqlite3_changeset_iter *pIter, /* Iterator to read from */
4536 sqlite3_changegroup *pGrp /* Changegroup object to add changeset to */
4538 u8 *aRec;
4539 int nRec;
4540 int rc = SQLITE_OK;
4541 SessionTable *pTab = 0;
4544 while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec) ){
4545 const char *zNew;
4546 int nCol;
4547 int op;
4548 int iHash;
4549 int bIndirect;
4550 SessionChange *pChange;
4551 SessionChange *pExist = 0;
4552 SessionChange **pp;
4554 if( pGrp->pList==0 ){
4555 pGrp->bPatch = pIter->bPatchset;
4556 }else if( pIter->bPatchset!=pGrp->bPatch ){
4557 rc = SQLITE_ERROR;
4558 break;
4561 sqlite3changeset_op(pIter, &zNew, &nCol, &op, &bIndirect);
4562 if( !pTab || sqlite3_stricmp(zNew, pTab->zName) ){
4563 /* Search the list for a matching table */
4564 int nNew = (int)strlen(zNew);
4565 u8 *abPK;
4567 sqlite3changeset_pk(pIter, &abPK, 0);
4568 for(pTab = pGrp->pList; pTab; pTab=pTab->pNext){
4569 if( 0==sqlite3_strnicmp(pTab->zName, zNew, nNew+1) ) break;
4571 if( !pTab ){
4572 SessionTable **ppTab;
4574 pTab = sqlite3_malloc(sizeof(SessionTable) + nCol + nNew+1);
4575 if( !pTab ){
4576 rc = SQLITE_NOMEM;
4577 break;
4579 memset(pTab, 0, sizeof(SessionTable));
4580 pTab->nCol = nCol;
4581 pTab->abPK = (u8*)&pTab[1];
4582 memcpy(pTab->abPK, abPK, nCol);
4583 pTab->zName = (char*)&pTab->abPK[nCol];
4584 memcpy(pTab->zName, zNew, nNew+1);
4586 /* The new object must be linked on to the end of the list, not
4587 ** simply added to the start of it. This is to ensure that the
4588 ** tables within the output of sqlite3changegroup_output() are in
4589 ** the right order. */
4590 for(ppTab=&pGrp->pList; *ppTab; ppTab=&(*ppTab)->pNext);
4591 *ppTab = pTab;
4592 }else if( pTab->nCol!=nCol || memcmp(pTab->abPK, abPK, nCol) ){
4593 rc = SQLITE_SCHEMA;
4594 break;
4598 if( sessionGrowHash(pIter->bPatchset, pTab) ){
4599 rc = SQLITE_NOMEM;
4600 break;
4602 iHash = sessionChangeHash(
4603 pTab, (pIter->bPatchset && op==SQLITE_DELETE), aRec, pTab->nChange
4606 /* Search for existing entry. If found, remove it from the hash table.
4607 ** Code below may link it back in.
4609 for(pp=&pTab->apChange[iHash]; *pp; pp=&(*pp)->pNext){
4610 int bPkOnly1 = 0;
4611 int bPkOnly2 = 0;
4612 if( pIter->bPatchset ){
4613 bPkOnly1 = (*pp)->op==SQLITE_DELETE;
4614 bPkOnly2 = op==SQLITE_DELETE;
4616 if( sessionChangeEqual(pTab, bPkOnly1, (*pp)->aRecord, bPkOnly2, aRec) ){
4617 pExist = *pp;
4618 *pp = (*pp)->pNext;
4619 pTab->nEntry--;
4620 break;
4624 rc = sessionChangeMerge(pTab,
4625 pIter->bPatchset, pExist, op, bIndirect, aRec, nRec, &pChange
4627 if( rc ) break;
4628 if( pChange ){
4629 pChange->pNext = pTab->apChange[iHash];
4630 pTab->apChange[iHash] = pChange;
4631 pTab->nEntry++;
4635 if( rc==SQLITE_OK ) rc = pIter->rc;
4636 return rc;
4640 ** Serialize a changeset (or patchset) based on all changesets (or patchsets)
4641 ** added to the changegroup object passed as the first argument.
4643 ** If xOutput is not NULL, then the changeset/patchset is returned to the
4644 ** user via one or more calls to xOutput, as with the other streaming
4645 ** interfaces.
4647 ** Or, if xOutput is NULL, then (*ppOut) is populated with a pointer to a
4648 ** buffer containing the output changeset before this function returns. In
4649 ** this case (*pnOut) is set to the size of the output buffer in bytes. It
4650 ** is the responsibility of the caller to free the output buffer using
4651 ** sqlite3_free() when it is no longer required.
4653 ** If successful, SQLITE_OK is returned. Or, if an error occurs, an SQLite
4654 ** error code. If an error occurs and xOutput is NULL, (*ppOut) and (*pnOut)
4655 ** are both set to 0 before returning.
4657 static int sessionChangegroupOutput(
4658 sqlite3_changegroup *pGrp,
4659 int (*xOutput)(void *pOut, const void *pData, int nData),
4660 void *pOut,
4661 int *pnOut,
4662 void **ppOut
4664 int rc = SQLITE_OK;
4665 SessionBuffer buf = {0, 0, 0};
4666 SessionTable *pTab;
4667 assert( xOutput==0 || (ppOut==0 && pnOut==0) );
4669 /* Create the serialized output changeset based on the contents of the
4670 ** hash tables attached to the SessionTable objects in list p->pList.
4672 for(pTab=pGrp->pList; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
4673 int i;
4674 if( pTab->nEntry==0 ) continue;
4676 sessionAppendTableHdr(&buf, pGrp->bPatch, pTab, &rc);
4677 for(i=0; i<pTab->nChange; i++){
4678 SessionChange *p;
4679 for(p=pTab->apChange[i]; p; p=p->pNext){
4680 sessionAppendByte(&buf, p->op, &rc);
4681 sessionAppendByte(&buf, p->bIndirect, &rc);
4682 sessionAppendBlob(&buf, p->aRecord, p->nRecord, &rc);
4686 if( rc==SQLITE_OK && xOutput && buf.nBuf>=SESSIONS_STRM_CHUNK_SIZE ){
4687 rc = xOutput(pOut, buf.aBuf, buf.nBuf);
4688 buf.nBuf = 0;
4692 if( rc==SQLITE_OK ){
4693 if( xOutput ){
4694 if( buf.nBuf>0 ) rc = xOutput(pOut, buf.aBuf, buf.nBuf);
4695 }else{
4696 *ppOut = buf.aBuf;
4697 *pnOut = buf.nBuf;
4698 buf.aBuf = 0;
4701 sqlite3_free(buf.aBuf);
4703 return rc;
4707 ** Allocate a new, empty, sqlite3_changegroup.
4709 int sqlite3changegroup_new(sqlite3_changegroup **pp){
4710 int rc = SQLITE_OK; /* Return code */
4711 sqlite3_changegroup *p; /* New object */
4712 p = (sqlite3_changegroup*)sqlite3_malloc(sizeof(sqlite3_changegroup));
4713 if( p==0 ){
4714 rc = SQLITE_NOMEM;
4715 }else{
4716 memset(p, 0, sizeof(sqlite3_changegroup));
4718 *pp = p;
4719 return rc;
4723 ** Add the changeset currently stored in buffer pData, size nData bytes,
4724 ** to changeset-group p.
4726 int sqlite3changegroup_add(sqlite3_changegroup *pGrp, int nData, void *pData){
4727 sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */
4728 int rc; /* Return code */
4730 rc = sqlite3changeset_start(&pIter, nData, pData);
4731 if( rc==SQLITE_OK ){
4732 rc = sessionChangesetToHash(pIter, pGrp);
4734 sqlite3changeset_finalize(pIter);
4735 return rc;
4739 ** Obtain a buffer containing a changeset representing the concatenation
4740 ** of all changesets added to the group so far.
4742 int sqlite3changegroup_output(
4743 sqlite3_changegroup *pGrp,
4744 int *pnData,
4745 void **ppData
4747 return sessionChangegroupOutput(pGrp, 0, 0, pnData, ppData);
4751 ** Streaming versions of changegroup_add().
4753 int sqlite3changegroup_add_strm(
4754 sqlite3_changegroup *pGrp,
4755 int (*xInput)(void *pIn, void *pData, int *pnData),
4756 void *pIn
4758 sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */
4759 int rc; /* Return code */
4761 rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
4762 if( rc==SQLITE_OK ){
4763 rc = sessionChangesetToHash(pIter, pGrp);
4765 sqlite3changeset_finalize(pIter);
4766 return rc;
4770 ** Streaming versions of changegroup_output().
4772 int sqlite3changegroup_output_strm(
4773 sqlite3_changegroup *pGrp,
4774 int (*xOutput)(void *pOut, const void *pData, int nData),
4775 void *pOut
4777 return sessionChangegroupOutput(pGrp, xOutput, pOut, 0, 0);
4781 ** Delete a changegroup object.
4783 void sqlite3changegroup_delete(sqlite3_changegroup *pGrp){
4784 if( pGrp ){
4785 sessionDeleteTable(pGrp->pList);
4786 sqlite3_free(pGrp);
4791 ** Combine two changesets together.
4793 int sqlite3changeset_concat(
4794 int nLeft, /* Number of bytes in lhs input */
4795 void *pLeft, /* Lhs input changeset */
4796 int nRight /* Number of bytes in rhs input */,
4797 void *pRight, /* Rhs input changeset */
4798 int *pnOut, /* OUT: Number of bytes in output changeset */
4799 void **ppOut /* OUT: changeset (left <concat> right) */
4801 sqlite3_changegroup *pGrp;
4802 int rc;
4804 rc = sqlite3changegroup_new(&pGrp);
4805 if( rc==SQLITE_OK ){
4806 rc = sqlite3changegroup_add(pGrp, nLeft, pLeft);
4808 if( rc==SQLITE_OK ){
4809 rc = sqlite3changegroup_add(pGrp, nRight, pRight);
4811 if( rc==SQLITE_OK ){
4812 rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
4814 sqlite3changegroup_delete(pGrp);
4816 return rc;
4820 ** Streaming version of sqlite3changeset_concat().
4822 int sqlite3changeset_concat_strm(
4823 int (*xInputA)(void *pIn, void *pData, int *pnData),
4824 void *pInA,
4825 int (*xInputB)(void *pIn, void *pData, int *pnData),
4826 void *pInB,
4827 int (*xOutput)(void *pOut, const void *pData, int nData),
4828 void *pOut
4830 sqlite3_changegroup *pGrp;
4831 int rc;
4833 rc = sqlite3changegroup_new(&pGrp);
4834 if( rc==SQLITE_OK ){
4835 rc = sqlite3changegroup_add_strm(pGrp, xInputA, pInA);
4837 if( rc==SQLITE_OK ){
4838 rc = sqlite3changegroup_add_strm(pGrp, xInputB, pInB);
4840 if( rc==SQLITE_OK ){
4841 rc = sqlite3changegroup_output_strm(pGrp, xOutput, pOut);
4843 sqlite3changegroup_delete(pGrp);
4845 return rc;
4848 #endif /* SQLITE_ENABLE_SESSION && SQLITE_ENABLE_PREUPDATE_HOOK */