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