sqlite
[Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI.
Brought by drakestapleton
sqlite / ext / session / sqlite3session.c
| 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 | #define SESSIONS_ROWID "_rowid_" |
| 29 | |
| 30 | static int sessions_strm_chunk_size = SESSIONS_STRM_CHUNK_SIZE; |
| 31 | |
| 32 | typedef struct SessionHook SessionHook; |
| 33 | struct SessionHook { |
| 34 | void *pCtx; |
| 35 | int (*xOld)(void*,int,sqlite3_value**); |
| 36 | int (*xNew)(void*,int,sqlite3_value**); |
| 37 | int (*xCount)(void*); |
| 38 | int (*xDepth)(void*); |
| 39 | }; |
| 40 | |
| 41 | /* |
| 42 | ** Session handle structure. |
| 43 | */ |
| 44 | struct sqlite3_session { |
| 45 | sqlite3 *db; /* Database handle session is attached to */ |
| 46 | char *zDb; /* Name of database session is attached to */ |
| 47 | int bEnableSize; /* True if changeset_size() enabled */ |
| 48 | int bEnable; /* True if currently recording */ |
| 49 | int bIndirect; /* True if all changes are indirect */ |
| 50 | int bAutoAttach; /* True to auto-attach tables */ |
| 51 | int bImplicitPK; /* True to handle tables with implicit PK */ |
| 52 | int rc; /* Non-zero if an error has occurred */ |
| 53 | void *pFilterCtx; /* First argument to pass to xTableFilter */ |
| 54 | int (*xTableFilter)(void *pCtx, const char *zTab); |
| 55 | i64 nMalloc; /* Number of bytes of data allocated */ |
| 56 | i64 nMaxChangesetSize; |
| 57 | sqlite3_value *pZeroBlob; /* Value containing X'' */ |
| 58 | sqlite3_session *pNext; /* Next session object on same db. */ |
| 59 | SessionTable *pTable; /* List of attached tables */ |
| 60 | SessionHook hook; /* APIs to grab new and old data with */ |
| 61 | }; |
| 62 | |
| 63 | /* |
| 64 | ** Instances of this structure are used to build strings or binary records. |
| 65 | */ |
| 66 | struct SessionBuffer { |
| 67 | u8 *aBuf; /* Pointer to changeset buffer */ |
| 68 | int nBuf; /* Size of buffer aBuf */ |
| 69 | int nAlloc; /* Size of allocation containing aBuf */ |
| 70 | }; |
| 71 | |
| 72 | /* |
| 73 | ** An object of this type is used internally as an abstraction for |
| 74 | ** input data. Input data may be supplied either as a single large buffer |
| 75 | ** (e.g. sqlite3changeset_start()) or using a stream function (e.g. |
| 76 | ** sqlite3changeset_start_strm()). |
| 77 | ** |
| 78 | ** bNoDiscard: |
| 79 | ** If true, then the only time data is discarded is as a result of explicit |
| 80 | ** sessionDiscardData() calls. Not within every sessionInputBuffer() call. |
| 81 | */ |
| 82 | struct SessionInput { |
| 83 | int bNoDiscard; /* If true, do not discard in InputBuffer() */ |
| 84 | int iCurrent; /* Offset in aData[] of current change */ |
| 85 | int iNext; /* Offset in aData[] of next change */ |
| 86 | u8 *aData; /* Pointer to buffer containing changeset */ |
| 87 | int nData; /* Number of bytes in aData */ |
| 88 | |
| 89 | SessionBuffer buf; /* Current read buffer */ |
| 90 | int (*xInput)(void*, void*, int*); /* Input stream call (or NULL) */ |
| 91 | void *pIn; /* First argument to xInput */ |
| 92 | int bEof; /* Set to true after xInput finished */ |
| 93 | }; |
| 94 | |
| 95 | /* |
| 96 | ** Structure for changeset iterators. |
| 97 | */ |
| 98 | struct sqlite3_changeset_iter { |
| 99 | SessionInput in; /* Input buffer or stream */ |
| 100 | SessionBuffer tblhdr; /* Buffer to hold apValue/zTab/abPK/ */ |
| 101 | int bPatchset; /* True if this is a patchset */ |
| 102 | int bInvert; /* True to invert changeset */ |
| 103 | int bSkipEmpty; /* Skip noop UPDATE changes */ |
| 104 | int rc; /* Iterator error code */ |
| 105 | sqlite3_stmt *pConflict; /* Points to conflicting row, if any */ |
| 106 | char *zTab; /* Current table */ |
| 107 | int nCol; /* Number of columns in zTab */ |
| 108 | int op; /* Current operation */ |
| 109 | int bIndirect; /* True if current change was indirect */ |
| 110 | u8 *abPK; /* Primary key array */ |
| 111 | sqlite3_value **apValue; /* old.* and new.* values */ |
| 112 | }; |
| 113 | |
| 114 | /* |
| 115 | ** Each session object maintains a set of the following structures, one |
| 116 | ** for each table the session object is monitoring. The structures are |
| 117 | ** stored in a linked list starting at sqlite3_session.pTable. |
| 118 | ** |
| 119 | ** The keys of the SessionTable.aChange[] hash table are all rows that have |
| 120 | ** been modified in any way since the session object was attached to the |
| 121 | ** table. |
| 122 | ** |
| 123 | ** The data associated with each hash-table entry is a structure containing |
| 124 | ** a subset of the initial values that the modified row contained at the |
| 125 | ** start of the session. Or no initial values if the row was inserted. |
| 126 | ** |
| 127 | ** pDfltStmt: |
| 128 | ** This is only used by the sqlite3changegroup_xxx() APIs, not by |
| 129 | ** regular sqlite3_session objects. It is a SELECT statement that |
| 130 | ** selects the default value for each table column. For example, |
| 131 | ** if the table is |
| 132 | ** |
| 133 | ** CREATE TABLE xx(a DEFAULT 1, b, c DEFAULT 'abc') |
| 134 | ** |
| 135 | ** then this variable is the compiled version of: |
| 136 | ** |
| 137 | ** SELECT 1, NULL, 'abc' |
| 138 | */ |
| 139 | struct SessionTable { |
| 140 | SessionTable *pNext; |
| 141 | char *zName; /* Local name of table */ |
| 142 | int nCol; /* Number of non-hidden columns */ |
| 143 | int nTotalCol; /* Number of columns including hidden */ |
| 144 | int bStat1; /* True if this is sqlite_stat1 */ |
| 145 | int bRowid; /* True if this table uses rowid for PK */ |
| 146 | const char **azCol; /* Column names */ |
| 147 | const char **azDflt; /* Default value expressions */ |
| 148 | int *aiIdx; /* Index to pass to xNew/xOld */ |
| 149 | u8 *abPK; /* Array of primary key flags */ |
| 150 | int nEntry; /* Total number of entries in hash table */ |
| 151 | int nChange; /* Size of apChange[] array */ |
| 152 | SessionChange **apChange; /* Hash table buckets */ |
| 153 | sqlite3_stmt *pDfltStmt; |
| 154 | }; |
| 155 | |
| 156 | /* |
| 157 | ** RECORD FORMAT: |
| 158 | ** |
| 159 | ** The following record format is similar to (but not compatible with) that |
| 160 | ** used in SQLite database files. This format is used as part of the |
| 161 | ** change-set binary format, and so must be architecture independent. |
| 162 | ** |
| 163 | ** Unlike the SQLite database record format, each field is self-contained - |
| 164 | ** there is no separation of header and data. Each field begins with a |
| 165 | ** single byte describing its type, as follows: |
| 166 | ** |
| 167 | ** 0x00: Undefined value. |
| 168 | ** 0x01: Integer value. |
| 169 | ** 0x02: Real value. |
| 170 | ** 0x03: Text value. |
| 171 | ** 0x04: Blob value. |
| 172 | ** 0x05: SQL NULL value. |
| 173 | ** |
| 174 | ** Note that the above match the definitions of SQLITE_INTEGER, SQLITE_TEXT |
| 175 | ** and so on in sqlite3.h. For undefined and NULL values, the field consists |
| 176 | ** only of the single type byte. For other types of values, the type byte |
| 177 | ** is followed by: |
| 178 | ** |
| 179 | ** Text values: |
| 180 | ** A varint containing the number of bytes in the value (encoded using |
| 181 | ** UTF-8). Followed by a buffer containing the UTF-8 representation |
| 182 | ** of the text value. There is no nul terminator. |
| 183 | ** |
| 184 | ** Blob values: |
| 185 | ** A varint containing the number of bytes in the value, followed by |
| 186 | ** a buffer containing the value itself. |
| 187 | ** |
| 188 | ** Integer values: |
| 189 | ** An 8-byte big-endian integer value. |
| 190 | ** |
| 191 | ** Real values: |
| 192 | ** An 8-byte big-endian IEEE 754-2008 real value. |
| 193 | ** |
| 194 | ** Varint values are encoded in the same way as varints in the SQLite |
| 195 | ** record format. |
| 196 | ** |
| 197 | ** CHANGESET FORMAT: |
| 198 | ** |
| 199 | ** A changeset is a collection of DELETE, UPDATE and INSERT operations on |
| 200 | ** one or more tables. Operations on a single table are grouped together, |
| 201 | ** but may occur in any order (i.e. deletes, updates and inserts are all |
| 202 | ** mixed together). |
| 203 | ** |
| 204 | ** Each group of changes begins with a table header: |
| 205 | ** |
| 206 | ** 1 byte: Constant 0x54 (capital 'T') |
| 207 | ** Varint: Number of columns in the table. |
| 208 | ** nCol bytes: 0x01 for PK columns, 0x00 otherwise. |
| 209 | ** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated. |
| 210 | ** |
| 211 | ** Followed by one or more changes to the table. |
| 212 | ** |
| 213 | ** 1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09). |
| 214 | ** 1 byte: The "indirect-change" flag. |
| 215 | ** old.* record: (delete and update only) |
| 216 | ** new.* record: (insert and update only) |
| 217 | ** |
| 218 | ** The "old.*" and "new.*" records, if present, are N field records in the |
| 219 | ** format described above under "RECORD FORMAT", where N is the number of |
| 220 | ** columns in the table. The i'th field of each record is associated with |
| 221 | ** the i'th column of the table, counting from left to right in the order |
| 222 | ** in which columns were declared in the CREATE TABLE statement. |
| 223 | ** |
| 224 | ** The new.* record that is part of each INSERT change contains the values |
| 225 | ** that make up the new row. Similarly, the old.* record that is part of each |
| 226 | ** DELETE change contains the values that made up the row that was deleted |
| 227 | ** from the database. In the changeset format, the records that are part |
| 228 | ** of INSERT or DELETE changes never contain any undefined (type byte 0x00) |
| 229 | ** fields. |
| 230 | ** |
| 231 | ** Within the old.* record associated with an UPDATE change, all fields |
| 232 | ** associated with table columns that are not PRIMARY KEY columns and are |
| 233 | ** not modified by the UPDATE change are set to "undefined". Other fields |
| 234 | ** are set to the values that made up the row before the UPDATE that the |
| 235 | ** change records took place. Within the new.* record, fields associated |
| 236 | ** with table columns modified by the UPDATE change contain the new |
| 237 | ** values. Fields associated with table columns that are not modified |
| 238 | ** are set to "undefined". |
| 239 | ** |
| 240 | ** PATCHSET FORMAT: |
| 241 | ** |
| 242 | ** A patchset is also a collection of changes. It is similar to a changeset, |
| 243 | ** but leaves undefined those fields that are not useful if no conflict |
| 244 | ** resolution is required when applying the changeset. |
| 245 | ** |
| 246 | ** Each group of changes begins with a table header: |
| 247 | ** |
| 248 | ** 1 byte: Constant 0x50 (capital 'P') |
| 249 | ** Varint: Number of columns in the table. |
| 250 | ** nCol bytes: 0x01 for PK columns, 0x00 otherwise. |
| 251 | ** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated. |
| 252 | ** |
| 253 | ** Followed by one or more changes to the table. |
| 254 | ** |
| 255 | ** 1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09). |
| 256 | ** 1 byte: The "indirect-change" flag. |
| 257 | ** single record: (PK fields for DELETE, PK and modified fields for UPDATE, |
| 258 | ** full record for INSERT). |
| 259 | ** |
| 260 | ** As in the changeset format, each field of the single record that is part |
| 261 | ** of a patchset change is associated with the correspondingly positioned |
| 262 | ** table column, counting from left to right within the CREATE TABLE |
| 263 | ** statement. |
| 264 | ** |
| 265 | ** For a DELETE change, all fields within the record except those associated |
| 266 | ** with PRIMARY KEY columns are omitted. The PRIMARY KEY fields contain the |
| 267 | ** values identifying the row to delete. |
| 268 | ** |
| 269 | ** For an UPDATE change, all fields except those associated with PRIMARY KEY |
| 270 | ** columns and columns that are modified by the UPDATE are set to "undefined". |
| 271 | ** PRIMARY KEY fields contain the values identifying the table row to update, |
| 272 | ** and fields associated with modified columns contain the new column values. |
| 273 | ** |
| 274 | ** The records associated with INSERT changes are in the same format as for |
| 275 | ** changesets. It is not possible for a record associated with an INSERT |
| 276 | ** change to contain a field set to "undefined". |
| 277 | ** |
| 278 | ** REBASE BLOB FORMAT: |
| 279 | ** |
| 280 | ** A rebase blob may be output by sqlite3changeset_apply_v2() and its |
| 281 | ** streaming equivalent for use with the sqlite3_rebaser APIs to rebase |
| 282 | ** existing changesets. A rebase blob contains one entry for each conflict |
| 283 | ** resolved using either the OMIT or REPLACE strategies within the apply_v2() |
| 284 | ** call. |
| 285 | ** |
| 286 | ** The format used for a rebase blob is very similar to that used for |
| 287 | ** changesets. All entries related to a single table are grouped together. |
| 288 | ** |
| 289 | ** Each group of entries begins with a table header in changeset format: |
| 290 | ** |
| 291 | ** 1 byte: Constant 0x54 (capital 'T') |
| 292 | ** Varint: Number of columns in the table. |
| 293 | ** nCol bytes: 0x01 for PK columns, 0x00 otherwise. |
| 294 | ** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated. |
| 295 | ** |
| 296 | ** Followed by one or more entries associated with the table. |
| 297 | ** |
| 298 | ** 1 byte: Either SQLITE_INSERT (0x12), DELETE (0x09). |
| 299 | ** 1 byte: Flag. 0x01 for REPLACE, 0x00 for OMIT. |
| 300 | ** record: (in the record format defined above). |
| 301 | ** |
| 302 | ** In a rebase blob, the first field is set to SQLITE_INSERT if the change |
| 303 | ** that caused the conflict was an INSERT or UPDATE, or to SQLITE_DELETE if |
| 304 | ** it was a DELETE. The second field is set to 0x01 if the conflict |
| 305 | ** resolution strategy was REPLACE, or 0x00 if it was OMIT. |
| 306 | ** |
| 307 | ** If the change that caused the conflict was a DELETE, then the single |
| 308 | ** record is a copy of the old.* record from the original changeset. If it |
| 309 | ** was an INSERT, then the single record is a copy of the new.* record. If |
| 310 | ** the conflicting change was an UPDATE, then the single record is a copy |
| 311 | ** of the new.* record with the PK fields filled in based on the original |
| 312 | ** old.* record. |
| 313 | */ |
| 314 | |
| 315 | /* |
| 316 | ** For each row modified during a session, there exists a single instance of |
| 317 | ** this structure stored in a SessionTable.aChange[] hash table. |
| 318 | */ |
| 319 | struct SessionChange { |
| 320 | u8 op; /* One of UPDATE, DELETE, INSERT */ |
| 321 | u8 bIndirect; /* True if this change is "indirect" */ |
| 322 | u16 nRecordField; /* Number of fields in aRecord[] */ |
| 323 | int nMaxSize; /* Max size of eventual changeset record */ |
| 324 | int nRecord; /* Number of bytes in buffer aRecord[] */ |
| 325 | u8 *aRecord; /* Buffer containing old.* record */ |
| 326 | SessionChange *pNext; /* For hash-table collisions */ |
| 327 | }; |
| 328 | |
| 329 | /* |
| 330 | ** Write a varint with value iVal into the buffer at aBuf. Return the |
| 331 | ** number of bytes written. |
| 332 | */ |
| 333 | static int sessionVarintPut(u8 *aBuf, int iVal){ |
| 334 | return putVarint32(aBuf, iVal); |
| 335 | } |
| 336 | |
| 337 | /* |
| 338 | ** Return the number of bytes required to store value iVal as a varint. |
| 339 | */ |
| 340 | static int sessionVarintLen(int iVal){ |
| 341 | return sqlite3VarintLen(iVal); |
| 342 | } |
| 343 | |
| 344 | /* |
| 345 | ** Read a varint value from aBuf[] into *piVal. Return the number of |
| 346 | ** bytes read. |
| 347 | */ |
| 348 | static int sessionVarintGet(const u8 *aBuf, int *piVal){ |
| 349 | int ret = getVarint32(aBuf, *piVal); |
| 350 | *piVal = (*piVal & 0x7FFFFFFF); |
| 351 | return ret; |
| 352 | } |
| 353 | |
| 354 | /* |
| 355 | ** Read a varint value from buffer aBuf[], size nBuf bytes, into *piVal. |
| 356 | ** Return the number of bytes read. |
| 357 | */ |
| 358 | static int sessionVarintGetSafe(const u8 *aBuf, int nBuf, int *piVal){ |
| 359 | u8 aCopy[9]; |
| 360 | const u8 *aRead = aBuf; |
| 361 | memset(aCopy, 0, sizeof(aCopy)); |
| 362 | if( nBuf<sizeof(aCopy) ){ |
| 363 | memcpy(aCopy, aBuf, nBuf); |
| 364 | aRead = aCopy; |
| 365 | } |
| 366 | return sessionVarintGet(aRead, piVal); |
| 367 | } |
| 368 | |
| 369 | /* Load an unaligned and unsigned 32-bit integer */ |
| 370 | #define SESSION_UINT32(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3]) |
| 371 | |
| 372 | /* |
| 373 | ** Read a 64-bit big-endian integer value from buffer aRec[]. Return |
| 374 | ** the value read. |
| 375 | */ |
| 376 | static sqlite3_int64 sessionGetI64(u8 *aRec){ |
| 377 | u64 x = SESSION_UINT32(aRec); |
| 378 | u32 y = SESSION_UINT32(aRec+4); |
| 379 | x = (x<<32) + y; |
| 380 | return (sqlite3_int64)x; |
| 381 | } |
| 382 | |
| 383 | /* |
| 384 | ** Write a 64-bit big-endian integer value to the buffer aBuf[]. |
| 385 | */ |
| 386 | static void sessionPutI64(u8 *aBuf, sqlite3_int64 i){ |
| 387 | aBuf[0] = (i>>56) & 0xFF; |
| 388 | aBuf[1] = (i>>48) & 0xFF; |
| 389 | aBuf[2] = (i>>40) & 0xFF; |
| 390 | aBuf[3] = (i>>32) & 0xFF; |
| 391 | aBuf[4] = (i>>24) & 0xFF; |
| 392 | aBuf[5] = (i>>16) & 0xFF; |
| 393 | aBuf[6] = (i>> 8) & 0xFF; |
| 394 | aBuf[7] = (i>> 0) & 0xFF; |
| 395 | } |
| 396 | |
| 397 | /* |
| 398 | ** Write a double value to the buffer aBuf[]. |
| 399 | */ |
| 400 | static void sessionPutDouble(u8 *aBuf, double r){ |
| 401 | /* TODO: SQLite does something special to deal with mixed-endian |
| 402 | ** floating point values (e.g. ARM7). This code probably should |
| 403 | ** too. */ |
| 404 | u64 i; |
| 405 | assert( sizeof(double)==8 && sizeof(u64)==8 ); |
| 406 | memcpy(&i, &r, 8); |
| 407 | sessionPutI64(aBuf, i); |
| 408 | } |
| 409 | |
| 410 | /* |
| 411 | ** This function is used to serialize the contents of value pValue (see |
| 412 | ** comment titled "RECORD FORMAT" above). |
| 413 | ** |
| 414 | ** If it is non-NULL, the serialized form of the value is written to |
| 415 | ** buffer aBuf. *pnWrite is set to the number of bytes written before |
| 416 | ** returning. Or, if aBuf is NULL, the only thing this function does is |
| 417 | ** set *pnWrite. |
| 418 | ** |
| 419 | ** If no error occurs, SQLITE_OK is returned. Or, if an OOM error occurs |
| 420 | ** within a call to sqlite3_value_text() (may fail if the db is utf-16)) |
| 421 | ** SQLITE_NOMEM is returned. |
| 422 | */ |
| 423 | static int sessionSerializeValue( |
| 424 | u8 *aBuf, /* If non-NULL, write serialized value here */ |
| 425 | sqlite3_value *pValue, /* Value to serialize */ |
| 426 | sqlite3_int64 *pnWrite /* IN/OUT: Increment by bytes written */ |
| 427 | ){ |
| 428 | int nByte; /* Size of serialized value in bytes */ |
| 429 | |
| 430 | if( pValue ){ |
| 431 | int eType; /* Value type (SQLITE_NULL, TEXT etc.) */ |
| 432 | |
| 433 | eType = sqlite3_value_type(pValue); |
| 434 | if( aBuf ) aBuf[0] = eType; |
| 435 | |
| 436 | switch( eType ){ |
| 437 | case SQLITE_NULL: |
| 438 | nByte = 1; |
| 439 | break; |
| 440 | |
| 441 | case SQLITE_INTEGER: |
| 442 | case SQLITE_FLOAT: |
| 443 | if( aBuf ){ |
| 444 | /* TODO: SQLite does something special to deal with mixed-endian |
| 445 | ** floating point values (e.g. ARM7). This code probably should |
| 446 | ** too. */ |
| 447 | if( eType==SQLITE_INTEGER ){ |
| 448 | u64 i = (u64)sqlite3_value_int64(pValue); |
| 449 | sessionPutI64(&aBuf[1], i); |
| 450 | }else{ |
| 451 | double r = sqlite3_value_double(pValue); |
| 452 | sessionPutDouble(&aBuf[1], r); |
| 453 | } |
| 454 | } |
| 455 | nByte = 9; |
| 456 | break; |
| 457 | |
| 458 | default: { |
| 459 | u8 *z; |
| 460 | int n; |
| 461 | int nVarint; |
| 462 | |
| 463 | assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB ); |
| 464 | if( eType==SQLITE_TEXT ){ |
| 465 | z = (u8 *)sqlite3_value_text(pValue); |
| 466 | }else{ |
| 467 | z = (u8 *)sqlite3_value_blob(pValue); |
| 468 | } |
| 469 | n = sqlite3_value_bytes(pValue); |
| 470 | if( z==0 && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM; |
| 471 | nVarint = sessionVarintLen(n); |
| 472 | |
| 473 | if( aBuf ){ |
| 474 | sessionVarintPut(&aBuf[1], n); |
| 475 | if( n>0 ) memcpy(&aBuf[nVarint + 1], z, n); |
| 476 | } |
| 477 | |
| 478 | nByte = 1 + nVarint + n; |
| 479 | break; |
| 480 | } |
| 481 | } |
| 482 | }else{ |
| 483 | nByte = 1; |
| 484 | if( aBuf ) aBuf[0] = '\0'; |
| 485 | } |
| 486 | |
| 487 | if( pnWrite ) *pnWrite += nByte; |
| 488 | return SQLITE_OK; |
| 489 | } |
| 490 | |
| 491 | /* |
| 492 | ** Allocate and return a pointer to a buffer nByte bytes in size. If |
| 493 | ** pSession is not NULL, increase the sqlite3_session.nMalloc variable |
| 494 | ** by the number of bytes allocated. |
| 495 | */ |
| 496 | static void *sessionMalloc64(sqlite3_session *pSession, i64 nByte){ |
| 497 | void *pRet = sqlite3_malloc64(nByte); |
| 498 | if( pSession ) pSession->nMalloc += sqlite3_msize(pRet); |
| 499 | return pRet; |
| 500 | } |
| 501 | |
| 502 | /* |
| 503 | ** Free buffer pFree, which must have been allocated by an earlier |
| 504 | ** call to sessionMalloc64(). If pSession is not NULL, decrease the |
| 505 | ** sqlite3_session.nMalloc counter by the number of bytes freed. |
| 506 | */ |
| 507 | static void sessionFree(sqlite3_session *pSession, void *pFree){ |
| 508 | if( pSession ) pSession->nMalloc -= sqlite3_msize(pFree); |
| 509 | sqlite3_free(pFree); |
| 510 | } |
| 511 | |
| 512 | /* |
| 513 | ** This macro is used to calculate hash key values for data structures. In |
| 514 | ** order to use this macro, the entire data structure must be represented |
| 515 | ** as a series of unsigned integers. In order to calculate a hash-key value |
| 516 | ** for a data structure represented as three such integers, the macro may |
| 517 | ** then be used as follows: |
| 518 | ** |
| 519 | ** int hash_key_value; |
| 520 | ** hash_key_value = HASH_APPEND(0, <value 1>); |
| 521 | ** hash_key_value = HASH_APPEND(hash_key_value, <value 2>); |
| 522 | ** hash_key_value = HASH_APPEND(hash_key_value, <value 3>); |
| 523 | ** |
| 524 | ** In practice, the data structures this macro is used for are the primary |
| 525 | ** key values of modified rows. |
| 526 | */ |
| 527 | #define HASH_APPEND(hash, add) ((hash) << 3) ^ (hash) ^ (unsigned int)(add) |
| 528 | |
| 529 | /* |
| 530 | ** Append the hash of the 64-bit integer passed as the second argument to the |
| 531 | ** hash-key value passed as the first. Return the new hash-key value. |
| 532 | */ |
| 533 | static unsigned int sessionHashAppendI64(unsigned int h, i64 i){ |
| 534 | h = HASH_APPEND(h, i & 0xFFFFFFFF); |
| 535 | return HASH_APPEND(h, (i>>32)&0xFFFFFFFF); |
| 536 | } |
| 537 | |
| 538 | /* |
| 539 | ** Append the hash of the blob passed via the second and third arguments to |
| 540 | ** the hash-key value passed as the first. Return the new hash-key value. |
| 541 | */ |
| 542 | static unsigned int sessionHashAppendBlob(unsigned int h, int n, const u8 *z){ |
| 543 | int i; |
| 544 | for(i=0; i<n; i++) h = HASH_APPEND(h, z[i]); |
| 545 | return h; |
| 546 | } |
| 547 | |
| 548 | /* |
| 549 | ** Append the hash of the data type passed as the second argument to the |
| 550 | ** hash-key value passed as the first. Return the new hash-key value. |
| 551 | */ |
| 552 | static unsigned int sessionHashAppendType(unsigned int h, int eType){ |
| 553 | return HASH_APPEND(h, eType); |
| 554 | } |
| 555 | |
| 556 | /* |
| 557 | ** This function may only be called from within a pre-update callback. |
| 558 | ** It calculates a hash based on the primary key values of the old.* or |
| 559 | ** new.* row currently available and, assuming no error occurs, writes it to |
| 560 | ** *piHash before returning. If the primary key contains one or more NULL |
| 561 | ** values, *pbNullPK is set to true before returning. |
| 562 | ** |
| 563 | ** If an error occurs, an SQLite error code is returned and the final values |
| 564 | ** of *piHash asn *pbNullPK are undefined. Otherwise, SQLITE_OK is returned |
| 565 | ** and the output variables are set as described above. |
| 566 | */ |
| 567 | static int sessionPreupdateHash( |
| 568 | sqlite3_session *pSession, /* Session object that owns pTab */ |
| 569 | i64 iRowid, |
| 570 | SessionTable *pTab, /* Session table handle */ |
| 571 | int bNew, /* True to hash the new.* PK */ |
| 572 | int *piHash, /* OUT: Hash value */ |
| 573 | int *pbNullPK /* OUT: True if there are NULL values in PK */ |
| 574 | ){ |
| 575 | unsigned int h = 0; /* Hash value to return */ |
| 576 | int i; /* Used to iterate through columns */ |
| 577 | |
| 578 | assert( pTab->nTotalCol==pSession->hook.xCount(pSession->hook.pCtx) ); |
| 579 | if( pTab->bRowid ){ |
| 580 | h = sessionHashAppendI64(h, iRowid); |
| 581 | }else{ |
| 582 | assert( *pbNullPK==0 ); |
| 583 | for(i=0; i<pTab->nCol; i++){ |
| 584 | if( pTab->abPK[i] ){ |
| 585 | int rc; |
| 586 | int eType; |
| 587 | sqlite3_value *pVal; |
| 588 | int iIdx = pTab->aiIdx[i]; |
| 589 | |
| 590 | if( bNew ){ |
| 591 | rc = pSession->hook.xNew(pSession->hook.pCtx, iIdx, &pVal); |
| 592 | }else{ |
| 593 | rc = pSession->hook.xOld(pSession->hook.pCtx, iIdx, &pVal); |
| 594 | } |
| 595 | if( rc!=SQLITE_OK ) return rc; |
| 596 | |
| 597 | eType = sqlite3_value_type(pVal); |
| 598 | h = sessionHashAppendType(h, eType); |
| 599 | if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){ |
| 600 | i64 iVal; |
| 601 | if( eType==SQLITE_INTEGER ){ |
| 602 | iVal = sqlite3_value_int64(pVal); |
| 603 | }else{ |
| 604 | double rVal = sqlite3_value_double(pVal); |
| 605 | assert( sizeof(iVal)==8 && sizeof(rVal)==8 ); |
| 606 | memcpy(&iVal, &rVal, 8); |
| 607 | } |
| 608 | h = sessionHashAppendI64(h, iVal); |
| 609 | }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){ |
| 610 | const u8 *z; |
| 611 | int n; |
| 612 | if( eType==SQLITE_TEXT ){ |
| 613 | z = (const u8 *)sqlite3_value_text(pVal); |
| 614 | }else{ |
| 615 | z = (const u8 *)sqlite3_value_blob(pVal); |
| 616 | } |
| 617 | n = sqlite3_value_bytes(pVal); |
| 618 | if( !z && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM; |
| 619 | h = sessionHashAppendBlob(h, n, z); |
| 620 | }else{ |
| 621 | assert( eType==SQLITE_NULL ); |
| 622 | assert( pTab->bStat1==0 || i!=1 ); |
| 623 | *pbNullPK = 1; |
| 624 | } |
| 625 | } |
| 626 | } |
| 627 | } |
| 628 | |
| 629 | *piHash = (h % pTab->nChange); |
| 630 | return SQLITE_OK; |
| 631 | } |
| 632 | |
| 633 | /* |
| 634 | ** The buffer that the argument points to contains a serialized SQL value. |
| 635 | ** Return the number of bytes of space occupied by the value (including |
| 636 | ** the type byte). |
| 637 | */ |
| 638 | static int sessionSerialLen(const u8 *a){ |
| 639 | int e; |
| 640 | int n; |
| 641 | assert( a!=0 ); |
| 642 | e = *a; |
| 643 | if( e==SQLITE_INTEGER || e==SQLITE_FLOAT ) return 9; |
| 644 | if( e==SQLITE_TEXT || e==SQLITE_BLOB ){ |
| 645 | const int v = sessionVarintGet(&a[1], &n); |
| 646 | return v + 1 + n; |
| 647 | } |
| 648 | return 1; |
| 649 | } |
| 650 | |
| 651 | /* |
| 652 | ** Based on the primary key values stored in change aRecord, calculate a |
| 653 | ** hash key. Assume the has table has nBucket buckets. The hash keys |
| 654 | ** calculated by this function are compatible with those calculated by |
| 655 | ** sessionPreupdateHash(). |
| 656 | ** |
| 657 | ** The bPkOnly argument is non-zero if the record at aRecord[] is from |
| 658 | ** a patchset DELETE. In this case the non-PK fields are omitted entirely. |
| 659 | */ |
| 660 | static unsigned int sessionChangeHash( |
| 661 | SessionTable *pTab, /* Table handle */ |
| 662 | int bPkOnly, /* Record consists of PK fields only */ |
| 663 | u8 *aRecord, /* Change record */ |
| 664 | int nBucket /* Assume this many buckets in hash table */ |
| 665 | ){ |
| 666 | unsigned int h = 0; /* Value to return */ |
| 667 | int i; /* Used to iterate through columns */ |
| 668 | u8 *a = aRecord; /* Used to iterate through change record */ |
| 669 | |
| 670 | for(i=0; i<pTab->nCol; i++){ |
| 671 | int isPK = pTab->abPK[i]; |
| 672 | if( bPkOnly && isPK==0 ) continue; |
| 673 | |
| 674 | if( isPK ){ |
| 675 | int eType = *a++; |
| 676 | |
| 677 | assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT |
| 678 | || eType==SQLITE_TEXT || eType==SQLITE_BLOB |
| 679 | || eType==SQLITE_NULL || eType==0 |
| 680 | ); |
| 681 | |
| 682 | h = sessionHashAppendType(h, eType); |
| 683 | if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){ |
| 684 | h = sessionHashAppendI64(h, sessionGetI64(a)); |
| 685 | a += 8; |
| 686 | }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){ |
| 687 | int n; |
| 688 | a += sessionVarintGet(a, &n); |
| 689 | h = sessionHashAppendBlob(h, n, a); |
| 690 | a += n; |
| 691 | } |
| 692 | /* It should not be possible for eType to be SQLITE_NULL or 0x00 here, |
| 693 | ** as the session module does not record changes for rows with NULL |
| 694 | ** values stored in primary key columns. But a corrupt changesets |
| 695 | ** may contain such a value. */ |
| 696 | }else{ |
| 697 | a += sessionSerialLen(a); |
| 698 | } |
| 699 | } |
| 700 | return (h % nBucket); |
| 701 | } |
| 702 | |
| 703 | /* |
| 704 | ** Arguments aLeft and aRight are pointers to change records for table pTab. |
| 705 | ** This function returns true if the two records apply to the same row (i.e. |
| 706 | ** have the same values stored in the primary key columns), or false |
| 707 | ** otherwise. |
| 708 | */ |
| 709 | static int sessionChangeEqual( |
| 710 | SessionTable *pTab, /* Table used for PK definition */ |
| 711 | int bLeftPkOnly, /* True if aLeft[] contains PK fields only */ |
| 712 | u8 *aLeft, /* Change record */ |
| 713 | int bRightPkOnly, /* True if aRight[] contains PK fields only */ |
| 714 | u8 *aRight /* Change record */ |
| 715 | ){ |
| 716 | u8 *a1 = aLeft; /* Cursor to iterate through aLeft */ |
| 717 | u8 *a2 = aRight; /* Cursor to iterate through aRight */ |
| 718 | int iCol; /* Used to iterate through table columns */ |
| 719 | |
| 720 | for(iCol=0; iCol<pTab->nCol; iCol++){ |
| 721 | if( pTab->abPK[iCol] ){ |
| 722 | int n1 = sessionSerialLen(a1); |
| 723 | int n2 = sessionSerialLen(a2); |
| 724 | |
| 725 | if( n1!=n2 || memcmp(a1, a2, n1) ){ |
| 726 | return 0; |
| 727 | } |
| 728 | a1 += n1; |
| 729 | a2 += n2; |
| 730 | }else{ |
| 731 | if( bLeftPkOnly==0 ) a1 += sessionSerialLen(a1); |
| 732 | if( bRightPkOnly==0 ) a2 += sessionSerialLen(a2); |
| 733 | } |
| 734 | } |
| 735 | |
| 736 | return 1; |
| 737 | } |
| 738 | |
| 739 | /* |
| 740 | ** Arguments aLeft and aRight both point to buffers containing change |
| 741 | ** records with nCol columns. This function "merges" the two records into |
| 742 | ** a single records which is written to the buffer at *paOut. *paOut is |
| 743 | ** then set to point to one byte after the last byte written before |
| 744 | ** returning. |
| 745 | ** |
| 746 | ** The merging of records is done as follows: For each column, if the |
| 747 | ** aRight record contains a value for the column, copy the value from |
| 748 | ** their. Otherwise, if aLeft contains a value, copy it. If neither |
| 749 | ** record contains a value for a given column, then neither does the |
| 750 | ** output record. |
| 751 | */ |
| 752 | static void sessionMergeRecord( |
| 753 | u8 **paOut, |
| 754 | int nCol, |
| 755 | u8 *aLeft, |
| 756 | u8 *aRight |
| 757 | ){ |
| 758 | u8 *a1 = aLeft; /* Cursor used to iterate through aLeft */ |
| 759 | u8 *a2 = aRight; /* Cursor used to iterate through aRight */ |
| 760 | u8 *aOut = *paOut; /* Output cursor */ |
| 761 | int iCol; /* Used to iterate from 0 to nCol */ |
| 762 | |
| 763 | for(iCol=0; iCol<nCol; iCol++){ |
| 764 | int n1 = sessionSerialLen(a1); |
| 765 | int n2 = sessionSerialLen(a2); |
| 766 | if( *a2 ){ |
| 767 | memcpy(aOut, a2, n2); |
| 768 | aOut += n2; |
| 769 | }else{ |
| 770 | memcpy(aOut, a1, n1); |
| 771 | aOut += n1; |
| 772 | } |
| 773 | a1 += n1; |
| 774 | a2 += n2; |
| 775 | } |
| 776 | |
| 777 | *paOut = aOut; |
| 778 | } |
| 779 | |
| 780 | /* |
| 781 | ** This is a helper function used by sessionMergeUpdate(). |
| 782 | ** |
| 783 | ** When this function is called, both *paOne and *paTwo point to a value |
| 784 | ** within a change record. Before it returns, both have been advanced so |
| 785 | ** as to point to the next value in the record. |
| 786 | ** |
| 787 | ** If, when this function is called, *paTwo points to a valid value (i.e. |
| 788 | ** *paTwo[0] is not 0x00 - the "no value" placeholder), a copy of the *paTwo |
| 789 | ** pointer is returned and *pnVal is set to the number of bytes in the |
| 790 | ** serialized value. Otherwise, a copy of *paOne is returned and *pnVal |
| 791 | ** set to the number of bytes in the value at *paOne. If *paOne points |
| 792 | ** to the "no value" placeholder, *pnVal is set to 1. In other words: |
| 793 | ** |
| 794 | ** if( *paTwo is valid ) return *paTwo; |
| 795 | ** return *paOne; |
| 796 | ** |
| 797 | */ |
| 798 | static u8 *sessionMergeValue( |
| 799 | u8 **paOne, /* IN/OUT: Left-hand buffer pointer */ |
| 800 | u8 **paTwo, /* IN/OUT: Right-hand buffer pointer */ |
| 801 | int *pnVal /* OUT: Bytes in returned value */ |
| 802 | ){ |
| 803 | u8 *a1 = *paOne; |
| 804 | u8 *a2 = *paTwo; |
| 805 | u8 *pRet = 0; |
| 806 | int n1; |
| 807 | |
| 808 | assert( a1 ); |
| 809 | if( a2 ){ |
| 810 | int n2 = sessionSerialLen(a2); |
| 811 | if( *a2 ){ |
| 812 | *pnVal = n2; |
| 813 | pRet = a2; |
| 814 | } |
| 815 | *paTwo = &a2[n2]; |
| 816 | } |
| 817 | |
| 818 | n1 = sessionSerialLen(a1); |
| 819 | if( pRet==0 ){ |
| 820 | *pnVal = n1; |
| 821 | pRet = a1; |
| 822 | } |
| 823 | *paOne = &a1[n1]; |
| 824 | |
| 825 | return pRet; |
| 826 | } |
| 827 | |
| 828 | /* |
| 829 | ** This function is used by changeset_concat() to merge two UPDATE changes |
| 830 | ** on the same row. |
| 831 | */ |
| 832 | static int sessionMergeUpdate( |
| 833 | u8 **paOut, /* IN/OUT: Pointer to output buffer */ |
| 834 | SessionTable *pTab, /* Table change pertains to */ |
| 835 | int bPatchset, /* True if records are patchset records */ |
| 836 | u8 *aOldRecord1, /* old.* record for first change */ |
| 837 | u8 *aOldRecord2, /* old.* record for second change */ |
| 838 | u8 *aNewRecord1, /* new.* record for first change */ |
| 839 | u8 *aNewRecord2 /* new.* record for second change */ |
| 840 | ){ |
| 841 | u8 *aOld1 = aOldRecord1; |
| 842 | u8 *aOld2 = aOldRecord2; |
| 843 | u8 *aNew1 = aNewRecord1; |
| 844 | u8 *aNew2 = aNewRecord2; |
| 845 | |
| 846 | u8 *aOut = *paOut; |
| 847 | int i; |
| 848 | |
| 849 | if( bPatchset==0 ){ |
| 850 | int bRequired = 0; |
| 851 | |
| 852 | assert( aOldRecord1 && aNewRecord1 ); |
| 853 | |
| 854 | /* Write the old.* vector first. */ |
| 855 | for(i=0; i<pTab->nCol; i++){ |
| 856 | int nOld; |
| 857 | u8 *aOld; |
| 858 | int nNew; |
| 859 | u8 *aNew; |
| 860 | |
| 861 | aOld = sessionMergeValue(&aOld1, &aOld2, &nOld); |
| 862 | aNew = sessionMergeValue(&aNew1, &aNew2, &nNew); |
| 863 | if( pTab->abPK[i] || nOld!=nNew || memcmp(aOld, aNew, nNew) ){ |
| 864 | if( pTab->abPK[i]==0 ) bRequired = 1; |
| 865 | memcpy(aOut, aOld, nOld); |
| 866 | aOut += nOld; |
| 867 | }else{ |
| 868 | *(aOut++) = '\0'; |
| 869 | } |
| 870 | } |
| 871 | |
| 872 | if( !bRequired ) return 0; |
| 873 | } |
| 874 | |
| 875 | /* Write the new.* vector */ |
| 876 | aOld1 = aOldRecord1; |
| 877 | aOld2 = aOldRecord2; |
| 878 | aNew1 = aNewRecord1; |
| 879 | aNew2 = aNewRecord2; |
| 880 | for(i=0; i<pTab->nCol; i++){ |
| 881 | int nOld; |
| 882 | u8 *aOld; |
| 883 | int nNew; |
| 884 | u8 *aNew; |
| 885 | |
| 886 | aOld = sessionMergeValue(&aOld1, &aOld2, &nOld); |
| 887 | aNew = sessionMergeValue(&aNew1, &aNew2, &nNew); |
| 888 | if( bPatchset==0 |
| 889 | && (pTab->abPK[i] || (nOld==nNew && 0==memcmp(aOld, aNew, nNew))) |
| 890 | ){ |
| 891 | *(aOut++) = '\0'; |
| 892 | }else{ |
| 893 | memcpy(aOut, aNew, nNew); |
| 894 | aOut += nNew; |
| 895 | } |
| 896 | } |
| 897 | |
| 898 | *paOut = aOut; |
| 899 | return 1; |
| 900 | } |
| 901 | |
| 902 | /* |
| 903 | ** This function is only called from within a pre-update-hook callback. |
| 904 | ** It determines if the current pre-update-hook change affects the same row |
| 905 | ** as the change stored in argument pChange. If so, it returns true. Otherwise |
| 906 | ** if the pre-update-hook does not affect the same row as pChange, it returns |
| 907 | ** false. |
| 908 | */ |
| 909 | static int sessionPreupdateEqual( |
| 910 | sqlite3_session *pSession, /* Session object that owns SessionTable */ |
| 911 | i64 iRowid, /* Rowid value if pTab->bRowid */ |
| 912 | SessionTable *pTab, /* Table associated with change */ |
| 913 | SessionChange *pChange, /* Change to compare to */ |
| 914 | int op /* Current pre-update operation */ |
| 915 | ){ |
| 916 | int iCol; /* Used to iterate through columns */ |
| 917 | u8 *a = pChange->aRecord; /* Cursor used to scan change record */ |
| 918 | |
| 919 | if( pTab->bRowid ){ |
| 920 | if( a[0]!=SQLITE_INTEGER ) return 0; |
| 921 | return sessionGetI64(&a[1])==iRowid; |
| 922 | } |
| 923 | |
| 924 | assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE ); |
| 925 | for(iCol=0; iCol<pTab->nCol; iCol++){ |
| 926 | if( !pTab->abPK[iCol] ){ |
| 927 | a += sessionSerialLen(a); |
| 928 | }else{ |
| 929 | sqlite3_value *pVal; /* Value returned by preupdate_new/old */ |
| 930 | int rc; /* Error code from preupdate_new/old */ |
| 931 | int eType = *a++; /* Type of value from change record */ |
| 932 | int iIdx = pTab->aiIdx[iCol]; |
| 933 | |
| 934 | /* The following calls to preupdate_new() and preupdate_old() can not |
| 935 | ** fail. This is because they cache their return values, and by the |
| 936 | ** time control flows to here they have already been called once from |
| 937 | ** within sessionPreupdateHash(). The first two asserts below verify |
| 938 | ** this (that the method has already been called). */ |
| 939 | if( op==SQLITE_INSERT ){ |
| 940 | /* assert( db->pPreUpdate->pNewUnpacked || db->pPreUpdate->aNew ); */ |
| 941 | rc = pSession->hook.xNew(pSession->hook.pCtx, iIdx, &pVal); |
| 942 | }else{ |
| 943 | /* assert( db->pPreUpdate->pUnpacked ); */ |
| 944 | rc = pSession->hook.xOld(pSession->hook.pCtx, iIdx, &pVal); |
| 945 | } |
| 946 | assert( rc==SQLITE_OK ); |
| 947 | (void)rc; /* Suppress warning about unused variable */ |
| 948 | if( sqlite3_value_type(pVal)!=eType ) return 0; |
| 949 | |
| 950 | /* A SessionChange object never has a NULL value in a PK column */ |
| 951 | assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT |
| 952 | || eType==SQLITE_BLOB || eType==SQLITE_TEXT |
| 953 | ); |
| 954 | |
| 955 | if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){ |
| 956 | i64 iVal = sessionGetI64(a); |
| 957 | a += 8; |
| 958 | if( eType==SQLITE_INTEGER ){ |
| 959 | if( sqlite3_value_int64(pVal)!=iVal ) return 0; |
| 960 | }else{ |
| 961 | double rVal; |
| 962 | assert( sizeof(iVal)==8 && sizeof(rVal)==8 ); |
| 963 | memcpy(&rVal, &iVal, 8); |
| 964 | if( sqlite3_value_double(pVal)!=rVal ) return 0; |
| 965 | } |
| 966 | }else{ |
| 967 | int n; |
| 968 | const u8 *z; |
| 969 | a += sessionVarintGet(a, &n); |
| 970 | if( sqlite3_value_bytes(pVal)!=n ) return 0; |
| 971 | if( eType==SQLITE_TEXT ){ |
| 972 | z = sqlite3_value_text(pVal); |
| 973 | }else{ |
| 974 | z = sqlite3_value_blob(pVal); |
| 975 | } |
| 976 | if( n>0 && memcmp(a, z, n) ) return 0; |
| 977 | a += n; |
| 978 | } |
| 979 | } |
| 980 | } |
| 981 | |
| 982 | return 1; |
| 983 | } |
| 984 | |
| 985 | /* |
| 986 | ** If required, grow the hash table used to store changes on table pTab |
| 987 | ** (part of the session pSession). If a fatal OOM error occurs, set the |
| 988 | ** session object to failed and return SQLITE_ERROR. Otherwise, return |
| 989 | ** SQLITE_OK. |
| 990 | ** |
| 991 | ** It is possible that a non-fatal OOM error occurs in this function. In |
| 992 | ** that case the hash-table does not grow, but SQLITE_OK is returned anyway. |
| 993 | ** Growing the hash table in this case is a performance optimization only, |
| 994 | ** it is not required for correct operation. |
| 995 | */ |
| 996 | static int sessionGrowHash( |
| 997 | sqlite3_session *pSession, /* For memory accounting. May be NULL */ |
| 998 | int bPatchset, |
| 999 | SessionTable *pTab |
| 1000 | ){ |
| 1001 | if( pTab->nChange==0 || pTab->nEntry>=(pTab->nChange/2) ){ |
| 1002 | int i; |
| 1003 | SessionChange **apNew; |
| 1004 | sqlite3_int64 nNew = 2*(sqlite3_int64)(pTab->nChange ? pTab->nChange : 128); |
| 1005 | |
| 1006 | apNew = (SessionChange**)sessionMalloc64( |
| 1007 | pSession, sizeof(SessionChange*) * nNew |
| 1008 | ); |
| 1009 | if( apNew==0 ){ |
| 1010 | if( pTab->nChange==0 ){ |
| 1011 | return SQLITE_ERROR; |
| 1012 | } |
| 1013 | return SQLITE_OK; |
| 1014 | } |
| 1015 | memset(apNew, 0, sizeof(SessionChange *) * nNew); |
| 1016 | |
| 1017 | for(i=0; i<pTab->nChange; i++){ |
| 1018 | SessionChange *p; |
| 1019 | SessionChange *pNext; |
| 1020 | for(p=pTab->apChange[i]; p; p=pNext){ |
| 1021 | int bPkOnly = (p->op==SQLITE_DELETE && bPatchset); |
| 1022 | int iHash = sessionChangeHash(pTab, bPkOnly, p->aRecord, nNew); |
| 1023 | pNext = p->pNext; |
| 1024 | p->pNext = apNew[iHash]; |
| 1025 | apNew[iHash] = p; |
| 1026 | } |
| 1027 | } |
| 1028 | |
| 1029 | sessionFree(pSession, pTab->apChange); |
| 1030 | pTab->nChange = nNew; |
| 1031 | pTab->apChange = apNew; |
| 1032 | } |
| 1033 | |
| 1034 | return SQLITE_OK; |
| 1035 | } |
| 1036 | |
| 1037 | /* |
| 1038 | ** This function queries the database for the names of the columns of table |
| 1039 | ** zThis, in schema zDb. |
| 1040 | ** |
| 1041 | ** Otherwise, if they are not NULL, variable *pnCol is set to the number |
| 1042 | ** of columns in the database table and variable *pzTab is set to point to a |
| 1043 | ** nul-terminated copy of the table name. *pazCol (if not NULL) is set to |
| 1044 | ** point to an array of pointers to column names. And *pabPK (again, if not |
| 1045 | ** NULL) is set to point to an array of booleans - true if the corresponding |
| 1046 | ** column is part of the primary key. |
| 1047 | ** |
| 1048 | ** For example, if the table is declared as: |
| 1049 | ** |
| 1050 | ** CREATE TABLE tbl1(w, x DEFAULT 'abc', y, z, PRIMARY KEY(w, z)); |
| 1051 | ** |
| 1052 | ** Then the five output variables are populated as follows: |
| 1053 | ** |
| 1054 | ** *pnCol = 4 |
| 1055 | ** *pzTab = "tbl1" |
| 1056 | ** *pazCol = {"w", "x", "y", "z"} |
| 1057 | ** *pazDflt = {NULL, 'abc', NULL, NULL} |
| 1058 | ** *pabPK = {1, 0, 0, 1} |
| 1059 | ** |
| 1060 | ** All returned buffers are part of the same single allocation, which must |
| 1061 | ** be freed using sqlite3_free() by the caller |
| 1062 | */ |
| 1063 | static int sessionTableInfo( |
| 1064 | sqlite3_session *pSession, /* For memory accounting. May be NULL */ |
| 1065 | sqlite3 *db, /* Database connection */ |
| 1066 | const char *zDb, /* Name of attached database (e.g. "main") */ |
| 1067 | const char *zThis, /* Table name */ |
| 1068 | int *pnCol, /* OUT: number of columns */ |
| 1069 | int *pnTotalCol, /* OUT: number of hidden columns */ |
| 1070 | const char **pzTab, /* OUT: Copy of zThis */ |
| 1071 | const char ***pazCol, /* OUT: Array of column names for table */ |
| 1072 | const char ***pazDflt, /* OUT: Array of default value expressions */ |
| 1073 | int **paiIdx, /* OUT: Array of xNew/xOld indexes */ |
| 1074 | u8 **pabPK, /* OUT: Array of booleans - true for PK col */ |
| 1075 | int *pbRowid /* OUT: True if only PK is a rowid */ |
| 1076 | ){ |
| 1077 | char *zPragma; |
| 1078 | sqlite3_stmt *pStmt; |
| 1079 | int rc; |
| 1080 | sqlite3_int64 nByte; |
| 1081 | int nDbCol = 0; |
| 1082 | int nThis; |
| 1083 | int i; |
| 1084 | u8 *pAlloc = 0; |
| 1085 | char **azCol = 0; |
| 1086 | char **azDflt = 0; |
| 1087 | u8 *abPK = 0; |
| 1088 | int *aiIdx = 0; |
| 1089 | int bRowid = 0; /* Set to true to use rowid as PK */ |
| 1090 | |
| 1091 | assert( pazCol && pabPK ); |
| 1092 | |
| 1093 | *pazCol = 0; |
| 1094 | *pabPK = 0; |
| 1095 | *pnCol = 0; |
| 1096 | if( pnTotalCol ) *pnTotalCol = 0; |
| 1097 | if( paiIdx ) *paiIdx = 0; |
| 1098 | if( pzTab ) *pzTab = 0; |
| 1099 | if( pazDflt ) *pazDflt = 0; |
| 1100 | |
| 1101 | nThis = sqlite3Strlen30(zThis); |
| 1102 | if( nThis==12 && 0==sqlite3_stricmp("sqlite_stat1", zThis) ){ |
| 1103 | rc = sqlite3_table_column_metadata(db, zDb, zThis, 0, 0, 0, 0, 0, 0); |
| 1104 | if( rc==SQLITE_OK ){ |
| 1105 | /* For sqlite_stat1, pretend that (tbl,idx) is the PRIMARY KEY. */ |
| 1106 | zPragma = sqlite3_mprintf( |
| 1107 | "SELECT 0, 'tbl', '', 0, '', 1, 0 UNION ALL " |
| 1108 | "SELECT 1, 'idx', '', 0, '', 2, 0 UNION ALL " |
| 1109 | "SELECT 2, 'stat', '', 0, '', 0, 0" |
| 1110 | ); |
| 1111 | }else if( rc==SQLITE_ERROR ){ |
| 1112 | zPragma = sqlite3_mprintf(""); |
| 1113 | }else{ |
| 1114 | return rc; |
| 1115 | } |
| 1116 | }else{ |
| 1117 | zPragma = sqlite3_mprintf("PRAGMA '%q'.table_xinfo('%q')", zDb, zThis); |
| 1118 | } |
| 1119 | if( !zPragma ){ |
| 1120 | return SQLITE_NOMEM; |
| 1121 | } |
| 1122 | |
| 1123 | rc = sqlite3_prepare_v2(db, zPragma, -1, &pStmt, 0); |
| 1124 | sqlite3_free(zPragma); |
| 1125 | if( rc!=SQLITE_OK ){ |
| 1126 | return rc; |
| 1127 | } |
| 1128 | |
| 1129 | nByte = nThis + 1; |
| 1130 | bRowid = (pbRowid!=0); |
| 1131 | while( SQLITE_ROW==sqlite3_step(pStmt) ){ |
| 1132 | nByte += sqlite3_column_bytes(pStmt, 1); /* name */ |
| 1133 | nByte += sqlite3_column_bytes(pStmt, 4); /* dflt_value */ |
| 1134 | if( sqlite3_column_int(pStmt, 6)==0 ){ /* !hidden */ |
| 1135 | nDbCol++; |
| 1136 | } |
| 1137 | if( sqlite3_column_int(pStmt, 5) ) bRowid = 0; /* pk */ |
| 1138 | } |
| 1139 | if( nDbCol==0 ) bRowid = 0; |
| 1140 | nDbCol += bRowid; |
| 1141 | nByte += strlen(SESSIONS_ROWID); |
| 1142 | rc = sqlite3_reset(pStmt); |
| 1143 | |
| 1144 | if( rc==SQLITE_OK ){ |
| 1145 | nByte += nDbCol * (sizeof(const char *)*2 +sizeof(int)+sizeof(u8) + 1 + 1); |
| 1146 | pAlloc = sessionMalloc64(pSession, nByte); |
| 1147 | if( pAlloc==0 ){ |
| 1148 | rc = SQLITE_NOMEM; |
| 1149 | }else{ |
| 1150 | memset(pAlloc, 0, nByte); |
| 1151 | } |
| 1152 | } |
| 1153 | if( rc==SQLITE_OK ){ |
| 1154 | azCol = (char **)pAlloc; |
| 1155 | azDflt = (char**)&azCol[nDbCol]; |
| 1156 | aiIdx = (int*)&azDflt[nDbCol]; |
| 1157 | abPK = (u8 *)&aiIdx[nDbCol]; |
| 1158 | pAlloc = &abPK[nDbCol]; |
| 1159 | if( pzTab ){ |
| 1160 | memcpy(pAlloc, zThis, nThis+1); |
| 1161 | *pzTab = (char *)pAlloc; |
| 1162 | pAlloc += nThis+1; |
| 1163 | } |
| 1164 | |
| 1165 | i = 0; |
| 1166 | if( bRowid ){ |
| 1167 | size_t nName = strlen(SESSIONS_ROWID); |
| 1168 | memcpy(pAlloc, SESSIONS_ROWID, nName+1); |
| 1169 | azCol[i] = (char*)pAlloc; |
| 1170 | pAlloc += nName+1; |
| 1171 | abPK[i] = 1; |
| 1172 | aiIdx[i] = -1; |
| 1173 | i++; |
| 1174 | } |
| 1175 | while( SQLITE_ROW==sqlite3_step(pStmt) ){ |
| 1176 | if( sqlite3_column_int(pStmt, 6)==0 ){ /* !hidden */ |
| 1177 | int nName = sqlite3_column_bytes(pStmt, 1); |
| 1178 | int nDflt = sqlite3_column_bytes(pStmt, 4); |
| 1179 | const unsigned char *zName = sqlite3_column_text(pStmt, 1); |
| 1180 | const unsigned char *zDflt = sqlite3_column_text(pStmt, 4); |
| 1181 | |
| 1182 | if( zName==0 ) break; |
| 1183 | memcpy(pAlloc, zName, nName+1); |
| 1184 | azCol[i] = (char *)pAlloc; |
| 1185 | pAlloc += nName+1; |
| 1186 | if( zDflt ){ |
| 1187 | memcpy(pAlloc, zDflt, nDflt+1); |
| 1188 | azDflt[i] = (char *)pAlloc; |
| 1189 | pAlloc += nDflt+1; |
| 1190 | }else{ |
| 1191 | azDflt[i] = 0; |
| 1192 | } |
| 1193 | abPK[i] = sqlite3_column_int(pStmt, 5); |
| 1194 | aiIdx[i] = sqlite3_column_int(pStmt, 0); |
| 1195 | i++; |
| 1196 | } |
| 1197 | if( pnTotalCol ) (*pnTotalCol)++; |
| 1198 | } |
| 1199 | rc = sqlite3_reset(pStmt); |
| 1200 | } |
| 1201 | |
| 1202 | /* If successful, populate the output variables. Otherwise, zero them and |
| 1203 | ** free any allocation made. An error code will be returned in this case. |
| 1204 | */ |
| 1205 | if( rc==SQLITE_OK ){ |
| 1206 | *pazCol = (const char**)azCol; |
| 1207 | if( pazDflt ) *pazDflt = (const char**)azDflt; |
| 1208 | *pabPK = abPK; |
| 1209 | *pnCol = nDbCol; |
| 1210 | if( paiIdx ) *paiIdx = aiIdx; |
| 1211 | }else{ |
| 1212 | sessionFree(pSession, azCol); |
| 1213 | } |
| 1214 | if( pbRowid ) *pbRowid = bRowid; |
| 1215 | sqlite3_finalize(pStmt); |
| 1216 | return rc; |
| 1217 | } |
| 1218 | |
| 1219 | /* |
| 1220 | ** This function is called to initialize the SessionTable.nCol, azCol[] |
| 1221 | ** abPK[] and azDflt[] members of SessionTable object pTab. If these |
| 1222 | ** fields are already initialized, this function is a no-op. |
| 1223 | ** |
| 1224 | ** If an error occurs, an error code is stored in sqlite3_session.rc and |
| 1225 | ** non-zero returned. Or, if no error occurs but the table has no primary |
| 1226 | ** key, sqlite3_session.rc is left set to SQLITE_OK and non-zero returned to |
| 1227 | ** indicate that updates on this table should be ignored. SessionTable.abPK |
| 1228 | ** is set to NULL in this case. |
| 1229 | */ |
| 1230 | static int sessionInitTable( |
| 1231 | sqlite3_session *pSession, /* Optional session handle */ |
| 1232 | SessionTable *pTab, /* Table object to initialize */ |
| 1233 | sqlite3 *db, /* Database handle to read schema from */ |
| 1234 | const char *zDb /* Name of db - "main", "temp" etc. */ |
| 1235 | ){ |
| 1236 | int rc = SQLITE_OK; |
| 1237 | |
| 1238 | if( pTab->nCol==0 ){ |
| 1239 | u8 *abPK; |
| 1240 | assert( pTab->azCol==0 || pTab->abPK==0 ); |
| 1241 | sqlite3_free(pTab->azCol); |
| 1242 | pTab->abPK = 0; |
| 1243 | rc = sessionTableInfo(pSession, db, zDb, |
| 1244 | pTab->zName, &pTab->nCol, &pTab->nTotalCol, 0, &pTab->azCol, |
| 1245 | &pTab->azDflt, &pTab->aiIdx, &abPK, |
| 1246 | ((pSession==0 || pSession->bImplicitPK) ? &pTab->bRowid : 0) |
| 1247 | ); |
| 1248 | if( rc==SQLITE_OK ){ |
| 1249 | int i; |
| 1250 | for(i=0; i<pTab->nCol; i++){ |
| 1251 | if( abPK[i] ){ |
| 1252 | pTab->abPK = abPK; |
| 1253 | break; |
| 1254 | } |
| 1255 | } |
| 1256 | if( 0==sqlite3_stricmp("sqlite_stat1", pTab->zName) ){ |
| 1257 | pTab->bStat1 = 1; |
| 1258 | } |
| 1259 | |
| 1260 | if( pSession && pSession->bEnableSize ){ |
| 1261 | pSession->nMaxChangesetSize += ( |
| 1262 | 1 + sessionVarintLen(pTab->nCol) + pTab->nCol + strlen(pTab->zName)+1 |
| 1263 | ); |
| 1264 | } |
| 1265 | } |
| 1266 | } |
| 1267 | |
| 1268 | if( pSession ){ |
| 1269 | pSession->rc = rc; |
| 1270 | return (rc || pTab->abPK==0); |
| 1271 | } |
| 1272 | return rc; |
| 1273 | } |
| 1274 | |
| 1275 | /* |
| 1276 | ** Re-initialize table object pTab. |
| 1277 | */ |
| 1278 | static int sessionReinitTable(sqlite3_session *pSession, SessionTable *pTab){ |
| 1279 | int nCol = 0; |
| 1280 | int nTotalCol = 0; |
| 1281 | const char **azCol = 0; |
| 1282 | const char **azDflt = 0; |
| 1283 | int *aiIdx = 0; |
| 1284 | u8 *abPK = 0; |
| 1285 | int bRowid = 0; |
| 1286 | |
| 1287 | assert( pSession->rc==SQLITE_OK ); |
| 1288 | |
| 1289 | pSession->rc = sessionTableInfo(pSession, pSession->db, pSession->zDb, |
| 1290 | pTab->zName, &nCol, &nTotalCol, 0, &azCol, &azDflt, &aiIdx, &abPK, |
| 1291 | (pSession->bImplicitPK ? &bRowid : 0) |
| 1292 | ); |
| 1293 | if( pSession->rc==SQLITE_OK ){ |
| 1294 | if( pTab->nCol>nCol || pTab->bRowid!=bRowid ){ |
| 1295 | pSession->rc = SQLITE_SCHEMA; |
| 1296 | }else{ |
| 1297 | int ii; |
| 1298 | int nOldCol = pTab->nCol; |
| 1299 | for(ii=0; ii<nCol; ii++){ |
| 1300 | if( ii<pTab->nCol ){ |
| 1301 | if( pTab->abPK[ii]!=abPK[ii] ){ |
| 1302 | pSession->rc = SQLITE_SCHEMA; |
| 1303 | } |
| 1304 | }else if( abPK[ii] ){ |
| 1305 | pSession->rc = SQLITE_SCHEMA; |
| 1306 | } |
| 1307 | } |
| 1308 | |
| 1309 | if( pSession->rc==SQLITE_OK ){ |
| 1310 | const char **a = pTab->azCol; |
| 1311 | pTab->azCol = azCol; |
| 1312 | pTab->nCol = nCol; |
| 1313 | pTab->nTotalCol = nTotalCol; |
| 1314 | pTab->azDflt = azDflt; |
| 1315 | pTab->abPK = abPK; |
| 1316 | pTab->aiIdx = aiIdx; |
| 1317 | azCol = a; |
| 1318 | } |
| 1319 | if( pSession->bEnableSize ){ |
| 1320 | pSession->nMaxChangesetSize += (nCol - nOldCol); |
| 1321 | pSession->nMaxChangesetSize += sessionVarintLen(nCol); |
| 1322 | pSession->nMaxChangesetSize -= sessionVarintLen(nOldCol); |
| 1323 | } |
| 1324 | } |
| 1325 | } |
| 1326 | |
| 1327 | sqlite3_free((char*)azCol); |
| 1328 | return pSession->rc; |
| 1329 | } |
| 1330 | |
| 1331 | /* |
| 1332 | ** Session-change object (*pp) contains an old.* record with fewer than |
| 1333 | ** nCol fields. This function updates it with the default values for |
| 1334 | ** the missing fields. |
| 1335 | */ |
| 1336 | static void sessionUpdateOneChange( |
| 1337 | sqlite3_session *pSession, /* For memory accounting */ |
| 1338 | int *pRc, /* IN/OUT: Error code */ |
| 1339 | SessionChange **pp, /* IN/OUT: Change object to update */ |
| 1340 | int nCol, /* Number of columns now in table */ |
| 1341 | sqlite3_stmt *pDflt /* SELECT <default-values...> */ |
| 1342 | ){ |
| 1343 | SessionChange *pOld = *pp; |
| 1344 | |
| 1345 | while( pOld->nRecordField<nCol ){ |
| 1346 | SessionChange *pNew = 0; |
| 1347 | int nByte = 0; |
| 1348 | int nIncr = 0; |
| 1349 | int iField = pOld->nRecordField; |
| 1350 | int eType = sqlite3_column_type(pDflt, iField); |
| 1351 | switch( eType ){ |
| 1352 | case SQLITE_NULL: |
| 1353 | nIncr = 1; |
| 1354 | break; |
| 1355 | case SQLITE_INTEGER: |
| 1356 | case SQLITE_FLOAT: |
| 1357 | nIncr = 9; |
| 1358 | break; |
| 1359 | default: { |
| 1360 | int n = sqlite3_column_bytes(pDflt, iField); |
| 1361 | nIncr = 1 + sessionVarintLen(n) + n; |
| 1362 | assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB ); |
| 1363 | break; |
| 1364 | } |
| 1365 | } |
| 1366 | |
| 1367 | nByte = nIncr + (sizeof(SessionChange) + pOld->nRecord); |
| 1368 | pNew = sessionMalloc64(pSession, nByte); |
| 1369 | if( pNew==0 ){ |
| 1370 | *pRc = SQLITE_NOMEM; |
| 1371 | return; |
| 1372 | }else{ |
| 1373 | memcpy(pNew, pOld, sizeof(SessionChange)); |
| 1374 | pNew->aRecord = (u8*)&pNew[1]; |
| 1375 | memcpy(pNew->aRecord, pOld->aRecord, pOld->nRecord); |
| 1376 | pNew->aRecord[pNew->nRecord++] = (u8)eType; |
| 1377 | switch( eType ){ |
| 1378 | case SQLITE_INTEGER: { |
| 1379 | i64 iVal = sqlite3_column_int64(pDflt, iField); |
| 1380 | sessionPutI64(&pNew->aRecord[pNew->nRecord], iVal); |
| 1381 | pNew->nRecord += 8; |
| 1382 | break; |
| 1383 | } |
| 1384 | |
| 1385 | case SQLITE_FLOAT: { |
| 1386 | double rVal = sqlite3_column_double(pDflt, iField); |
| 1387 | sessionPutDouble(&pNew->aRecord[pNew->nRecord], rVal); |
| 1388 | pNew->nRecord += 8; |
| 1389 | break; |
| 1390 | } |
| 1391 | |
| 1392 | case SQLITE_TEXT: { |
| 1393 | int n = sqlite3_column_bytes(pDflt, iField); |
| 1394 | const char *z = (const char*)sqlite3_column_text(pDflt, iField); |
| 1395 | pNew->nRecord += sessionVarintPut(&pNew->aRecord[pNew->nRecord], n); |
| 1396 | memcpy(&pNew->aRecord[pNew->nRecord], z, n); |
| 1397 | pNew->nRecord += n; |
| 1398 | break; |
| 1399 | } |
| 1400 | |
| 1401 | case SQLITE_BLOB: { |
| 1402 | int n = sqlite3_column_bytes(pDflt, iField); |
| 1403 | const u8 *z = (const u8*)sqlite3_column_blob(pDflt, iField); |
| 1404 | pNew->nRecord += sessionVarintPut(&pNew->aRecord[pNew->nRecord], n); |
| 1405 | memcpy(&pNew->aRecord[pNew->nRecord], z, n); |
| 1406 | pNew->nRecord += n; |
| 1407 | break; |
| 1408 | } |
| 1409 | |
| 1410 | default: |
| 1411 | assert( eType==SQLITE_NULL ); |
| 1412 | break; |
| 1413 | } |
| 1414 | |
| 1415 | sessionFree(pSession, pOld); |
| 1416 | *pp = pOld = pNew; |
| 1417 | pNew->nRecordField++; |
| 1418 | pNew->nMaxSize += nIncr; |
| 1419 | if( pSession ){ |
| 1420 | pSession->nMaxChangesetSize += nIncr; |
| 1421 | } |
| 1422 | } |
| 1423 | } |
| 1424 | } |
| 1425 | |
| 1426 | /* |
| 1427 | ** Ensure that there is room in the buffer to append nByte bytes of data. |
| 1428 | ** If not, use sqlite3_realloc() to grow the buffer so that there is. |
| 1429 | ** |
| 1430 | ** If successful, return zero. Otherwise, if an OOM condition is encountered, |
| 1431 | ** set *pRc to SQLITE_NOMEM and return non-zero. |
| 1432 | */ |
| 1433 | static int sessionBufferGrow(SessionBuffer *p, i64 nByte, int *pRc){ |
| 1434 | #define SESSION_MAX_BUFFER_SZ (0x7FFFFF00 - 1) |
| 1435 | i64 nReq = p->nBuf + nByte; |
| 1436 | if( *pRc==SQLITE_OK && nReq>p->nAlloc ){ |
| 1437 | u8 *aNew; |
| 1438 | i64 nNew = p->nAlloc ? p->nAlloc : 128; |
| 1439 | |
| 1440 | do { |
| 1441 | nNew = nNew*2; |
| 1442 | }while( nNew<nReq ); |
| 1443 | |
| 1444 | /* The value of SESSION_MAX_BUFFER_SZ is copied from the implementation |
| 1445 | ** of sqlite3_realloc64(). Allocations greater than this size in bytes |
| 1446 | ** always fail. It is used here to ensure that this routine can always |
| 1447 | ** allocate up to this limit - instead of up to the largest power of |
| 1448 | ** two smaller than the limit. */ |
| 1449 | if( nNew>SESSION_MAX_BUFFER_SZ ){ |
| 1450 | nNew = SESSION_MAX_BUFFER_SZ; |
| 1451 | if( nNew<nReq ){ |
| 1452 | *pRc = SQLITE_NOMEM; |
| 1453 | return 1; |
| 1454 | } |
| 1455 | } |
| 1456 | |
| 1457 | aNew = (u8 *)sqlite3_realloc64(p->aBuf, nNew); |
| 1458 | if( 0==aNew ){ |
| 1459 | *pRc = SQLITE_NOMEM; |
| 1460 | }else{ |
| 1461 | p->aBuf = aNew; |
| 1462 | p->nAlloc = nNew; |
| 1463 | } |
| 1464 | } |
| 1465 | return (*pRc!=SQLITE_OK); |
| 1466 | } |
| 1467 | |
| 1468 | |
| 1469 | /* |
| 1470 | ** This function is a no-op if *pRc is other than SQLITE_OK when it is |
| 1471 | ** called. Otherwise, append a string to the buffer. All bytes in the string |
| 1472 | ** up to (but not including) the nul-terminator are written to the buffer. |
| 1473 | ** |
| 1474 | ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before |
| 1475 | ** returning. |
| 1476 | */ |
| 1477 | static void sessionAppendStr( |
| 1478 | SessionBuffer *p, |
| 1479 | const char *zStr, |
| 1480 | int *pRc |
| 1481 | ){ |
| 1482 | int nStr = sqlite3Strlen30(zStr); |
| 1483 | if( 0==sessionBufferGrow(p, (i64)nStr+1, pRc) ){ |
| 1484 | memcpy(&p->aBuf[p->nBuf], zStr, nStr); |
| 1485 | p->nBuf += nStr; |
| 1486 | p->aBuf[p->nBuf] = 0x00; |
| 1487 | } |
| 1488 | } |
| 1489 | |
| 1490 | /* |
| 1491 | ** Format a string using printf() style formatting and then append it to the |
| 1492 | ** buffer using sessionAppendString(). |
| 1493 | */ |
| 1494 | static void sessionAppendPrintf( |
| 1495 | SessionBuffer *p, /* Buffer to append to */ |
| 1496 | int *pRc, |
| 1497 | const char *zFmt, |
| 1498 | ... |
| 1499 | ){ |
| 1500 | if( *pRc==SQLITE_OK ){ |
| 1501 | char *zApp = 0; |
| 1502 | va_list ap; |
| 1503 | va_start(ap, zFmt); |
| 1504 | zApp = sqlite3_vmprintf(zFmt, ap); |
| 1505 | if( zApp==0 ){ |
| 1506 | *pRc = SQLITE_NOMEM; |
| 1507 | }else{ |
| 1508 | sessionAppendStr(p, zApp, pRc); |
| 1509 | } |
| 1510 | va_end(ap); |
| 1511 | sqlite3_free(zApp); |
| 1512 | } |
| 1513 | } |
| 1514 | |
| 1515 | /* |
| 1516 | ** Prepare a statement against database handle db that SELECTs a single |
| 1517 | ** row containing the default values for each column in table pTab. For |
| 1518 | ** example, if pTab is declared as: |
| 1519 | ** |
| 1520 | ** CREATE TABLE pTab(a PRIMARY KEY, b DEFAULT 123, c DEFAULT 'abcd'); |
| 1521 | ** |
| 1522 | ** Then this function prepares and returns the SQL statement: |
| 1523 | ** |
| 1524 | ** SELECT NULL, 123, 'abcd'; |
| 1525 | */ |
| 1526 | static int sessionPrepareDfltStmt( |
| 1527 | sqlite3 *db, /* Database handle */ |
| 1528 | SessionTable *pTab, /* Table to prepare statement for */ |
| 1529 | sqlite3_stmt **ppStmt /* OUT: Statement handle */ |
| 1530 | ){ |
| 1531 | SessionBuffer sql = {0,0,0}; |
| 1532 | int rc = SQLITE_OK; |
| 1533 | const char *zSep = " "; |
| 1534 | int ii = 0; |
| 1535 | |
| 1536 | *ppStmt = 0; |
| 1537 | sessionAppendPrintf(&sql, &rc, "SELECT"); |
| 1538 | for(ii=0; ii<pTab->nCol; ii++){ |
| 1539 | const char *zDflt = pTab->azDflt[ii] ? pTab->azDflt[ii] : "NULL"; |
| 1540 | sessionAppendPrintf(&sql, &rc, "%s%s", zSep, zDflt); |
| 1541 | zSep = ", "; |
| 1542 | } |
| 1543 | if( rc==SQLITE_OK ){ |
| 1544 | rc = sqlite3_prepare_v2(db, (const char*)sql.aBuf, -1, ppStmt, 0); |
| 1545 | } |
| 1546 | sqlite3_free(sql.aBuf); |
| 1547 | |
| 1548 | return rc; |
| 1549 | } |
| 1550 | |
| 1551 | /* |
| 1552 | ** Finalize statement pStmt. If (*pRc) is SQLITE_OK when this function is |
| 1553 | ** called, set it to the results of the sqlite3_finalize() call. Or, if |
| 1554 | ** it is already set to an error code, leave it as is. |
| 1555 | */ |
| 1556 | static void sessionFinalizeStmt(sqlite3_stmt *pStmt, int *pRc){ |
| 1557 | int rc = sqlite3_finalize(pStmt); |
| 1558 | if( *pRc==SQLITE_OK ) *pRc = rc; |
| 1559 | } |
| 1560 | |
| 1561 | /* |
| 1562 | ** Table pTab has one or more existing change-records with old.* records |
| 1563 | ** with fewer than pTab->nCol columns. This function updates all such |
| 1564 | ** change-records with the default values for the missing columns. |
| 1565 | */ |
| 1566 | static int sessionUpdateChanges(sqlite3_session *pSession, SessionTable *pTab){ |
| 1567 | sqlite3_stmt *pStmt = 0; |
| 1568 | int rc = pSession->rc; |
| 1569 | |
| 1570 | rc = sessionPrepareDfltStmt(pSession->db, pTab, &pStmt); |
| 1571 | if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ |
| 1572 | int ii = 0; |
| 1573 | SessionChange **pp = 0; |
| 1574 | for(ii=0; ii<pTab->nChange; ii++){ |
| 1575 | for(pp=&pTab->apChange[ii]; *pp; pp=&((*pp)->pNext)){ |
| 1576 | if( (*pp)->nRecordField!=pTab->nCol ){ |
| 1577 | sessionUpdateOneChange(pSession, &rc, pp, pTab->nCol, pStmt); |
| 1578 | } |
| 1579 | } |
| 1580 | } |
| 1581 | } |
| 1582 | |
| 1583 | sessionFinalizeStmt(pStmt, &rc); |
| 1584 | pSession->rc = rc; |
| 1585 | return pSession->rc; |
| 1586 | } |
| 1587 | |
| 1588 | /* |
| 1589 | ** Versions of the four methods in object SessionHook for use with the |
| 1590 | ** sqlite_stat1 table. The purpose of this is to substitute a zero-length |
| 1591 | ** blob each time a NULL value is read from the "idx" column of the |
| 1592 | ** sqlite_stat1 table. |
| 1593 | */ |
| 1594 | typedef struct SessionStat1Ctx SessionStat1Ctx; |
| 1595 | struct SessionStat1Ctx { |
| 1596 | SessionHook hook; |
| 1597 | sqlite3_session *pSession; |
| 1598 | }; |
| 1599 | static int sessionStat1Old(void *pCtx, int iCol, sqlite3_value **ppVal){ |
| 1600 | SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx; |
| 1601 | sqlite3_value *pVal = 0; |
| 1602 | int rc = p->hook.xOld(p->hook.pCtx, iCol, &pVal); |
| 1603 | if( rc==SQLITE_OK && iCol==1 && sqlite3_value_type(pVal)==SQLITE_NULL ){ |
| 1604 | pVal = p->pSession->pZeroBlob; |
| 1605 | } |
| 1606 | *ppVal = pVal; |
| 1607 | return rc; |
| 1608 | } |
| 1609 | static int sessionStat1New(void *pCtx, int iCol, sqlite3_value **ppVal){ |
| 1610 | SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx; |
| 1611 | sqlite3_value *pVal = 0; |
| 1612 | int rc = p->hook.xNew(p->hook.pCtx, iCol, &pVal); |
| 1613 | if( rc==SQLITE_OK && iCol==1 && sqlite3_value_type(pVal)==SQLITE_NULL ){ |
| 1614 | pVal = p->pSession->pZeroBlob; |
| 1615 | } |
| 1616 | *ppVal = pVal; |
| 1617 | return rc; |
| 1618 | } |
| 1619 | static int sessionStat1Count(void *pCtx){ |
| 1620 | SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx; |
| 1621 | return p->hook.xCount(p->hook.pCtx); |
| 1622 | } |
| 1623 | static int sessionStat1Depth(void *pCtx){ |
| 1624 | SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx; |
| 1625 | return p->hook.xDepth(p->hook.pCtx); |
| 1626 | } |
| 1627 | |
| 1628 | static int sessionUpdateMaxSize( |
| 1629 | int op, |
| 1630 | sqlite3_session *pSession, /* Session object pTab is attached to */ |
| 1631 | SessionTable *pTab, /* Table that change applies to */ |
| 1632 | SessionChange *pC /* Update pC->nMaxSize */ |
| 1633 | ){ |
| 1634 | i64 nNew = 2; |
| 1635 | if( pC->op==SQLITE_INSERT ){ |
| 1636 | if( pTab->bRowid ) nNew += 9; |
| 1637 | if( op!=SQLITE_DELETE ){ |
| 1638 | int ii; |
| 1639 | for(ii=0; ii<pTab->nCol; ii++){ |
| 1640 | sqlite3_value *p = 0; |
| 1641 | pSession->hook.xNew(pSession->hook.pCtx, pTab->aiIdx[ii], &p); |
| 1642 | sessionSerializeValue(0, p, &nNew); |
| 1643 | } |
| 1644 | } |
| 1645 | }else if( op==SQLITE_DELETE ){ |
| 1646 | nNew += pC->nRecord; |
| 1647 | if( sqlite3_preupdate_blobwrite(pSession->db)>=0 ){ |
| 1648 | nNew += pC->nRecord; |
| 1649 | } |
| 1650 | }else{ |
| 1651 | int ii; |
| 1652 | u8 *pCsr = pC->aRecord; |
| 1653 | if( pTab->bRowid ){ |
| 1654 | nNew += 9 + 1; |
| 1655 | pCsr += 9; |
| 1656 | } |
| 1657 | for(ii=pTab->bRowid; ii<pTab->nCol; ii++){ |
| 1658 | int bChanged = 1; |
| 1659 | int nOld = 0; |
| 1660 | int eType; |
| 1661 | int iIdx = pTab->aiIdx[ii]; |
| 1662 | sqlite3_value *p = 0; |
| 1663 | pSession->hook.xNew(pSession->hook.pCtx, iIdx, &p); |
| 1664 | if( p==0 ){ |
| 1665 | return SQLITE_NOMEM; |
| 1666 | } |
| 1667 | |
| 1668 | eType = *pCsr++; |
| 1669 | switch( eType ){ |
| 1670 | case SQLITE_NULL: |
| 1671 | bChanged = sqlite3_value_type(p)!=SQLITE_NULL; |
| 1672 | break; |
| 1673 | |
| 1674 | case SQLITE_FLOAT: |
| 1675 | case SQLITE_INTEGER: { |
| 1676 | if( eType==sqlite3_value_type(p) ){ |
| 1677 | sqlite3_int64 iVal = sessionGetI64(pCsr); |
| 1678 | if( eType==SQLITE_INTEGER ){ |
| 1679 | bChanged = (iVal!=sqlite3_value_int64(p)); |
| 1680 | }else{ |
| 1681 | double dVal; |
| 1682 | memcpy(&dVal, &iVal, 8); |
| 1683 | bChanged = (dVal!=sqlite3_value_double(p)); |
| 1684 | } |
| 1685 | } |
| 1686 | nOld = 8; |
| 1687 | pCsr += 8; |
| 1688 | break; |
| 1689 | } |
| 1690 | |
| 1691 | default: { |
| 1692 | int nByte; |
| 1693 | nOld = sessionVarintGet(pCsr, &nByte); |
| 1694 | pCsr += nOld; |
| 1695 | nOld += nByte; |
| 1696 | assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB ); |
| 1697 | if( eType==sqlite3_value_type(p) |
| 1698 | && nByte==sqlite3_value_bytes(p) |
| 1699 | && (nByte==0 || 0==memcmp(pCsr, sqlite3_value_blob(p), nByte)) |
| 1700 | ){ |
| 1701 | bChanged = 0; |
| 1702 | } |
| 1703 | pCsr += nByte; |
| 1704 | break; |
| 1705 | } |
| 1706 | } |
| 1707 | |
| 1708 | if( bChanged && pTab->abPK[ii] ){ |
| 1709 | nNew = pC->nRecord + 2; |
| 1710 | break; |
| 1711 | } |
| 1712 | |
| 1713 | if( bChanged ){ |
| 1714 | nNew += 1 + nOld; |
| 1715 | sessionSerializeValue(0, p, &nNew); |
| 1716 | }else if( pTab->abPK[ii] ){ |
| 1717 | nNew += 2 + nOld; |
| 1718 | }else{ |
| 1719 | nNew += 2; |
| 1720 | } |
| 1721 | } |
| 1722 | } |
| 1723 | |
| 1724 | if( nNew>pC->nMaxSize ){ |
| 1725 | int nIncr = nNew - pC->nMaxSize; |
| 1726 | pC->nMaxSize = nNew; |
| 1727 | pSession->nMaxChangesetSize += nIncr; |
| 1728 | } |
| 1729 | return SQLITE_OK; |
| 1730 | } |
| 1731 | |
| 1732 | /* |
| 1733 | ** This function is only called from with a pre-update-hook reporting a |
| 1734 | ** change on table pTab (attached to session pSession). The type of change |
| 1735 | ** (UPDATE, INSERT, DELETE) is specified by the first argument. |
| 1736 | ** |
| 1737 | ** Unless one is already present or an error occurs, an entry is added |
| 1738 | ** to the changed-rows hash table associated with table pTab. |
| 1739 | */ |
| 1740 | static void sessionPreupdateOneChange( |
| 1741 | int op, /* One of SQLITE_UPDATE, INSERT, DELETE */ |
| 1742 | i64 iRowid, |
| 1743 | sqlite3_session *pSession, /* Session object pTab is attached to */ |
| 1744 | SessionTable *pTab /* Table that change applies to */ |
| 1745 | ){ |
| 1746 | int iHash; |
| 1747 | int bNull = 0; |
| 1748 | int rc = SQLITE_OK; |
| 1749 | int nExpect = 0; |
| 1750 | SessionStat1Ctx stat1 = {{0,0,0,0,0},0}; |
| 1751 | |
| 1752 | if( pSession->rc ) return; |
| 1753 | |
| 1754 | /* Load table details if required */ |
| 1755 | if( sessionInitTable(pSession, pTab, pSession->db, pSession->zDb) ) return; |
| 1756 | |
| 1757 | /* Check the number of columns in this xPreUpdate call matches the |
| 1758 | ** number of columns in the table. */ |
| 1759 | nExpect = pSession->hook.xCount(pSession->hook.pCtx); |
| 1760 | if( pTab->nTotalCol<nExpect ){ |
| 1761 | if( sessionReinitTable(pSession, pTab) ) return; |
| 1762 | if( sessionUpdateChanges(pSession, pTab) ) return; |
| 1763 | } |
| 1764 | if( pTab->nTotalCol!=nExpect ){ |
| 1765 | pSession->rc = SQLITE_SCHEMA; |
| 1766 | return; |
| 1767 | } |
| 1768 | |
| 1769 | /* Grow the hash table if required */ |
| 1770 | if( sessionGrowHash(pSession, 0, pTab) ){ |
| 1771 | pSession->rc = SQLITE_NOMEM; |
| 1772 | return; |
| 1773 | } |
| 1774 | |
| 1775 | if( pTab->bStat1 ){ |
| 1776 | stat1.hook = pSession->hook; |
| 1777 | stat1.pSession = pSession; |
| 1778 | pSession->hook.pCtx = (void*)&stat1; |
| 1779 | pSession->hook.xNew = sessionStat1New; |
| 1780 | pSession->hook.xOld = sessionStat1Old; |
| 1781 | pSession->hook.xCount = sessionStat1Count; |
| 1782 | pSession->hook.xDepth = sessionStat1Depth; |
| 1783 | if( pSession->pZeroBlob==0 ){ |
| 1784 | sqlite3_value *p = sqlite3ValueNew(0); |
| 1785 | if( p==0 ){ |
| 1786 | rc = SQLITE_NOMEM; |
| 1787 | goto error_out; |
| 1788 | } |
| 1789 | sqlite3ValueSetStr(p, 0, "", 0, SQLITE_STATIC); |
| 1790 | pSession->pZeroBlob = p; |
| 1791 | } |
| 1792 | } |
| 1793 | |
| 1794 | /* Calculate the hash-key for this change. If the primary key of the row |
| 1795 | ** includes a NULL value, exit early. Such changes are ignored by the |
| 1796 | ** session module. */ |
| 1797 | rc = sessionPreupdateHash( |
| 1798 | pSession, iRowid, pTab, op==SQLITE_INSERT, &iHash, &bNull |
| 1799 | ); |
| 1800 | if( rc!=SQLITE_OK ) goto error_out; |
| 1801 | |
| 1802 | if( bNull==0 ){ |
| 1803 | /* Search the hash table for an existing record for this row. */ |
| 1804 | SessionChange *pC; |
| 1805 | for(pC=pTab->apChange[iHash]; pC; pC=pC->pNext){ |
| 1806 | if( sessionPreupdateEqual(pSession, iRowid, pTab, pC, op) ) break; |
| 1807 | } |
| 1808 | |
| 1809 | if( pC==0 ){ |
| 1810 | /* Create a new change object containing all the old values (if |
| 1811 | ** this is an SQLITE_UPDATE or SQLITE_DELETE), or just the PK |
| 1812 | ** values (if this is an INSERT). */ |
| 1813 | sqlite3_int64 nByte; /* Number of bytes to allocate */ |
| 1814 | int i; /* Used to iterate through columns */ |
| 1815 | |
| 1816 | assert( rc==SQLITE_OK ); |
| 1817 | pTab->nEntry++; |
| 1818 | |
| 1819 | /* Figure out how large an allocation is required */ |
| 1820 | nByte = sizeof(SessionChange); |
| 1821 | for(i=pTab->bRowid; i<pTab->nCol; i++){ |
| 1822 | int iIdx = pTab->aiIdx[i]; |
| 1823 | sqlite3_value *p = 0; |
| 1824 | if( op!=SQLITE_INSERT ){ |
| 1825 | /* This may fail if the column has a non-NULL default and was added |
| 1826 | ** using ALTER TABLE ADD COLUMN after this record was created. */ |
| 1827 | rc = pSession->hook.xOld(pSession->hook.pCtx, iIdx, &p); |
| 1828 | }else if( pTab->abPK[i] ){ |
| 1829 | TESTONLY(int trc = ) pSession->hook.xNew(pSession->hook.pCtx,iIdx,&p); |
| 1830 | assert( trc==SQLITE_OK ); |
| 1831 | } |
| 1832 | |
| 1833 | if( rc==SQLITE_OK ){ |
| 1834 | /* This may fail if SQLite value p contains a utf-16 string that must |
| 1835 | ** be converted to utf-8 and an OOM error occurs while doing so. */ |
| 1836 | rc = sessionSerializeValue(0, p, &nByte); |
| 1837 | } |
| 1838 | if( rc!=SQLITE_OK ) goto error_out; |
| 1839 | } |
| 1840 | if( pTab->bRowid ){ |
| 1841 | nByte += 9; /* Size of rowid field - an integer */ |
| 1842 | } |
| 1843 | |
| 1844 | /* Allocate the change object */ |
| 1845 | pC = (SessionChange*)sessionMalloc64(pSession, nByte); |
| 1846 | if( !pC ){ |
| 1847 | rc = SQLITE_NOMEM; |
| 1848 | goto error_out; |
| 1849 | }else{ |
| 1850 | memset(pC, 0, sizeof(SessionChange)); |
| 1851 | pC->aRecord = (u8 *)&pC[1]; |
| 1852 | } |
| 1853 | |
| 1854 | /* Populate the change object. None of the preupdate_old(), |
| 1855 | ** preupdate_new() or SerializeValue() calls below may fail as all |
| 1856 | ** required values and encodings have already been cached in memory. |
| 1857 | ** It is not possible for an OOM to occur in this block. */ |
| 1858 | nByte = 0; |
| 1859 | if( pTab->bRowid ){ |
| 1860 | pC->aRecord[0] = SQLITE_INTEGER; |
| 1861 | sessionPutI64(&pC->aRecord[1], iRowid); |
| 1862 | nByte = 9; |
| 1863 | } |
| 1864 | for(i=pTab->bRowid; i<pTab->nCol; i++){ |
| 1865 | sqlite3_value *p = 0; |
| 1866 | int iIdx = pTab->aiIdx[i]; |
| 1867 | if( op!=SQLITE_INSERT ){ |
| 1868 | pSession->hook.xOld(pSession->hook.pCtx, iIdx, &p); |
| 1869 | }else if( pTab->abPK[i] ){ |
| 1870 | pSession->hook.xNew(pSession->hook.pCtx, iIdx, &p); |
| 1871 | } |
| 1872 | sessionSerializeValue(&pC->aRecord[nByte], p, &nByte); |
| 1873 | } |
| 1874 | |
| 1875 | /* Add the change to the hash-table */ |
| 1876 | if( pSession->bIndirect || pSession->hook.xDepth(pSession->hook.pCtx) ){ |
| 1877 | pC->bIndirect = 1; |
| 1878 | } |
| 1879 | pC->nRecordField = pTab->nCol; |
| 1880 | pC->nRecord = nByte; |
| 1881 | pC->op = op; |
| 1882 | pC->pNext = pTab->apChange[iHash]; |
| 1883 | pTab->apChange[iHash] = pC; |
| 1884 | |
| 1885 | }else if( pC->bIndirect ){ |
| 1886 | /* If the existing change is considered "indirect", but this current |
| 1887 | ** change is "direct", mark the change object as direct. */ |
| 1888 | if( pSession->hook.xDepth(pSession->hook.pCtx)==0 |
| 1889 | && pSession->bIndirect==0 |
| 1890 | ){ |
| 1891 | pC->bIndirect = 0; |
| 1892 | } |
| 1893 | } |
| 1894 | |
| 1895 | assert( rc==SQLITE_OK ); |
| 1896 | if( pSession->bEnableSize ){ |
| 1897 | rc = sessionUpdateMaxSize(op, pSession, pTab, pC); |
| 1898 | } |
| 1899 | } |
| 1900 | |
| 1901 | |
| 1902 | /* If an error has occurred, mark the session object as failed. */ |
| 1903 | error_out: |
| 1904 | if( pTab->bStat1 ){ |
| 1905 | pSession->hook = stat1.hook; |
| 1906 | } |
| 1907 | if( rc!=SQLITE_OK ){ |
| 1908 | pSession->rc = rc; |
| 1909 | } |
| 1910 | } |
| 1911 | |
| 1912 | static int sessionFindTable( |
| 1913 | sqlite3_session *pSession, |
| 1914 | const char *zName, |
| 1915 | SessionTable **ppTab |
| 1916 | ){ |
| 1917 | int rc = SQLITE_OK; |
| 1918 | int nName = sqlite3Strlen30(zName); |
| 1919 | SessionTable *pRet; |
| 1920 | |
| 1921 | /* Search for an existing table */ |
| 1922 | for(pRet=pSession->pTable; pRet; pRet=pRet->pNext){ |
| 1923 | if( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) ) break; |
| 1924 | } |
| 1925 | |
| 1926 | if( pRet==0 && pSession->bAutoAttach ){ |
| 1927 | /* If there is a table-filter configured, invoke it. If it returns 0, |
| 1928 | ** do not automatically add the new table. */ |
| 1929 | if( pSession->xTableFilter==0 |
| 1930 | || pSession->xTableFilter(pSession->pFilterCtx, zName) |
| 1931 | ){ |
| 1932 | rc = sqlite3session_attach(pSession, zName); |
| 1933 | if( rc==SQLITE_OK ){ |
| 1934 | pRet = pSession->pTable; |
| 1935 | while( ALWAYS(pRet) && pRet->pNext ){ |
| 1936 | pRet = pRet->pNext; |
| 1937 | } |
| 1938 | assert( pRet!=0 ); |
| 1939 | assert( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) ); |
| 1940 | } |
| 1941 | } |
| 1942 | } |
| 1943 | |
| 1944 | assert( rc==SQLITE_OK || pRet==0 ); |
| 1945 | *ppTab = pRet; |
| 1946 | return rc; |
| 1947 | } |
| 1948 | |
| 1949 | /* |
| 1950 | ** The 'pre-update' hook registered by this module with SQLite databases. |
| 1951 | */ |
| 1952 | static void xPreUpdate( |
| 1953 | void *pCtx, /* Copy of third arg to preupdate_hook() */ |
| 1954 | sqlite3 *db, /* Database handle */ |
| 1955 | int op, /* SQLITE_UPDATE, DELETE or INSERT */ |
| 1956 | char const *zDb, /* Database name */ |
| 1957 | char const *zName, /* Table name */ |
| 1958 | sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */ |
| 1959 | sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */ |
| 1960 | ){ |
| 1961 | sqlite3_session *pSession; |
| 1962 | int nDb = sqlite3Strlen30(zDb); |
| 1963 | |
| 1964 | assert( sqlite3_mutex_held(db->mutex) ); |
| 1965 | (void)iKey1; |
| 1966 | (void)iKey2; |
| 1967 | |
| 1968 | for(pSession=(sqlite3_session *)pCtx; pSession; pSession=pSession->pNext){ |
| 1969 | SessionTable *pTab; |
| 1970 | |
| 1971 | /* If this session is attached to a different database ("main", "temp" |
| 1972 | ** etc.), or if it is not currently enabled, there is nothing to do. Skip |
| 1973 | ** to the next session object attached to this database. */ |
| 1974 | if( pSession->bEnable==0 ) continue; |
| 1975 | if( pSession->rc ) continue; |
| 1976 | if( sqlite3_strnicmp(zDb, pSession->zDb, nDb+1) ) continue; |
| 1977 | |
| 1978 | pSession->rc = sessionFindTable(pSession, zName, &pTab); |
| 1979 | if( pTab ){ |
| 1980 | assert( pSession->rc==SQLITE_OK ); |
| 1981 | assert( op==SQLITE_UPDATE || iKey1==iKey2 ); |
| 1982 | sessionPreupdateOneChange(op, iKey1, pSession, pTab); |
| 1983 | if( op==SQLITE_UPDATE ){ |
| 1984 | sessionPreupdateOneChange(SQLITE_INSERT, iKey2, pSession, pTab); |
| 1985 | } |
| 1986 | } |
| 1987 | } |
| 1988 | } |
| 1989 | |
| 1990 | /* |
| 1991 | ** The pre-update hook implementations. |
| 1992 | */ |
| 1993 | static int sessionPreupdateOld(void *pCtx, int iVal, sqlite3_value **ppVal){ |
| 1994 | return sqlite3_preupdate_old((sqlite3*)pCtx, iVal, ppVal); |
| 1995 | } |
| 1996 | static int sessionPreupdateNew(void *pCtx, int iVal, sqlite3_value **ppVal){ |
| 1997 | return sqlite3_preupdate_new((sqlite3*)pCtx, iVal, ppVal); |
| 1998 | } |
| 1999 | static int sessionPreupdateCount(void *pCtx){ |
| 2000 | return sqlite3_preupdate_count((sqlite3*)pCtx); |
| 2001 | } |
| 2002 | static int sessionPreupdateDepth(void *pCtx){ |
| 2003 | return sqlite3_preupdate_depth((sqlite3*)pCtx); |
| 2004 | } |
| 2005 | |
| 2006 | /* |
| 2007 | ** Install the pre-update hooks on the session object passed as the only |
| 2008 | ** argument. |
| 2009 | */ |
| 2010 | static void sessionPreupdateHooks( |
| 2011 | sqlite3_session *pSession |
| 2012 | ){ |
| 2013 | pSession->hook.pCtx = (void*)pSession->db; |
| 2014 | pSession->hook.xOld = sessionPreupdateOld; |
| 2015 | pSession->hook.xNew = sessionPreupdateNew; |
| 2016 | pSession->hook.xCount = sessionPreupdateCount; |
| 2017 | pSession->hook.xDepth = sessionPreupdateDepth; |
| 2018 | } |
| 2019 | |
| 2020 | typedef struct SessionDiffCtx SessionDiffCtx; |
| 2021 | struct SessionDiffCtx { |
| 2022 | sqlite3_stmt *pStmt; |
| 2023 | int bRowid; |
| 2024 | int nOldOff; |
| 2025 | }; |
| 2026 | |
| 2027 | /* |
| 2028 | ** The diff hook implementations. |
| 2029 | */ |
| 2030 | static int sessionDiffOld(void *pCtx, int iVal, sqlite3_value **ppVal){ |
| 2031 | SessionDiffCtx *p = (SessionDiffCtx*)pCtx; |
| 2032 | *ppVal = sqlite3_column_value(p->pStmt, iVal+p->nOldOff+p->bRowid); |
| 2033 | return SQLITE_OK; |
| 2034 | } |
| 2035 | static int sessionDiffNew(void *pCtx, int iVal, sqlite3_value **ppVal){ |
| 2036 | SessionDiffCtx *p = (SessionDiffCtx*)pCtx; |
| 2037 | *ppVal = sqlite3_column_value(p->pStmt, iVal+p->bRowid); |
| 2038 | return SQLITE_OK; |
| 2039 | } |
| 2040 | static int sessionDiffCount(void *pCtx){ |
| 2041 | SessionDiffCtx *p = (SessionDiffCtx*)pCtx; |
| 2042 | return (p->nOldOff ? p->nOldOff : sqlite3_column_count(p->pStmt)) - p->bRowid; |
| 2043 | } |
| 2044 | static int sessionDiffDepth(void *pCtx){ |
| 2045 | (void)pCtx; |
| 2046 | return 0; |
| 2047 | } |
| 2048 | |
| 2049 | /* |
| 2050 | ** Install the diff hooks on the session object passed as the only |
| 2051 | ** argument. |
| 2052 | */ |
| 2053 | static void sessionDiffHooks( |
| 2054 | sqlite3_session *pSession, |
| 2055 | SessionDiffCtx *pDiffCtx |
| 2056 | ){ |
| 2057 | pSession->hook.pCtx = (void*)pDiffCtx; |
| 2058 | pSession->hook.xOld = sessionDiffOld; |
| 2059 | pSession->hook.xNew = sessionDiffNew; |
| 2060 | pSession->hook.xCount = sessionDiffCount; |
| 2061 | pSession->hook.xDepth = sessionDiffDepth; |
| 2062 | } |
| 2063 | |
| 2064 | static char *sessionExprComparePK( |
| 2065 | int nCol, |
| 2066 | const char *zDb1, const char *zDb2, |
| 2067 | const char *zTab, |
| 2068 | const char **azCol, u8 *abPK |
| 2069 | ){ |
| 2070 | int i; |
| 2071 | const char *zSep = ""; |
| 2072 | char *zRet = 0; |
| 2073 | |
| 2074 | for(i=0; i<nCol; i++){ |
| 2075 | if( abPK[i] ){ |
| 2076 | zRet = sqlite3_mprintf("%z%s\"%w\".\"%w\".\"%w\"=\"%w\".\"%w\".\"%w\"", |
| 2077 | zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i] |
| 2078 | ); |
| 2079 | zSep = " AND "; |
| 2080 | if( zRet==0 ) break; |
| 2081 | } |
| 2082 | } |
| 2083 | |
| 2084 | return zRet; |
| 2085 | } |
| 2086 | |
| 2087 | static char *sessionExprCompareOther( |
| 2088 | int nCol, |
| 2089 | const char *zDb1, const char *zDb2, |
| 2090 | const char *zTab, |
| 2091 | const char **azCol, u8 *abPK |
| 2092 | ){ |
| 2093 | int i; |
| 2094 | const char *zSep = ""; |
| 2095 | char *zRet = 0; |
| 2096 | int bHave = 0; |
| 2097 | |
| 2098 | for(i=0; i<nCol; i++){ |
| 2099 | if( abPK[i]==0 ){ |
| 2100 | bHave = 1; |
| 2101 | zRet = sqlite3_mprintf( |
| 2102 | "%z%s\"%w\".\"%w\".\"%w\" IS NOT \"%w\".\"%w\".\"%w\"", |
| 2103 | zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i] |
| 2104 | ); |
| 2105 | zSep = " OR "; |
| 2106 | if( zRet==0 ) break; |
| 2107 | } |
| 2108 | } |
| 2109 | |
| 2110 | if( bHave==0 ){ |
| 2111 | assert( zRet==0 ); |
| 2112 | zRet = sqlite3_mprintf("0"); |
| 2113 | } |
| 2114 | |
| 2115 | return zRet; |
| 2116 | } |
| 2117 | |
| 2118 | static char *sessionSelectFindNew( |
| 2119 | const char *zDb1, /* Pick rows in this db only */ |
| 2120 | const char *zDb2, /* But not in this one */ |
| 2121 | int bRowid, |
| 2122 | const char *zTbl, /* Table name */ |
| 2123 | const char *zExpr |
| 2124 | ){ |
| 2125 | const char *zSel = (bRowid ? SESSIONS_ROWID ", *" : "*"); |
| 2126 | char *zRet = sqlite3_mprintf( |
| 2127 | "SELECT %s FROM \"%w\".\"%w\" WHERE NOT EXISTS (" |
| 2128 | " SELECT 1 FROM \"%w\".\"%w\" WHERE %s" |
| 2129 | ")", |
| 2130 | zSel, zDb1, zTbl, zDb2, zTbl, zExpr |
| 2131 | ); |
| 2132 | return zRet; |
| 2133 | } |
| 2134 | |
| 2135 | static int sessionDiffFindNew( |
| 2136 | int op, |
| 2137 | sqlite3_session *pSession, |
| 2138 | SessionTable *pTab, |
| 2139 | const char *zDb1, |
| 2140 | const char *zDb2, |
| 2141 | char *zExpr |
| 2142 | ){ |
| 2143 | int rc = SQLITE_OK; |
| 2144 | char *zStmt = sessionSelectFindNew( |
| 2145 | zDb1, zDb2, pTab->bRowid, pTab->zName, zExpr |
| 2146 | ); |
| 2147 | |
| 2148 | if( zStmt==0 ){ |
| 2149 | rc = SQLITE_NOMEM; |
| 2150 | }else{ |
| 2151 | sqlite3_stmt *pStmt; |
| 2152 | rc = sqlite3_prepare_v2(pSession->db, zStmt, -1, &pStmt, 0); |
| 2153 | if( rc==SQLITE_OK ){ |
| 2154 | SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx; |
| 2155 | pDiffCtx->pStmt = pStmt; |
| 2156 | pDiffCtx->nOldOff = 0; |
| 2157 | pDiffCtx->bRowid = pTab->bRowid; |
| 2158 | while( SQLITE_ROW==sqlite3_step(pStmt) ){ |
| 2159 | i64 iRowid = (pTab->bRowid ? sqlite3_column_int64(pStmt, 0) : 0); |
| 2160 | sessionPreupdateOneChange(op, iRowid, pSession, pTab); |
| 2161 | } |
| 2162 | rc = sqlite3_finalize(pStmt); |
| 2163 | } |
| 2164 | sqlite3_free(zStmt); |
| 2165 | } |
| 2166 | |
| 2167 | return rc; |
| 2168 | } |
| 2169 | |
| 2170 | /* |
| 2171 | ** Return a comma-separated list of the fully-qualified (with both database |
| 2172 | ** and table name) column names from table pTab. e.g. |
| 2173 | ** |
| 2174 | ** "main"."t1"."a", "main"."t1"."b", "main"."t1"."c" |
| 2175 | */ |
| 2176 | static char *sessionAllCols( |
| 2177 | const char *zDb, |
| 2178 | SessionTable *pTab |
| 2179 | ){ |
| 2180 | int ii; |
| 2181 | char *zRet = 0; |
| 2182 | for(ii=0; ii<pTab->nCol; ii++){ |
| 2183 | zRet = sqlite3_mprintf("%z%s\"%w\".\"%w\".\"%w\"", |
| 2184 | zRet, (zRet ? ", " : ""), zDb, pTab->zName, pTab->azCol[ii] |
| 2185 | ); |
| 2186 | if( !zRet ) break; |
| 2187 | } |
| 2188 | return zRet; |
| 2189 | } |
| 2190 | |
| 2191 | static int sessionDiffFindModified( |
| 2192 | sqlite3_session *pSession, |
| 2193 | SessionTable *pTab, |
| 2194 | const char *zFrom, |
| 2195 | const char *zExpr |
| 2196 | ){ |
| 2197 | int rc = SQLITE_OK; |
| 2198 | |
| 2199 | char *zExpr2 = sessionExprCompareOther(pTab->nCol, |
| 2200 | pSession->zDb, zFrom, pTab->zName, pTab->azCol, pTab->abPK |
| 2201 | ); |
| 2202 | if( zExpr2==0 ){ |
| 2203 | rc = SQLITE_NOMEM; |
| 2204 | }else{ |
| 2205 | char *z1 = sessionAllCols(pSession->zDb, pTab); |
| 2206 | char *z2 = sessionAllCols(zFrom, pTab); |
| 2207 | char *zStmt = sqlite3_mprintf( |
| 2208 | "SELECT %s,%s FROM \"%w\".\"%w\", \"%w\".\"%w\" WHERE %s AND (%z)", |
| 2209 | z1, z2, pSession->zDb, pTab->zName, zFrom, pTab->zName, zExpr, zExpr2 |
| 2210 | ); |
| 2211 | if( zStmt==0 || z1==0 || z2==0 ){ |
| 2212 | rc = SQLITE_NOMEM; |
| 2213 | }else{ |
| 2214 | sqlite3_stmt *pStmt; |
| 2215 | rc = sqlite3_prepare_v2(pSession->db, zStmt, -1, &pStmt, 0); |
| 2216 | |
| 2217 | if( rc==SQLITE_OK ){ |
| 2218 | SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx; |
| 2219 | pDiffCtx->pStmt = pStmt; |
| 2220 | pDiffCtx->nOldOff = pTab->nCol; |
| 2221 | while( SQLITE_ROW==sqlite3_step(pStmt) ){ |
| 2222 | i64 iRowid = (pTab->bRowid ? sqlite3_column_int64(pStmt, 0) : 0); |
| 2223 | sessionPreupdateOneChange(SQLITE_UPDATE, iRowid, pSession, pTab); |
| 2224 | } |
| 2225 | rc = sqlite3_finalize(pStmt); |
| 2226 | } |
| 2227 | } |
| 2228 | sqlite3_free(zStmt); |
| 2229 | sqlite3_free(z1); |
| 2230 | sqlite3_free(z2); |
| 2231 | } |
| 2232 | |
| 2233 | return rc; |
| 2234 | } |
| 2235 | |
| 2236 | int sqlite3session_diff( |
| 2237 | sqlite3_session *pSession, |
| 2238 | const char *zFrom, |
| 2239 | const char *zTbl, |
| 2240 | char **pzErrMsg |
| 2241 | ){ |
| 2242 | const char *zDb = pSession->zDb; |
| 2243 | int rc = pSession->rc; |
| 2244 | SessionDiffCtx d; |
| 2245 | |
| 2246 | memset(&d, 0, sizeof(d)); |
| 2247 | sessionDiffHooks(pSession, &d); |
| 2248 | |
| 2249 | sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db)); |
| 2250 | if( pzErrMsg ) *pzErrMsg = 0; |
| 2251 | if( rc==SQLITE_OK ){ |
| 2252 | char *zExpr = 0; |
| 2253 | sqlite3 *db = pSession->db; |
| 2254 | SessionTable *pTo; /* Table zTbl */ |
| 2255 | |
| 2256 | /* Locate and if necessary initialize the target table object */ |
| 2257 | pSession->bAutoAttach++; |
| 2258 | rc = sessionFindTable(pSession, zTbl, &pTo); |
| 2259 | pSession->bAutoAttach--; |
| 2260 | if( pTo==0 ) goto diff_out; |
| 2261 | if( sessionInitTable(pSession, pTo, pSession->db, pSession->zDb) ){ |
| 2262 | rc = pSession->rc; |
| 2263 | goto diff_out; |
| 2264 | } |
| 2265 | |
| 2266 | /* Check the table schemas match */ |
| 2267 | if( rc==SQLITE_OK ){ |
| 2268 | int bHasPk = 0; |
| 2269 | int bMismatch = 0; |
| 2270 | int nCol = 0; /* Columns in zFrom.zTbl */ |
| 2271 | int bRowid = 0; |
| 2272 | u8 *abPK = 0; |
| 2273 | const char **azCol = 0; |
| 2274 | char *zDbExists = 0; |
| 2275 | |
| 2276 | /* Check that database zFrom is attached. */ |
| 2277 | zDbExists = sqlite3_mprintf("SELECT * FROM %Q.sqlite_schema", zFrom); |
| 2278 | if( zDbExists==0 ){ |
| 2279 | rc = SQLITE_NOMEM; |
| 2280 | }else{ |
| 2281 | sqlite3_stmt *pDbExists = 0; |
| 2282 | rc = sqlite3_prepare_v2(db, zDbExists, -1, &pDbExists, 0); |
| 2283 | if( rc==SQLITE_ERROR ){ |
| 2284 | rc = SQLITE_OK; |
| 2285 | nCol = -1; |
| 2286 | } |
| 2287 | sqlite3_finalize(pDbExists); |
| 2288 | sqlite3_free(zDbExists); |
| 2289 | } |
| 2290 | |
| 2291 | if( rc==SQLITE_OK && nCol==0 ){ |
| 2292 | rc = sessionTableInfo(0, db, zFrom, zTbl, |
| 2293 | &nCol, 0, 0, &azCol, 0, 0, &abPK, |
| 2294 | pSession->bImplicitPK ? &bRowid : 0 |
| 2295 | ); |
| 2296 | } |
| 2297 | if( rc==SQLITE_OK ){ |
| 2298 | if( pTo->nCol!=nCol ){ |
| 2299 | if( nCol<=0 ){ |
| 2300 | rc = SQLITE_SCHEMA; |
| 2301 | if( pzErrMsg ){ |
| 2302 | *pzErrMsg = sqlite3_mprintf("no such table: %s.%s", zFrom, zTbl); |
| 2303 | } |
| 2304 | }else{ |
| 2305 | bMismatch = 1; |
| 2306 | } |
| 2307 | }else{ |
| 2308 | int i; |
| 2309 | for(i=0; i<nCol; i++){ |
| 2310 | if( pTo->abPK[i]!=abPK[i] ) bMismatch = 1; |
| 2311 | if( sqlite3_stricmp(azCol[i], pTo->azCol[i]) ) bMismatch = 1; |
| 2312 | if( abPK[i] ) bHasPk = 1; |
| 2313 | } |
| 2314 | } |
| 2315 | } |
| 2316 | sqlite3_free((char*)azCol); |
| 2317 | if( bMismatch ){ |
| 2318 | if( pzErrMsg ){ |
| 2319 | *pzErrMsg = sqlite3_mprintf("table schemas do not match"); |
| 2320 | } |
| 2321 | rc = SQLITE_SCHEMA; |
| 2322 | } |
| 2323 | if( bHasPk==0 ){ |
| 2324 | /* Ignore tables with no primary keys */ |
| 2325 | goto diff_out; |
| 2326 | } |
| 2327 | } |
| 2328 | |
| 2329 | if( rc==SQLITE_OK ){ |
| 2330 | zExpr = sessionExprComparePK(pTo->nCol, |
| 2331 | zDb, zFrom, pTo->zName, pTo->azCol, pTo->abPK |
| 2332 | ); |
| 2333 | } |
| 2334 | |
| 2335 | /* Find new rows */ |
| 2336 | if( rc==SQLITE_OK ){ |
| 2337 | rc = sessionDiffFindNew(SQLITE_INSERT, pSession, pTo, zDb, zFrom, zExpr); |
| 2338 | } |
| 2339 | |
| 2340 | /* Find old rows */ |
| 2341 | if( rc==SQLITE_OK ){ |
| 2342 | rc = sessionDiffFindNew(SQLITE_DELETE, pSession, pTo, zFrom, zDb, zExpr); |
| 2343 | } |
| 2344 | |
| 2345 | /* Find modified rows */ |
| 2346 | if( rc==SQLITE_OK ){ |
| 2347 | rc = sessionDiffFindModified(pSession, pTo, zFrom, zExpr); |
| 2348 | } |
| 2349 | |
| 2350 | sqlite3_free(zExpr); |
| 2351 | } |
| 2352 | |
| 2353 | diff_out: |
| 2354 | sessionPreupdateHooks(pSession); |
| 2355 | sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db)); |
| 2356 | return rc; |
| 2357 | } |
| 2358 | |
| 2359 | /* |
| 2360 | ** Create a session object. This session object will record changes to |
| 2361 | ** database zDb attached to connection db. |
| 2362 | */ |
| 2363 | int sqlite3session_create( |
| 2364 | sqlite3 *db, /* Database handle */ |
| 2365 | const char *zDb, /* Name of db (e.g. "main") */ |
| 2366 | sqlite3_session **ppSession /* OUT: New session object */ |
| 2367 | ){ |
| 2368 | sqlite3_session *pNew; /* Newly allocated session object */ |
| 2369 | sqlite3_session *pOld; /* Session object already attached to db */ |
| 2370 | int nDb = sqlite3Strlen30(zDb); /* Length of zDb in bytes */ |
| 2371 | |
| 2372 | /* Zero the output value in case an error occurs. */ |
| 2373 | *ppSession = 0; |
| 2374 | |
| 2375 | /* Allocate and populate the new session object. */ |
| 2376 | pNew = (sqlite3_session *)sqlite3_malloc64(sizeof(sqlite3_session) + nDb + 1); |
| 2377 | if( !pNew ) return SQLITE_NOMEM; |
| 2378 | memset(pNew, 0, sizeof(sqlite3_session)); |
| 2379 | pNew->db = db; |
| 2380 | pNew->zDb = (char *)&pNew[1]; |
| 2381 | pNew->bEnable = 1; |
| 2382 | memcpy(pNew->zDb, zDb, nDb+1); |
| 2383 | sessionPreupdateHooks(pNew); |
| 2384 | |
| 2385 | /* Add the new session object to the linked list of session objects |
| 2386 | ** attached to database handle $db. Do this under the cover of the db |
| 2387 | ** handle mutex. */ |
| 2388 | sqlite3_mutex_enter(sqlite3_db_mutex(db)); |
| 2389 | pOld = (sqlite3_session*)sqlite3_preupdate_hook(db, xPreUpdate, (void*)pNew); |
| 2390 | pNew->pNext = pOld; |
| 2391 | sqlite3_mutex_leave(sqlite3_db_mutex(db)); |
| 2392 | |
| 2393 | *ppSession = pNew; |
| 2394 | return SQLITE_OK; |
| 2395 | } |
| 2396 | |
| 2397 | /* |
| 2398 | ** Free the list of table objects passed as the first argument. The contents |
| 2399 | ** of the changed-rows hash tables are also deleted. |
| 2400 | */ |
| 2401 | static void sessionDeleteTable(sqlite3_session *pSession, SessionTable *pList){ |
| 2402 | SessionTable *pNext; |
| 2403 | SessionTable *pTab; |
| 2404 | |
| 2405 | for(pTab=pList; pTab; pTab=pNext){ |
| 2406 | int i; |
| 2407 | pNext = pTab->pNext; |
| 2408 | for(i=0; i<pTab->nChange; i++){ |
| 2409 | SessionChange *p; |
| 2410 | SessionChange *pNextChange; |
| 2411 | for(p=pTab->apChange[i]; p; p=pNextChange){ |
| 2412 | pNextChange = p->pNext; |
| 2413 | sessionFree(pSession, p); |
| 2414 | } |
| 2415 | } |
| 2416 | sqlite3_finalize(pTab->pDfltStmt); |
| 2417 | sessionFree(pSession, (char*)pTab->azCol); /* cast works around VC++ bug */ |
| 2418 | sessionFree(pSession, pTab->apChange); |
| 2419 | sessionFree(pSession, pTab); |
| 2420 | } |
| 2421 | } |
| 2422 | |
| 2423 | /* |
| 2424 | ** Delete a session object previously allocated using sqlite3session_create(). |
| 2425 | */ |
| 2426 | void sqlite3session_delete(sqlite3_session *pSession){ |
| 2427 | sqlite3 *db = pSession->db; |
| 2428 | sqlite3_session *pHead; |
| 2429 | sqlite3_session **pp; |
| 2430 | |
| 2431 | /* Unlink the session from the linked list of sessions attached to the |
| 2432 | ** database handle. Hold the db mutex while doing so. */ |
| 2433 | sqlite3_mutex_enter(sqlite3_db_mutex(db)); |
| 2434 | pHead = (sqlite3_session*)sqlite3_preupdate_hook(db, 0, 0); |
| 2435 | for(pp=&pHead; ALWAYS((*pp)!=0); pp=&((*pp)->pNext)){ |
| 2436 | if( (*pp)==pSession ){ |
| 2437 | *pp = (*pp)->pNext; |
| 2438 | if( pHead ) sqlite3_preupdate_hook(db, xPreUpdate, (void*)pHead); |
| 2439 | break; |
| 2440 | } |
| 2441 | } |
| 2442 | sqlite3_mutex_leave(sqlite3_db_mutex(db)); |
| 2443 | sqlite3ValueFree(pSession->pZeroBlob); |
| 2444 | |
| 2445 | /* Delete all attached table objects. And the contents of their |
| 2446 | ** associated hash-tables. */ |
| 2447 | sessionDeleteTable(pSession, pSession->pTable); |
| 2448 | |
| 2449 | /* Free the session object. */ |
| 2450 | sqlite3_free(pSession); |
| 2451 | } |
| 2452 | |
| 2453 | /* |
| 2454 | ** Set a table filter on a Session Object. |
| 2455 | */ |
| 2456 | void sqlite3session_table_filter( |
| 2457 | sqlite3_session *pSession, |
| 2458 | int(*xFilter)(void*, const char*), |
| 2459 | void *pCtx /* First argument passed to xFilter */ |
| 2460 | ){ |
| 2461 | pSession->bAutoAttach = 1; |
| 2462 | pSession->pFilterCtx = pCtx; |
| 2463 | pSession->xTableFilter = xFilter; |
| 2464 | } |
| 2465 | |
| 2466 | /* |
| 2467 | ** Attach a table to a session. All subsequent changes made to the table |
| 2468 | ** while the session object is enabled will be recorded. |
| 2469 | ** |
| 2470 | ** Only tables that have a PRIMARY KEY defined may be attached. It does |
| 2471 | ** not matter if the PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias) |
| 2472 | ** or not. |
| 2473 | */ |
| 2474 | int sqlite3session_attach( |
| 2475 | sqlite3_session *pSession, /* Session object */ |
| 2476 | const char *zName /* Table name */ |
| 2477 | ){ |
| 2478 | int rc = SQLITE_OK; |
| 2479 | sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db)); |
| 2480 | |
| 2481 | if( !zName ){ |
| 2482 | pSession->bAutoAttach = 1; |
| 2483 | }else{ |
| 2484 | SessionTable *pTab; /* New table object (if required) */ |
| 2485 | int nName; /* Number of bytes in string zName */ |
| 2486 | |
| 2487 | /* First search for an existing entry. If one is found, this call is |
| 2488 | ** a no-op. Return early. */ |
| 2489 | nName = sqlite3Strlen30(zName); |
| 2490 | for(pTab=pSession->pTable; pTab; pTab=pTab->pNext){ |
| 2491 | if( 0==sqlite3_strnicmp(pTab->zName, zName, nName+1) ) break; |
| 2492 | } |
| 2493 | |
| 2494 | if( !pTab ){ |
| 2495 | /* Allocate new SessionTable object. */ |
| 2496 | int nByte = sizeof(SessionTable) + nName + 1; |
| 2497 | pTab = (SessionTable*)sessionMalloc64(pSession, nByte); |
| 2498 | if( !pTab ){ |
| 2499 | rc = SQLITE_NOMEM; |
| 2500 | }else{ |
| 2501 | /* Populate the new SessionTable object and link it into the list. |
| 2502 | ** The new object must be linked onto the end of the list, not |
| 2503 | ** simply added to the start of it in order to ensure that tables |
| 2504 | ** appear in the correct order when a changeset or patchset is |
| 2505 | ** eventually generated. */ |
| 2506 | SessionTable **ppTab; |
| 2507 | memset(pTab, 0, sizeof(SessionTable)); |
| 2508 | pTab->zName = (char *)&pTab[1]; |
| 2509 | memcpy(pTab->zName, zName, nName+1); |
| 2510 | for(ppTab=&pSession->pTable; *ppTab; ppTab=&(*ppTab)->pNext); |
| 2511 | *ppTab = pTab; |
| 2512 | } |
| 2513 | } |
| 2514 | } |
| 2515 | |
| 2516 | sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db)); |
| 2517 | return rc; |
| 2518 | } |
| 2519 | |
| 2520 | /* |
| 2521 | ** Append the value passed as the second argument to the buffer passed |
| 2522 | ** as the first. |
| 2523 | ** |
| 2524 | ** This function is a no-op if *pRc is non-zero when it is called. |
| 2525 | ** Otherwise, if an error occurs, *pRc is set to an SQLite error code |
| 2526 | ** before returning. |
| 2527 | */ |
| 2528 | static void sessionAppendValue(SessionBuffer *p, sqlite3_value *pVal, int *pRc){ |
| 2529 | int rc = *pRc; |
| 2530 | if( rc==SQLITE_OK ){ |
| 2531 | sqlite3_int64 nByte = 0; |
| 2532 | rc = sessionSerializeValue(0, pVal, &nByte); |
| 2533 | sessionBufferGrow(p, nByte, &rc); |
| 2534 | if( rc==SQLITE_OK ){ |
| 2535 | rc = sessionSerializeValue(&p->aBuf[p->nBuf], pVal, 0); |
| 2536 | p->nBuf += nByte; |
| 2537 | }else{ |
| 2538 | *pRc = rc; |
| 2539 | } |
| 2540 | } |
| 2541 | } |
| 2542 | |
| 2543 | /* |
| 2544 | ** This function is a no-op if *pRc is other than SQLITE_OK when it is |
| 2545 | ** called. Otherwise, append a single byte to the buffer. |
| 2546 | ** |
| 2547 | ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before |
| 2548 | ** returning. |
| 2549 | */ |
| 2550 | static void sessionAppendByte(SessionBuffer *p, u8 v, int *pRc){ |
| 2551 | if( 0==sessionBufferGrow(p, 1, pRc) ){ |
| 2552 | p->aBuf[p->nBuf++] = v; |
| 2553 | } |
| 2554 | } |
| 2555 | |
| 2556 | /* |
| 2557 | ** This function is a no-op if *pRc is other than SQLITE_OK when it is |
| 2558 | ** called. Otherwise, append a single varint to the buffer. |
| 2559 | ** |
| 2560 | ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before |
| 2561 | ** returning. |
| 2562 | */ |
| 2563 | static void sessionAppendVarint(SessionBuffer *p, int v, int *pRc){ |
| 2564 | if( 0==sessionBufferGrow(p, 9, pRc) ){ |
| 2565 | p->nBuf += sessionVarintPut(&p->aBuf[p->nBuf], v); |
| 2566 | } |
| 2567 | } |
| 2568 | |
| 2569 | /* |
| 2570 | ** This function is a no-op if *pRc is other than SQLITE_OK when it is |
| 2571 | ** called. Otherwise, append a blob of data to the buffer. |
| 2572 | ** |
| 2573 | ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before |
| 2574 | ** returning. |
| 2575 | */ |
| 2576 | static void sessionAppendBlob( |
| 2577 | SessionBuffer *p, |
| 2578 | const u8 *aBlob, |
| 2579 | int nBlob, |
| 2580 | int *pRc |
| 2581 | ){ |
| 2582 | if( nBlob>0 && 0==sessionBufferGrow(p, nBlob, pRc) ){ |
| 2583 | memcpy(&p->aBuf[p->nBuf], aBlob, nBlob); |
| 2584 | p->nBuf += nBlob; |
| 2585 | } |
| 2586 | } |
| 2587 | |
| 2588 | /* |
| 2589 | ** This function is a no-op if *pRc is other than SQLITE_OK when it is |
| 2590 | ** called. Otherwise, append the string representation of integer iVal |
| 2591 | ** to the buffer. No nul-terminator is written. |
| 2592 | ** |
| 2593 | ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before |
| 2594 | ** returning. |
| 2595 | */ |
| 2596 | static void sessionAppendInteger( |
| 2597 | SessionBuffer *p, /* Buffer to append to */ |
| 2598 | int iVal, /* Value to write the string rep. of */ |
| 2599 | int *pRc /* IN/OUT: Error code */ |
| 2600 | ){ |
| 2601 | char aBuf[24]; |
| 2602 | sqlite3_snprintf(sizeof(aBuf)-1, aBuf, "%d", iVal); |
| 2603 | sessionAppendStr(p, aBuf, pRc); |
| 2604 | } |
| 2605 | |
| 2606 | /* |
| 2607 | ** This function is a no-op if *pRc is other than SQLITE_OK when it is |
| 2608 | ** called. Otherwise, append the string zStr enclosed in quotes (") and |
| 2609 | ** with any embedded quote characters escaped to the buffer. No |
| 2610 | ** nul-terminator byte is written. |
| 2611 | ** |
| 2612 | ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before |
| 2613 | ** returning. |
| 2614 | */ |
| 2615 | static void sessionAppendIdent( |
| 2616 | SessionBuffer *p, /* Buffer to a append to */ |
| 2617 | const char *zStr, /* String to quote, escape and append */ |
| 2618 | int *pRc /* IN/OUT: Error code */ |
| 2619 | ){ |
| 2620 | int nStr = sqlite3Strlen30(zStr)*2 + 2 + 2; |
| 2621 | if( 0==sessionBufferGrow(p, nStr, pRc) ){ |
| 2622 | char *zOut = (char *)&p->aBuf[p->nBuf]; |
| 2623 | const char *zIn = zStr; |
| 2624 | *zOut++ = '"'; |
| 2625 | if( zIn!=0 ){ |
| 2626 | while( *zIn ){ |
| 2627 | if( *zIn=='"' ) *zOut++ = '"'; |
| 2628 | *zOut++ = *(zIn++); |
| 2629 | } |
| 2630 | } |
| 2631 | *zOut++ = '"'; |
| 2632 | p->nBuf = (int)((u8 *)zOut - p->aBuf); |
| 2633 | p->aBuf[p->nBuf] = 0x00; |
| 2634 | } |
| 2635 | } |
| 2636 | |
| 2637 | /* |
| 2638 | ** This function is a no-op if *pRc is other than SQLITE_OK when it is |
| 2639 | ** called. Otherwse, it appends the serialized version of the value stored |
| 2640 | ** in column iCol of the row that SQL statement pStmt currently points |
| 2641 | ** to to the buffer. |
| 2642 | */ |
| 2643 | static void sessionAppendCol( |
| 2644 | SessionBuffer *p, /* Buffer to append to */ |
| 2645 | sqlite3_stmt *pStmt, /* Handle pointing to row containing value */ |
| 2646 | int iCol, /* Column to read value from */ |
| 2647 | int *pRc /* IN/OUT: Error code */ |
| 2648 | ){ |
| 2649 | if( *pRc==SQLITE_OK ){ |
| 2650 | int eType = sqlite3_column_type(pStmt, iCol); |
| 2651 | sessionAppendByte(p, (u8)eType, pRc); |
| 2652 | if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){ |
| 2653 | u8 aBuf[8]; |
| 2654 | if( eType==SQLITE_INTEGER ){ |
| 2655 | sqlite3_int64 i = sqlite3_column_int64(pStmt, iCol); |
| 2656 | sessionPutI64(aBuf, i); |
| 2657 | }else{ |
| 2658 | double r = sqlite3_column_double(pStmt, iCol); |
| 2659 | sessionPutDouble(aBuf, r); |
| 2660 | } |
| 2661 | sessionAppendBlob(p, aBuf, 8, pRc); |
| 2662 | } |
| 2663 | if( eType==SQLITE_BLOB || eType==SQLITE_TEXT ){ |
| 2664 | u8 *z; |
| 2665 | int nByte; |
| 2666 | if( eType==SQLITE_BLOB ){ |
| 2667 | z = (u8 *)sqlite3_column_blob(pStmt, iCol); |
| 2668 | }else{ |
| 2669 | z = (u8 *)sqlite3_column_text(pStmt, iCol); |
| 2670 | } |
| 2671 | nByte = sqlite3_column_bytes(pStmt, iCol); |
| 2672 | if( z || (eType==SQLITE_BLOB && nByte==0) ){ |
| 2673 | sessionAppendVarint(p, nByte, pRc); |
| 2674 | sessionAppendBlob(p, z, nByte, pRc); |
| 2675 | }else{ |
| 2676 | *pRc = SQLITE_NOMEM; |
| 2677 | } |
| 2678 | } |
| 2679 | } |
| 2680 | } |
| 2681 | |
| 2682 | /* |
| 2683 | ** |
| 2684 | ** This function appends an update change to the buffer (see the comments |
| 2685 | ** under "CHANGESET FORMAT" at the top of the file). An update change |
| 2686 | ** consists of: |
| 2687 | ** |
| 2688 | ** 1 byte: SQLITE_UPDATE (0x17) |
| 2689 | ** n bytes: old.* record (see RECORD FORMAT) |
| 2690 | ** m bytes: new.* record (see RECORD FORMAT) |
| 2691 | ** |
| 2692 | ** The SessionChange object passed as the third argument contains the |
| 2693 | ** values that were stored in the row when the session began (the old.* |
| 2694 | ** values). The statement handle passed as the second argument points |
| 2695 | ** at the current version of the row (the new.* values). |
| 2696 | ** |
| 2697 | ** If all of the old.* values are equal to their corresponding new.* value |
| 2698 | ** (i.e. nothing has changed), then no data at all is appended to the buffer. |
| 2699 | ** |
| 2700 | ** Otherwise, the old.* record contains all primary key values and the |
| 2701 | ** original values of any fields that have been modified. The new.* record |
| 2702 | ** contains the new values of only those fields that have been modified. |
| 2703 | */ |
| 2704 | static int sessionAppendUpdate( |
| 2705 | SessionBuffer *pBuf, /* Buffer to append to */ |
| 2706 | int bPatchset, /* True for "patchset", 0 for "changeset" */ |
| 2707 | sqlite3_stmt *pStmt, /* Statement handle pointing at new row */ |
| 2708 | SessionChange *p, /* Object containing old values */ |
| 2709 | u8 *abPK /* Boolean array - true for PK columns */ |
| 2710 | ){ |
| 2711 | int rc = SQLITE_OK; |
| 2712 | SessionBuffer buf2 = {0,0,0}; /* Buffer to accumulate new.* record in */ |
| 2713 | int bNoop = 1; /* Set to zero if any values are modified */ |
| 2714 | int nRewind = pBuf->nBuf; /* Set to zero if any values are modified */ |
| 2715 | int i; /* Used to iterate through columns */ |
| 2716 | u8 *pCsr = p->aRecord; /* Used to iterate through old.* values */ |
| 2717 | |
| 2718 | assert( abPK!=0 ); |
| 2719 | sessionAppendByte(pBuf, SQLITE_UPDATE, &rc); |
| 2720 | sessionAppendByte(pBuf, p->bIndirect, &rc); |
| 2721 | for(i=0; i<sqlite3_column_count(pStmt); i++){ |
| 2722 | int bChanged = 0; |
| 2723 | int nAdvance; |
| 2724 | int eType = *pCsr; |
| 2725 | switch( eType ){ |
| 2726 | case SQLITE_NULL: |
| 2727 | nAdvance = 1; |
| 2728 | if( sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){ |
| 2729 | bChanged = 1; |
| 2730 | } |
| 2731 | break; |
| 2732 | |
| 2733 | case SQLITE_FLOAT: |
| 2734 | case SQLITE_INTEGER: { |
| 2735 | nAdvance = 9; |
| 2736 | if( eType==sqlite3_column_type(pStmt, i) ){ |
| 2737 | sqlite3_int64 iVal = sessionGetI64(&pCsr[1]); |
| 2738 | if( eType==SQLITE_INTEGER ){ |
| 2739 | if( iVal==sqlite3_column_int64(pStmt, i) ) break; |
| 2740 | }else{ |
| 2741 | double dVal; |
| 2742 | memcpy(&dVal, &iVal, 8); |
| 2743 | if( dVal==sqlite3_column_double(pStmt, i) ) break; |
| 2744 | } |
| 2745 | } |
| 2746 | bChanged = 1; |
| 2747 | break; |
| 2748 | } |
| 2749 | |
| 2750 | default: { |
| 2751 | int n; |
| 2752 | int nHdr = 1 + sessionVarintGet(&pCsr[1], &n); |
| 2753 | assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB ); |
| 2754 | nAdvance = nHdr + n; |
| 2755 | if( eType==sqlite3_column_type(pStmt, i) |
| 2756 | && n==sqlite3_column_bytes(pStmt, i) |
| 2757 | && (n==0 || 0==memcmp(&pCsr[nHdr], sqlite3_column_blob(pStmt, i), n)) |
| 2758 | ){ |
| 2759 | break; |
| 2760 | } |
| 2761 | bChanged = 1; |
| 2762 | } |
| 2763 | } |
| 2764 | |
| 2765 | /* If at least one field has been modified, this is not a no-op. */ |
| 2766 | if( bChanged ) bNoop = 0; |
| 2767 | |
| 2768 | /* Add a field to the old.* record. This is omitted if this module is |
| 2769 | ** currently generating a patchset. */ |
| 2770 | if( bPatchset==0 ){ |
| 2771 | if( bChanged || abPK[i] ){ |
| 2772 | sessionAppendBlob(pBuf, pCsr, nAdvance, &rc); |
| 2773 | }else{ |
| 2774 | sessionAppendByte(pBuf, 0, &rc); |
| 2775 | } |
| 2776 | } |
| 2777 | |
| 2778 | /* Add a field to the new.* record. Or the only record if currently |
| 2779 | ** generating a patchset. */ |
| 2780 | if( bChanged || (bPatchset && abPK[i]) ){ |
| 2781 | sessionAppendCol(&buf2, pStmt, i, &rc); |
| 2782 | }else{ |
| 2783 | sessionAppendByte(&buf2, 0, &rc); |
| 2784 | } |
| 2785 | |
| 2786 | pCsr += nAdvance; |
| 2787 | } |
| 2788 | |
| 2789 | if( bNoop ){ |
| 2790 | pBuf->nBuf = nRewind; |
| 2791 | }else{ |
| 2792 | sessionAppendBlob(pBuf, buf2.aBuf, buf2.nBuf, &rc); |
| 2793 | } |
| 2794 | sqlite3_free(buf2.aBuf); |
| 2795 | |
| 2796 | return rc; |
| 2797 | } |
| 2798 | |
| 2799 | /* |
| 2800 | ** Append a DELETE change to the buffer passed as the first argument. Use |
| 2801 | ** the changeset format if argument bPatchset is zero, or the patchset |
| 2802 | ** format otherwise. |
| 2803 | */ |
| 2804 | static int sessionAppendDelete( |
| 2805 | SessionBuffer *pBuf, /* Buffer to append to */ |
| 2806 | int bPatchset, /* True for "patchset", 0 for "changeset" */ |
| 2807 | SessionChange *p, /* Object containing old values */ |
| 2808 | int nCol, /* Number of columns in table */ |
| 2809 | u8 *abPK /* Boolean array - true for PK columns */ |
| 2810 | ){ |
| 2811 | int rc = SQLITE_OK; |
| 2812 | |
| 2813 | sessionAppendByte(pBuf, SQLITE_DELETE, &rc); |
| 2814 | sessionAppendByte(pBuf, p->bIndirect, &rc); |
| 2815 | |
| 2816 | if( bPatchset==0 ){ |
| 2817 | sessionAppendBlob(pBuf, p->aRecord, p->nRecord, &rc); |
| 2818 | }else{ |
| 2819 | int i; |
| 2820 | u8 *a = p->aRecord; |
| 2821 | for(i=0; i<nCol; i++){ |
| 2822 | u8 *pStart = a; |
| 2823 | int eType = *a++; |
| 2824 | |
| 2825 | switch( eType ){ |
| 2826 | case 0: |
| 2827 | case SQLITE_NULL: |
| 2828 | assert( abPK[i]==0 ); |
| 2829 | break; |
| 2830 | |
| 2831 | case SQLITE_FLOAT: |
| 2832 | case SQLITE_INTEGER: |
| 2833 | a += 8; |
| 2834 | break; |
| 2835 | |
| 2836 | default: { |
| 2837 | int n; |
| 2838 | a += sessionVarintGet(a, &n); |
| 2839 | a += n; |
| 2840 | break; |
| 2841 | } |
| 2842 | } |
| 2843 | if( abPK[i] ){ |
| 2844 | sessionAppendBlob(pBuf, pStart, (int)(a-pStart), &rc); |
| 2845 | } |
| 2846 | } |
| 2847 | assert( (a - p->aRecord)==p->nRecord ); |
| 2848 | } |
| 2849 | |
| 2850 | return rc; |
| 2851 | } |
| 2852 | |
| 2853 | static int sessionPrepare( |
| 2854 | sqlite3 *db, |
| 2855 | sqlite3_stmt **pp, |
| 2856 | char **pzErrmsg, |
| 2857 | const char *zSql |
| 2858 | ){ |
| 2859 | int rc = sqlite3_prepare_v2(db, zSql, -1, pp, 0); |
| 2860 | if( pzErrmsg && rc!=SQLITE_OK ){ |
| 2861 | *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db)); |
| 2862 | } |
| 2863 | return rc; |
| 2864 | } |
| 2865 | |
| 2866 | /* |
| 2867 | ** Prepare the statement specified by printf format zFmt and its trailing |
| 2868 | ** arguments. |
| 2869 | */ |
| 2870 | static void sessionPrepareMprintf( |
| 2871 | int *pRc, |
| 2872 | sqlite3 *db, |
| 2873 | sqlite3_stmt **pp, |
| 2874 | char **pzErrmsg, |
| 2875 | const char *zFmt, |
| 2876 | ... |
| 2877 | ){ |
| 2878 | if( *pRc==SQLITE_OK ){ |
| 2879 | char *zSql; |
| 2880 | va_list ap; |
| 2881 | va_start(ap, zFmt); |
| 2882 | zSql = sqlite3_vmprintf(zFmt, ap); |
| 2883 | if( zSql==0 ){ |
| 2884 | *pRc = SQLITE_NOMEM; |
| 2885 | }else{ |
| 2886 | *pRc = sessionPrepare(db, pp, pzErrmsg, zSql); |
| 2887 | sqlite3_free(zSql); |
| 2888 | } |
| 2889 | va_end(ap); |
| 2890 | } |
| 2891 | } |
| 2892 | |
| 2893 | /* |
| 2894 | ** Formulate and prepare a SELECT statement to retrieve a row from table |
| 2895 | ** zTab in database zDb based on its primary key. i.e. |
| 2896 | ** |
| 2897 | ** SELECT *, <noop-test> FROM zDb.zTab WHERE (pk1, pk2,...) IS (?1, ?2,...) |
| 2898 | ** |
| 2899 | ** where <noop-test> is: |
| 2900 | ** |
| 2901 | ** 1 AND (?A OR ?1 IS <column>) AND ... |
| 2902 | ** |
| 2903 | ** for each non-pk <column>. |
| 2904 | */ |
| 2905 | static int sessionSelectStmt( |
| 2906 | sqlite3 *db, /* Database handle */ |
| 2907 | int bIgnoreNoop, |
| 2908 | const char *zDb, /* Database name */ |
| 2909 | const char *zTab, /* Table name */ |
| 2910 | int bRowid, |
| 2911 | int nCol, /* Number of columns in table */ |
| 2912 | const char **azCol, /* Names of table columns */ |
| 2913 | u8 *abPK, /* PRIMARY KEY array */ |
| 2914 | sqlite3_stmt **ppStmt, /* OUT: Prepared SELECT statement */ |
| 2915 | char **pzErrmsg /* OUT: Error message */ |
| 2916 | ){ |
| 2917 | int rc = SQLITE_OK; |
| 2918 | char *zSql = 0; |
| 2919 | const char *zSep = ""; |
| 2920 | int i; |
| 2921 | |
| 2922 | SessionBuffer cols = {0, 0, 0}; |
| 2923 | SessionBuffer nooptest = {0, 0, 0}; |
| 2924 | SessionBuffer pkfield = {0, 0, 0}; |
| 2925 | SessionBuffer pkvar = {0, 0, 0}; |
| 2926 | |
| 2927 | sessionAppendStr(&nooptest, ", 1", &rc); |
| 2928 | |
| 2929 | if( 0==sqlite3_stricmp("sqlite_stat1", zTab) ){ |
| 2930 | sessionAppendStr(&nooptest, " AND (?6 OR ?3 IS stat)", &rc); |
| 2931 | sessionAppendStr(&pkfield, "tbl, idx", &rc); |
| 2932 | sessionAppendStr(&pkvar, |
| 2933 | "?1, (CASE WHEN ?2=X'' THEN NULL ELSE ?2 END)", &rc |
| 2934 | ); |
| 2935 | sessionAppendStr(&cols, "tbl, ?2, stat", &rc); |
| 2936 | }else{ |
| 2937 | #if 0 |
| 2938 | if( bRowid ){ |
| 2939 | sessionAppendStr(&cols, SESSIONS_ROWID, &rc); |
| 2940 | } |
| 2941 | #endif |
| 2942 | for(i=0; i<nCol; i++){ |
| 2943 | if( cols.nBuf ) sessionAppendStr(&cols, ", ", &rc); |
| 2944 | sessionAppendIdent(&cols, azCol[i], &rc); |
| 2945 | if( abPK[i] ){ |
| 2946 | sessionAppendStr(&pkfield, zSep, &rc); |
| 2947 | sessionAppendStr(&pkvar, zSep, &rc); |
| 2948 | zSep = ", "; |
| 2949 | sessionAppendIdent(&pkfield, azCol[i], &rc); |
| 2950 | sessionAppendPrintf(&pkvar, &rc, "?%d", i+1); |
| 2951 | }else{ |
| 2952 | sessionAppendPrintf(&nooptest, &rc, |
| 2953 | " AND (?%d OR ?%d IS %w.%w)", i+1+nCol, i+1, zTab, azCol[i] |
| 2954 | ); |
| 2955 | } |
| 2956 | } |
| 2957 | } |
| 2958 | |
| 2959 | if( rc==SQLITE_OK ){ |
| 2960 | zSql = sqlite3_mprintf( |
| 2961 | "SELECT %s%s FROM %Q.%Q WHERE (%s) IS (%s)", |
| 2962 | (char*)cols.aBuf, (bIgnoreNoop ? (char*)nooptest.aBuf : ""), |
| 2963 | zDb, zTab, (char*)pkfield.aBuf, (char*)pkvar.aBuf |
| 2964 | ); |
| 2965 | if( zSql==0 ) rc = SQLITE_NOMEM; |
| 2966 | } |
| 2967 | |
| 2968 | #if 0 |
| 2969 | if( 0==sqlite3_stricmp("sqlite_stat1", zTab) ){ |
| 2970 | zSql = sqlite3_mprintf( |
| 2971 | "SELECT tbl, ?2, stat FROM %Q.sqlite_stat1 WHERE tbl IS ?1 AND " |
| 2972 | "idx IS (CASE WHEN ?2=X'' THEN NULL ELSE ?2 END)", zDb |
| 2973 | ); |
| 2974 | if( zSql==0 ) rc = SQLITE_NOMEM; |
| 2975 | }else{ |
| 2976 | const char *zSep = ""; |
| 2977 | SessionBuffer buf = {0, 0, 0}; |
| 2978 | |
| 2979 | sessionAppendStr(&buf, "SELECT * FROM ", &rc); |
| 2980 | sessionAppendIdent(&buf, zDb, &rc); |
| 2981 | sessionAppendStr(&buf, ".", &rc); |
| 2982 | sessionAppendIdent(&buf, zTab, &rc); |
| 2983 | sessionAppendStr(&buf, " WHERE ", &rc); |
| 2984 | for(i=0; i<nCol; i++){ |
| 2985 | if( abPK[i] ){ |
| 2986 | sessionAppendStr(&buf, zSep, &rc); |
| 2987 | sessionAppendIdent(&buf, azCol[i], &rc); |
| 2988 | sessionAppendStr(&buf, " IS ?", &rc); |
| 2989 | sessionAppendInteger(&buf, i+1, &rc); |
| 2990 | zSep = " AND "; |
| 2991 | } |
| 2992 | } |
| 2993 | zSql = (char*)buf.aBuf; |
| 2994 | nSql = buf.nBuf; |
| 2995 | } |
| 2996 | #endif |
| 2997 | |
| 2998 | if( rc==SQLITE_OK ){ |
| 2999 | rc = sessionPrepare(db, ppStmt, pzErrmsg, zSql); |
| 3000 | } |
| 3001 | sqlite3_free(zSql); |
| 3002 | sqlite3_free(nooptest.aBuf); |
| 3003 | sqlite3_free(pkfield.aBuf); |
| 3004 | sqlite3_free(pkvar.aBuf); |
| 3005 | sqlite3_free(cols.aBuf); |
| 3006 | return rc; |
| 3007 | } |
| 3008 | |
| 3009 | /* |
| 3010 | ** Bind the PRIMARY KEY values from the change passed in argument pChange |
| 3011 | ** to the SELECT statement passed as the first argument. The SELECT statement |
| 3012 | ** is as prepared by function sessionSelectStmt(). |
| 3013 | ** |
| 3014 | ** Return SQLITE_OK if all PK values are successfully bound, or an SQLite |
| 3015 | ** error code (e.g. SQLITE_NOMEM) otherwise. |
| 3016 | */ |
| 3017 | static int sessionSelectBind( |
| 3018 | sqlite3_stmt *pSelect, /* SELECT from sessionSelectStmt() */ |
| 3019 | int nCol, /* Number of columns in table */ |
| 3020 | u8 *abPK, /* PRIMARY KEY array */ |
| 3021 | SessionChange *pChange /* Change structure */ |
| 3022 | ){ |
| 3023 | int i; |
| 3024 | int rc = SQLITE_OK; |
| 3025 | u8 *a = pChange->aRecord; |
| 3026 | |
| 3027 | for(i=0; i<nCol && rc==SQLITE_OK; i++){ |
| 3028 | int eType = *a++; |
| 3029 | |
| 3030 | switch( eType ){ |
| 3031 | case 0: |
| 3032 | case SQLITE_NULL: |
| 3033 | assert( abPK[i]==0 ); |
| 3034 | break; |
| 3035 | |
| 3036 | case SQLITE_INTEGER: { |
| 3037 | if( abPK[i] ){ |
| 3038 | i64 iVal = sessionGetI64(a); |
| 3039 | rc = sqlite3_bind_int64(pSelect, i+1, iVal); |
| 3040 | } |
| 3041 | a += 8; |
| 3042 | break; |
| 3043 | } |
| 3044 | |
| 3045 | case SQLITE_FLOAT: { |
| 3046 | if( abPK[i] ){ |
| 3047 | double rVal; |
| 3048 | i64 iVal = sessionGetI64(a); |
| 3049 | memcpy(&rVal, &iVal, 8); |
| 3050 | rc = sqlite3_bind_double(pSelect, i+1, rVal); |
| 3051 | } |
| 3052 | a += 8; |
| 3053 | break; |
| 3054 | } |
| 3055 | |
| 3056 | case SQLITE_TEXT: { |
| 3057 | int n; |
| 3058 | a += sessionVarintGet(a, &n); |
| 3059 | if( abPK[i] ){ |
| 3060 | rc = sqlite3_bind_text(pSelect, i+1, (char *)a, n, SQLITE_TRANSIENT); |
| 3061 | } |
| 3062 | a += n; |
| 3063 | break; |
| 3064 | } |
| 3065 | |
| 3066 | default: { |
| 3067 | int n; |
| 3068 | assert( eType==SQLITE_BLOB ); |
| 3069 | a += sessionVarintGet(a, &n); |
| 3070 | if( abPK[i] ){ |
| 3071 | rc = sqlite3_bind_blob(pSelect, i+1, a, n, SQLITE_TRANSIENT); |
| 3072 | } |
| 3073 | a += n; |
| 3074 | break; |
| 3075 | } |
| 3076 | } |
| 3077 | } |
| 3078 | |
| 3079 | return rc; |
| 3080 | } |
| 3081 | |
| 3082 | /* |
| 3083 | ** This function is a no-op if *pRc is set to other than SQLITE_OK when it |
| 3084 | ** is called. Otherwise, append a serialized table header (part of the binary |
| 3085 | ** changeset format) to buffer *pBuf. If an error occurs, set *pRc to an |
| 3086 | ** SQLite error code before returning. |
| 3087 | */ |
| 3088 | static void sessionAppendTableHdr( |
| 3089 | SessionBuffer *pBuf, /* Append header to this buffer */ |
| 3090 | int bPatchset, /* Use the patchset format if true */ |
| 3091 | SessionTable *pTab, /* Table object to append header for */ |
| 3092 | int *pRc /* IN/OUT: Error code */ |
| 3093 | ){ |
| 3094 | /* Write a table header */ |
| 3095 | sessionAppendByte(pBuf, (bPatchset ? 'P' : 'T'), pRc); |
| 3096 | sessionAppendVarint(pBuf, pTab->nCol, pRc); |
| 3097 | sessionAppendBlob(pBuf, pTab->abPK, pTab->nCol, pRc); |
| 3098 | sessionAppendBlob(pBuf, (u8 *)pTab->zName, (int)strlen(pTab->zName)+1, pRc); |
| 3099 | } |
| 3100 | |
| 3101 | /* |
| 3102 | ** Generate either a changeset (if argument bPatchset is zero) or a patchset |
| 3103 | ** (if it is non-zero) based on the current contents of the session object |
| 3104 | ** passed as the first argument. |
| 3105 | ** |
| 3106 | ** If no error occurs, SQLITE_OK is returned and the new changeset/patchset |
| 3107 | ** stored in output variables *pnChangeset and *ppChangeset. Or, if an error |
| 3108 | ** occurs, an SQLite error code is returned and both output variables set |
| 3109 | ** to 0. |
| 3110 | */ |
| 3111 | static int sessionGenerateChangeset( |
| 3112 | sqlite3_session *pSession, /* Session object */ |
| 3113 | int bPatchset, /* True for patchset, false for changeset */ |
| 3114 | int (*xOutput)(void *pOut, const void *pData, int nData), |
| 3115 | void *pOut, /* First argument for xOutput */ |
| 3116 | int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */ |
| 3117 | void **ppChangeset /* OUT: Buffer containing changeset */ |
| 3118 | ){ |
| 3119 | sqlite3 *db = pSession->db; /* Source database handle */ |
| 3120 | SessionTable *pTab; /* Used to iterate through attached tables */ |
| 3121 | SessionBuffer buf = {0,0,0}; /* Buffer in which to accumulate changeset */ |
| 3122 | int rc; /* Return code */ |
| 3123 | |
| 3124 | assert( xOutput==0 || (pnChangeset==0 && ppChangeset==0) ); |
| 3125 | assert( xOutput!=0 || (pnChangeset!=0 && ppChangeset!=0) ); |
| 3126 | |
| 3127 | /* Zero the output variables in case an error occurs. If this session |
| 3128 | ** object is already in the error state (sqlite3_session.rc != SQLITE_OK), |
| 3129 | ** this call will be a no-op. */ |
| 3130 | if( xOutput==0 ){ |
| 3131 | assert( pnChangeset!=0 && ppChangeset!=0 ); |
| 3132 | *pnChangeset = 0; |
| 3133 | *ppChangeset = 0; |
| 3134 | } |
| 3135 | |
| 3136 | if( pSession->rc ) return pSession->rc; |
| 3137 | |
| 3138 | sqlite3_mutex_enter(sqlite3_db_mutex(db)); |
| 3139 | rc = sqlite3_exec(pSession->db, "SAVEPOINT changeset", 0, 0, 0); |
| 3140 | if( rc!=SQLITE_OK ){ |
| 3141 | sqlite3_mutex_leave(sqlite3_db_mutex(db)); |
| 3142 | return rc; |
| 3143 | } |
| 3144 | |
| 3145 | for(pTab=pSession->pTable; rc==SQLITE_OK && pTab; pTab=pTab->pNext){ |
| 3146 | if( pTab->nEntry ){ |
| 3147 | const char *zName = pTab->zName; |
| 3148 | int i; /* Used to iterate through hash buckets */ |
| 3149 | sqlite3_stmt *pSel = 0; /* SELECT statement to query table pTab */ |
| 3150 | int nRewind = buf.nBuf; /* Initial size of write buffer */ |
| 3151 | int nNoop; /* Size of buffer after writing tbl header */ |
| 3152 | int nOldCol = pTab->nCol; |
| 3153 | |
| 3154 | /* Check the table schema is still Ok. */ |
| 3155 | rc = sessionReinitTable(pSession, pTab); |
| 3156 | if( rc==SQLITE_OK && pTab->nCol!=nOldCol ){ |
| 3157 | rc = sessionUpdateChanges(pSession, pTab); |
| 3158 | } |
| 3159 | |
| 3160 | /* Write a table header */ |
| 3161 | sessionAppendTableHdr(&buf, bPatchset, pTab, &rc); |
| 3162 | |
| 3163 | /* Build and compile a statement to execute: */ |
| 3164 | if( rc==SQLITE_OK ){ |
| 3165 | rc = sessionSelectStmt(db, 0, pSession->zDb, |
| 3166 | zName, pTab->bRowid, pTab->nCol, pTab->azCol, pTab->abPK, &pSel, 0 |
| 3167 | ); |
| 3168 | } |
| 3169 | |
| 3170 | nNoop = buf.nBuf; |
| 3171 | for(i=0; i<pTab->nChange && rc==SQLITE_OK; i++){ |
| 3172 | SessionChange *p; /* Used to iterate through changes */ |
| 3173 | |
| 3174 | for(p=pTab->apChange[i]; rc==SQLITE_OK && p; p=p->pNext){ |
| 3175 | rc = sessionSelectBind(pSel, pTab->nCol, pTab->abPK, p); |
| 3176 | if( rc!=SQLITE_OK ) continue; |
| 3177 | if( sqlite3_step(pSel)==SQLITE_ROW ){ |
| 3178 | if( p->op==SQLITE_INSERT ){ |
| 3179 | int iCol; |
| 3180 | sessionAppendByte(&buf, SQLITE_INSERT, &rc); |
| 3181 | sessionAppendByte(&buf, p->bIndirect, &rc); |
| 3182 | for(iCol=0; iCol<pTab->nCol; iCol++){ |
| 3183 | sessionAppendCol(&buf, pSel, iCol, &rc); |
| 3184 | } |
| 3185 | }else{ |
| 3186 | assert( pTab->abPK!=0 ); |
| 3187 | rc = sessionAppendUpdate(&buf, bPatchset, pSel, p, pTab->abPK); |
| 3188 | } |
| 3189 | }else if( p->op!=SQLITE_INSERT ){ |
| 3190 | rc = sessionAppendDelete(&buf, bPatchset, p, pTab->nCol,pTab->abPK); |
| 3191 | } |
| 3192 | if( rc==SQLITE_OK ){ |
| 3193 | rc = sqlite3_reset(pSel); |
| 3194 | } |
| 3195 | |
| 3196 | /* If the buffer is now larger than sessions_strm_chunk_size, pass |
| 3197 | ** its contents to the xOutput() callback. */ |
| 3198 | if( xOutput |
| 3199 | && rc==SQLITE_OK |
| 3200 | && buf.nBuf>nNoop |
| 3201 | && buf.nBuf>sessions_strm_chunk_size |
| 3202 | ){ |
| 3203 | rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf); |
| 3204 | nNoop = -1; |
| 3205 | buf.nBuf = 0; |
| 3206 | } |
| 3207 | |
| 3208 | } |
| 3209 | } |
| 3210 | |
| 3211 | sqlite3_finalize(pSel); |
| 3212 | if( buf.nBuf==nNoop ){ |
| 3213 | buf.nBuf = nRewind; |
| 3214 | } |
| 3215 | } |
| 3216 | } |
| 3217 | |
| 3218 | if( rc==SQLITE_OK ){ |
| 3219 | if( xOutput==0 ){ |
| 3220 | *pnChangeset = buf.nBuf; |
| 3221 | *ppChangeset = buf.aBuf; |
| 3222 | buf.aBuf = 0; |
| 3223 | }else if( buf.nBuf>0 ){ |
| 3224 | rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf); |
| 3225 | } |
| 3226 | } |
| 3227 | |
| 3228 | sqlite3_free(buf.aBuf); |
| 3229 | sqlite3_exec(db, "RELEASE changeset", 0, 0, 0); |
| 3230 | sqlite3_mutex_leave(sqlite3_db_mutex(db)); |
| 3231 | return rc; |
| 3232 | } |
| 3233 | |
| 3234 | /* |
| 3235 | ** Obtain a changeset object containing all changes recorded by the |
| 3236 | ** session object passed as the first argument. |
| 3237 | ** |
| 3238 | ** It is the responsibility of the caller to eventually free the buffer |
| 3239 | ** using sqlite3_free(). |
| 3240 | */ |
| 3241 | int sqlite3session_changeset( |
| 3242 | sqlite3_session *pSession, /* Session object */ |
| 3243 | int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */ |
| 3244 | void **ppChangeset /* OUT: Buffer containing changeset */ |
| 3245 | ){ |
| 3246 | int rc; |
| 3247 | |
| 3248 | if( pnChangeset==0 || ppChangeset==0 ) return SQLITE_MISUSE; |
| 3249 | rc = sessionGenerateChangeset(pSession, 0, 0, 0, pnChangeset, ppChangeset); |
| 3250 | assert( rc || pnChangeset==0 |
| 3251 | || pSession->bEnableSize==0 || *pnChangeset<=pSession->nMaxChangesetSize |
| 3252 | ); |
| 3253 | return rc; |
| 3254 | } |
| 3255 | |
| 3256 | /* |
| 3257 | ** Streaming version of sqlite3session_changeset(). |
| 3258 | */ |
| 3259 | int sqlite3session_changeset_strm( |
| 3260 | sqlite3_session *pSession, |
| 3261 | int (*xOutput)(void *pOut, const void *pData, int nData), |
| 3262 | void *pOut |
| 3263 | ){ |
| 3264 | if( xOutput==0 ) return SQLITE_MISUSE; |
| 3265 | return sessionGenerateChangeset(pSession, 0, xOutput, pOut, 0, 0); |
| 3266 | } |
| 3267 | |
| 3268 | /* |
| 3269 | ** Streaming version of sqlite3session_patchset(). |
| 3270 | */ |
| 3271 | int sqlite3session_patchset_strm( |
| 3272 | sqlite3_session *pSession, |
| 3273 | int (*xOutput)(void *pOut, const void *pData, int nData), |
| 3274 | void *pOut |
| 3275 | ){ |
| 3276 | if( xOutput==0 ) return SQLITE_MISUSE; |
| 3277 | return sessionGenerateChangeset(pSession, 1, xOutput, pOut, 0, 0); |
| 3278 | } |
| 3279 | |
| 3280 | /* |
| 3281 | ** Obtain a patchset object containing all changes recorded by the |
| 3282 | ** session object passed as the first argument. |
| 3283 | ** |
| 3284 | ** It is the responsibility of the caller to eventually free the buffer |
| 3285 | ** using sqlite3_free(). |
| 3286 | */ |
| 3287 | int sqlite3session_patchset( |
| 3288 | sqlite3_session *pSession, /* Session object */ |
| 3289 | int *pnPatchset, /* OUT: Size of buffer at *ppChangeset */ |
| 3290 | void **ppPatchset /* OUT: Buffer containing changeset */ |
| 3291 | ){ |
| 3292 | if( pnPatchset==0 || ppPatchset==0 ) return SQLITE_MISUSE; |
| 3293 | return sessionGenerateChangeset(pSession, 1, 0, 0, pnPatchset, ppPatchset); |
| 3294 | } |
| 3295 | |
| 3296 | /* |
| 3297 | ** Enable or disable the session object passed as the first argument. |
| 3298 | */ |
| 3299 | int sqlite3session_enable(sqlite3_session *pSession, int bEnable){ |
| 3300 | int ret; |
| 3301 | sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db)); |
| 3302 | if( bEnable>=0 ){ |
| 3303 | pSession->bEnable = bEnable; |
| 3304 | } |
| 3305 | ret = pSession->bEnable; |
| 3306 | sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db)); |
| 3307 | return ret; |
| 3308 | } |
| 3309 | |
| 3310 | /* |
| 3311 | ** Enable or disable the session object passed as the first argument. |
| 3312 | */ |
| 3313 | int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect){ |
| 3314 | int ret; |
| 3315 | sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db)); |
| 3316 | if( bIndirect>=0 ){ |
| 3317 | pSession->bIndirect = bIndirect; |
| 3318 | } |
| 3319 | ret = pSession->bIndirect; |
| 3320 | sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db)); |
| 3321 | return ret; |
| 3322 | } |
| 3323 | |
| 3324 | /* |
| 3325 | ** Return true if there have been no changes to monitored tables recorded |
| 3326 | ** by the session object passed as the only argument. |
| 3327 | */ |
| 3328 | int sqlite3session_isempty(sqlite3_session *pSession){ |
| 3329 | int ret = 0; |
| 3330 | SessionTable *pTab; |
| 3331 | |
| 3332 | sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db)); |
| 3333 | for(pTab=pSession->pTable; pTab && ret==0; pTab=pTab->pNext){ |
| 3334 | ret = (pTab->nEntry>0); |
| 3335 | } |
| 3336 | sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db)); |
| 3337 | |
| 3338 | return (ret==0); |
| 3339 | } |
| 3340 | |
| 3341 | /* |
| 3342 | ** Return the amount of heap memory in use. |
| 3343 | */ |
| 3344 | sqlite3_int64 sqlite3session_memory_used(sqlite3_session *pSession){ |
| 3345 | return pSession->nMalloc; |
| 3346 | } |
| 3347 | |
| 3348 | /* |
| 3349 | ** Configure the session object passed as the first argument. |
| 3350 | */ |
| 3351 | int sqlite3session_object_config(sqlite3_session *pSession, int op, void *pArg){ |
| 3352 | int rc = SQLITE_OK; |
| 3353 | switch( op ){ |
| 3354 | case SQLITE_SESSION_OBJCONFIG_SIZE: { |
| 3355 | int iArg = *(int*)pArg; |
| 3356 | if( iArg>=0 ){ |
| 3357 | if( pSession->pTable ){ |
| 3358 | rc = SQLITE_MISUSE; |
| 3359 | }else{ |
| 3360 | pSession->bEnableSize = (iArg!=0); |
| 3361 | } |
| 3362 | } |
| 3363 | *(int*)pArg = pSession->bEnableSize; |
| 3364 | break; |
| 3365 | } |
| 3366 | |
| 3367 | case SQLITE_SESSION_OBJCONFIG_ROWID: { |
| 3368 | int iArg = *(int*)pArg; |
| 3369 | if( iArg>=0 ){ |
| 3370 | if( pSession->pTable ){ |
| 3371 | rc = SQLITE_MISUSE; |
| 3372 | }else{ |
| 3373 | pSession->bImplicitPK = (iArg!=0); |
| 3374 | } |
| 3375 | } |
| 3376 | *(int*)pArg = pSession->bImplicitPK; |
| 3377 | break; |
| 3378 | } |
| 3379 | |
| 3380 | default: |
| 3381 | rc = SQLITE_MISUSE; |
| 3382 | } |
| 3383 | |
| 3384 | return rc; |
| 3385 | } |
| 3386 | |
| 3387 | /* |
| 3388 | ** Return the maximum size of sqlite3session_changeset() output. |
| 3389 | */ |
| 3390 | sqlite3_int64 sqlite3session_changeset_size(sqlite3_session *pSession){ |
| 3391 | return pSession->nMaxChangesetSize; |
| 3392 | } |
| 3393 | |
| 3394 | /* |
| 3395 | ** Do the work for either sqlite3changeset_start() or start_strm(). |
| 3396 | */ |
| 3397 | static int sessionChangesetStart( |
| 3398 | sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */ |
| 3399 | int (*xInput)(void *pIn, void *pData, int *pnData), |
| 3400 | void *pIn, |
| 3401 | int nChangeset, /* Size of buffer pChangeset in bytes */ |
| 3402 | void *pChangeset, /* Pointer to buffer containing changeset */ |
| 3403 | int bInvert, /* True to invert changeset */ |
| 3404 | int bSkipEmpty /* True to skip empty UPDATE changes */ |
| 3405 | ){ |
| 3406 | sqlite3_changeset_iter *pRet; /* Iterator to return */ |
| 3407 | int nByte; /* Number of bytes to allocate for iterator */ |
| 3408 | |
| 3409 | assert( xInput==0 || (pChangeset==0 && nChangeset==0) ); |
| 3410 | |
| 3411 | /* Zero the output variable in case an error occurs. */ |
| 3412 | *pp = 0; |
| 3413 | |
| 3414 | /* Allocate and initialize the iterator structure. */ |
| 3415 | nByte = sizeof(sqlite3_changeset_iter); |
| 3416 | pRet = (sqlite3_changeset_iter *)sqlite3_malloc(nByte); |
| 3417 | if( !pRet ) return SQLITE_NOMEM; |
| 3418 | memset(pRet, 0, sizeof(sqlite3_changeset_iter)); |
| 3419 | pRet->in.aData = (u8 *)pChangeset; |
| 3420 | pRet->in.nData = nChangeset; |
| 3421 | pRet->in.xInput = xInput; |
| 3422 | pRet->in.pIn = pIn; |
| 3423 | pRet->in.bEof = (xInput ? 0 : 1); |
| 3424 | pRet->bInvert = bInvert; |
| 3425 | pRet->bSkipEmpty = bSkipEmpty; |
| 3426 | |
| 3427 | /* Populate the output variable and return success. */ |
| 3428 | *pp = pRet; |
| 3429 | return SQLITE_OK; |
| 3430 | } |
| 3431 | |
| 3432 | /* |
| 3433 | ** Create an iterator used to iterate through the contents of a changeset. |
| 3434 | */ |
| 3435 | int sqlite3changeset_start( |
| 3436 | sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */ |
| 3437 | int nChangeset, /* Size of buffer pChangeset in bytes */ |
| 3438 | void *pChangeset /* Pointer to buffer containing changeset */ |
| 3439 | ){ |
| 3440 | return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset, 0, 0); |
| 3441 | } |
| 3442 | int sqlite3changeset_start_v2( |
| 3443 | sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */ |
| 3444 | int nChangeset, /* Size of buffer pChangeset in bytes */ |
| 3445 | void *pChangeset, /* Pointer to buffer containing changeset */ |
| 3446 | int flags |
| 3447 | ){ |
| 3448 | int bInvert = !!(flags & SQLITE_CHANGESETSTART_INVERT); |
| 3449 | return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset, bInvert, 0); |
| 3450 | } |
| 3451 | |
| 3452 | /* |
| 3453 | ** Streaming version of sqlite3changeset_start(). |
| 3454 | */ |
| 3455 | int sqlite3changeset_start_strm( |
| 3456 | sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */ |
| 3457 | int (*xInput)(void *pIn, void *pData, int *pnData), |
| 3458 | void *pIn |
| 3459 | ){ |
| 3460 | return sessionChangesetStart(pp, xInput, pIn, 0, 0, 0, 0); |
| 3461 | } |
| 3462 | int sqlite3changeset_start_v2_strm( |
| 3463 | sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */ |
| 3464 | int (*xInput)(void *pIn, void *pData, int *pnData), |
| 3465 | void *pIn, |
| 3466 | int flags |
| 3467 | ){ |
| 3468 | int bInvert = !!(flags & SQLITE_CHANGESETSTART_INVERT); |
| 3469 | return sessionChangesetStart(pp, xInput, pIn, 0, 0, bInvert, 0); |
| 3470 | } |
| 3471 | |
| 3472 | /* |
| 3473 | ** If the SessionInput object passed as the only argument is a streaming |
| 3474 | ** object and the buffer is full, discard some data to free up space. |
| 3475 | */ |
| 3476 | static void sessionDiscardData(SessionInput *pIn){ |
| 3477 | if( pIn->xInput && pIn->iCurrent>=sessions_strm_chunk_size ){ |
| 3478 | int nMove = pIn->buf.nBuf - pIn->iCurrent; |
| 3479 | assert( nMove>=0 ); |
| 3480 | if( nMove>0 ){ |
| 3481 | memmove(pIn->buf.aBuf, &pIn->buf.aBuf[pIn->iCurrent], nMove); |
| 3482 | } |
| 3483 | pIn->buf.nBuf -= pIn->iCurrent; |
| 3484 | pIn->iNext -= pIn->iCurrent; |
| 3485 | pIn->iCurrent = 0; |
| 3486 | pIn->nData = pIn->buf.nBuf; |
| 3487 | } |
| 3488 | } |
| 3489 | |
| 3490 | /* |
| 3491 | ** Ensure that there are at least nByte bytes available in the buffer. Or, |
| 3492 | ** if there are not nByte bytes remaining in the input, that all available |
| 3493 | ** data is in the buffer. |
| 3494 | ** |
| 3495 | ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise. |
| 3496 | */ |
| 3497 | static int sessionInputBuffer(SessionInput *pIn, int nByte){ |
| 3498 | int rc = SQLITE_OK; |
| 3499 | if( pIn->xInput ){ |
| 3500 | while( !pIn->bEof && (pIn->iNext+nByte)>=pIn->nData && rc==SQLITE_OK ){ |
| 3501 | int nNew = sessions_strm_chunk_size; |
| 3502 | |
| 3503 | if( pIn->bNoDiscard==0 ) sessionDiscardData(pIn); |
| 3504 | if( SQLITE_OK==sessionBufferGrow(&pIn->buf, nNew, &rc) ){ |
| 3505 | rc = pIn->xInput(pIn->pIn, &pIn->buf.aBuf[pIn->buf.nBuf], &nNew); |
| 3506 | if( nNew==0 ){ |
| 3507 | pIn->bEof = 1; |
| 3508 | }else{ |
| 3509 | pIn->buf.nBuf += nNew; |
| 3510 | } |
| 3511 | } |
| 3512 | |
| 3513 | pIn->aData = pIn->buf.aBuf; |
| 3514 | pIn->nData = pIn->buf.nBuf; |
| 3515 | } |
| 3516 | } |
| 3517 | return rc; |
| 3518 | } |
| 3519 | |
| 3520 | /* |
| 3521 | ** When this function is called, *ppRec points to the start of a record |
| 3522 | ** that contains nCol values. This function advances the pointer *ppRec |
| 3523 | ** until it points to the byte immediately following that record. |
| 3524 | */ |
| 3525 | static void sessionSkipRecord( |
| 3526 | u8 **ppRec, /* IN/OUT: Record pointer */ |
| 3527 | int nCol /* Number of values in record */ |
| 3528 | ){ |
| 3529 | u8 *aRec = *ppRec; |
| 3530 | int i; |
| 3531 | for(i=0; i<nCol; i++){ |
| 3532 | int eType = *aRec++; |
| 3533 | if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){ |
| 3534 | int nByte; |
| 3535 | aRec += sessionVarintGet((u8*)aRec, &nByte); |
| 3536 | aRec += nByte; |
| 3537 | }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){ |
| 3538 | aRec += 8; |
| 3539 | } |
| 3540 | } |
| 3541 | |
| 3542 | *ppRec = aRec; |
| 3543 | } |
| 3544 | |
| 3545 | /* |
| 3546 | ** This function sets the value of the sqlite3_value object passed as the |
| 3547 | ** first argument to a copy of the string or blob held in the aData[] |
| 3548 | ** buffer. SQLITE_OK is returned if successful, or SQLITE_NOMEM if an OOM |
| 3549 | ** error occurs. |
| 3550 | */ |
| 3551 | static int sessionValueSetStr( |
| 3552 | sqlite3_value *pVal, /* Set the value of this object */ |
| 3553 | u8 *aData, /* Buffer containing string or blob data */ |
| 3554 | int nData, /* Size of buffer aData[] in bytes */ |
| 3555 | u8 enc /* String encoding (0 for blobs) */ |
| 3556 | ){ |
| 3557 | /* In theory this code could just pass SQLITE_TRANSIENT as the final |
| 3558 | ** argument to sqlite3ValueSetStr() and have the copy created |
| 3559 | ** automatically. But doing so makes it difficult to detect any OOM |
| 3560 | ** error. Hence the code to create the copy externally. */ |
| 3561 | u8 *aCopy = sqlite3_malloc64((sqlite3_int64)nData+1); |
| 3562 | if( aCopy==0 ) return SQLITE_NOMEM; |
| 3563 | memcpy(aCopy, aData, nData); |
| 3564 | sqlite3ValueSetStr(pVal, nData, (char*)aCopy, enc, sqlite3_free); |
| 3565 | return SQLITE_OK; |
| 3566 | } |
| 3567 | |
| 3568 | /* |
| 3569 | ** Deserialize a single record from a buffer in memory. See "RECORD FORMAT" |
| 3570 | ** for details. |
| 3571 | ** |
| 3572 | ** When this function is called, *paChange points to the start of the record |
| 3573 | ** to deserialize. Assuming no error occurs, *paChange is set to point to |
| 3574 | ** one byte after the end of the same record before this function returns. |
| 3575 | ** If the argument abPK is NULL, then the record contains nCol values. Or, |
| 3576 | ** if abPK is other than NULL, then the record contains only the PK fields |
| 3577 | ** (in other words, it is a patchset DELETE record). |
| 3578 | ** |
| 3579 | ** If successful, each element of the apOut[] array (allocated by the caller) |
| 3580 | ** is set to point to an sqlite3_value object containing the value read |
| 3581 | ** from the corresponding position in the record. If that value is not |
| 3582 | ** included in the record (i.e. because the record is part of an UPDATE change |
| 3583 | ** and the field was not modified), the corresponding element of apOut[] is |
| 3584 | ** set to NULL. |
| 3585 | ** |
| 3586 | ** It is the responsibility of the caller to free all sqlite_value structures |
| 3587 | ** using sqlite3_free(). |
| 3588 | ** |
| 3589 | ** If an error occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned. |
| 3590 | ** The apOut[] array may have been partially populated in this case. |
| 3591 | */ |
| 3592 | static int sessionReadRecord( |
| 3593 | SessionInput *pIn, /* Input data */ |
| 3594 | int nCol, /* Number of values in record */ |
| 3595 | u8 *abPK, /* Array of primary key flags, or NULL */ |
| 3596 | sqlite3_value **apOut, /* Write values to this array */ |
| 3597 | int *pbEmpty |
| 3598 | ){ |
| 3599 | int i; /* Used to iterate through columns */ |
| 3600 | int rc = SQLITE_OK; |
| 3601 | |
| 3602 | assert( pbEmpty==0 || *pbEmpty==0 ); |
| 3603 | if( pbEmpty ) *pbEmpty = 1; |
| 3604 | for(i=0; i<nCol && rc==SQLITE_OK; i++){ |
| 3605 | int eType = 0; /* Type of value (SQLITE_NULL, TEXT etc.) */ |
| 3606 | if( abPK && abPK[i]==0 ) continue; |
| 3607 | rc = sessionInputBuffer(pIn, 9); |
| 3608 | if( rc==SQLITE_OK ){ |
| 3609 | if( pIn->iNext>=pIn->nData ){ |
| 3610 | rc = SQLITE_CORRUPT_BKPT; |
| 3611 | }else{ |
| 3612 | eType = pIn->aData[pIn->iNext++]; |
| 3613 | assert( apOut[i]==0 ); |
| 3614 | if( eType ){ |
| 3615 | if( pbEmpty ) *pbEmpty = 0; |
| 3616 | apOut[i] = sqlite3ValueNew(0); |
| 3617 | if( !apOut[i] ) rc = SQLITE_NOMEM; |
| 3618 | } |
| 3619 | } |
| 3620 | } |
| 3621 | |
| 3622 | if( rc==SQLITE_OK ){ |
| 3623 | u8 *aVal = &pIn->aData[pIn->iNext]; |
| 3624 | if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){ |
| 3625 | int nByte; |
| 3626 | int nRem = pIn->nData - pIn->iNext; |
| 3627 | pIn->iNext += sessionVarintGetSafe(aVal, nRem, &nByte); |
| 3628 | rc = sessionInputBuffer(pIn, nByte); |
| 3629 | if( rc==SQLITE_OK ){ |
| 3630 | if( nByte<0 || nByte>pIn->nData-pIn->iNext ){ |
| 3631 | rc = SQLITE_CORRUPT_BKPT; |
| 3632 | }else{ |
| 3633 | u8 enc = (eType==SQLITE_TEXT ? SQLITE_UTF8 : 0); |
| 3634 | rc = sessionValueSetStr(apOut[i],&pIn->aData[pIn->iNext],nByte,enc); |
| 3635 | pIn->iNext += nByte; |
| 3636 | } |
| 3637 | } |
| 3638 | } |
| 3639 | if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){ |
| 3640 | if( (pIn->nData-pIn->iNext)<8 ){ |
| 3641 | rc = SQLITE_CORRUPT_BKPT; |
| 3642 | }else{ |
| 3643 | sqlite3_int64 v = sessionGetI64(aVal); |
| 3644 | if( eType==SQLITE_INTEGER ){ |
| 3645 | sqlite3VdbeMemSetInt64(apOut[i], v); |
| 3646 | }else{ |
| 3647 | double d; |
| 3648 | memcpy(&d, &v, 8); |
| 3649 | sqlite3VdbeMemSetDouble(apOut[i], d); |
| 3650 | } |
| 3651 | pIn->iNext += 8; |
| 3652 | } |
| 3653 | } |
| 3654 | } |
| 3655 | } |
| 3656 | |
| 3657 | return rc; |
| 3658 | } |
| 3659 | |
| 3660 | /* |
| 3661 | ** The input pointer currently points to the second byte of a table-header. |
| 3662 | ** Specifically, to the following: |
| 3663 | ** |
| 3664 | ** + number of columns in table (varint) |
| 3665 | ** + array of PK flags (1 byte per column), |
| 3666 | ** + table name (nul terminated). |
| 3667 | ** |
| 3668 | ** This function ensures that all of the above is present in the input |
| 3669 | ** buffer (i.e. that it can be accessed without any calls to xInput()). |
| 3670 | ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code. |
| 3671 | ** The input pointer is not moved. |
| 3672 | */ |
| 3673 | static int sessionChangesetBufferTblhdr(SessionInput *pIn, int *pnByte){ |
| 3674 | int rc = SQLITE_OK; |
| 3675 | int nCol = 0; |
| 3676 | int nRead = 0; |
| 3677 | |
| 3678 | rc = sessionInputBuffer(pIn, 9); |
| 3679 | if( rc==SQLITE_OK ){ |
| 3680 | int nBuf = pIn->nData - pIn->iNext; |
| 3681 | nRead += sessionVarintGetSafe(&pIn->aData[pIn->iNext], nBuf, &nCol); |
| 3682 | /* The hard upper limit for the number of columns in an SQLite |
| 3683 | ** database table is, according to sqliteLimit.h, 32676. So |
| 3684 | ** consider any table-header that purports to have more than 65536 |
| 3685 | ** columns to be corrupt. This is convenient because otherwise, |
| 3686 | ** if the (nCol>65536) condition below were omitted, a sufficiently |
| 3687 | ** large value for nCol may cause nRead to wrap around and become |
| 3688 | ** negative. Leading to a crash. */ |
| 3689 | if( nCol<0 || nCol>65536 ){ |
| 3690 | rc = SQLITE_CORRUPT_BKPT; |
| 3691 | }else{ |
| 3692 | rc = sessionInputBuffer(pIn, nRead+nCol+100); |
| 3693 | nRead += nCol; |
| 3694 | } |
| 3695 | } |
| 3696 | |
| 3697 | while( rc==SQLITE_OK ){ |
| 3698 | while( (pIn->iNext + nRead)<pIn->nData && pIn->aData[pIn->iNext + nRead] ){ |
| 3699 | nRead++; |
| 3700 | } |
| 3701 | |
| 3702 | /* Break out of the loop if if the nul-terminator byte has been found. |
| 3703 | ** Otherwise, read some more input data and keep seeking. If there is |
| 3704 | ** no more input data, consider the changeset corrupt. */ |
| 3705 | if( (pIn->iNext + nRead)<pIn->nData ) break; |
| 3706 | rc = sessionInputBuffer(pIn, nRead + 100); |
| 3707 | if( rc==SQLITE_OK && (pIn->iNext + nRead)>=pIn->nData ){ |
| 3708 | rc = SQLITE_CORRUPT_BKPT; |
| 3709 | } |
| 3710 | } |
| 3711 | *pnByte = nRead+1; |
| 3712 | return rc; |
| 3713 | } |
| 3714 | |
| 3715 | /* |
| 3716 | ** The input pointer currently points to the first byte of the first field |
| 3717 | ** of a record consisting of nCol columns. This function ensures the entire |
| 3718 | ** record is buffered. It does not move the input pointer. |
| 3719 | ** |
| 3720 | ** If successful, SQLITE_OK is returned and *pnByte is set to the size of |
| 3721 | ** the record in bytes. Otherwise, an SQLite error code is returned. The |
| 3722 | ** final value of *pnByte is undefined in this case. |
| 3723 | */ |
| 3724 | static int sessionChangesetBufferRecord( |
| 3725 | SessionInput *pIn, /* Input data */ |
| 3726 | int nCol, /* Number of columns in record */ |
| 3727 | int *pnByte /* OUT: Size of record in bytes */ |
| 3728 | ){ |
| 3729 | int rc = SQLITE_OK; |
| 3730 | i64 nByte = 0; |
| 3731 | int i; |
| 3732 | for(i=0; rc==SQLITE_OK && i<nCol; i++){ |
| 3733 | int eType; |
| 3734 | rc = sessionInputBuffer(pIn, nByte + 10); |
| 3735 | if( rc==SQLITE_OK ){ |
| 3736 | if( pIn->iNext+nByte>=pIn->nData ){ |
| 3737 | rc = SQLITE_CORRUPT_BKPT; |
| 3738 | }else{ |
| 3739 | eType = pIn->aData[pIn->iNext + nByte++]; |
| 3740 | if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){ |
| 3741 | int n; |
| 3742 | int nRem = pIn->nData - (pIn->iNext + nByte); |
| 3743 | nByte += sessionVarintGetSafe(&pIn->aData[pIn->iNext+nByte], nRem,&n); |
| 3744 | nByte += n; |
| 3745 | rc = sessionInputBuffer(pIn, nByte); |
| 3746 | }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){ |
| 3747 | nByte += 8; |
| 3748 | }else if( eType!=0 && eType!=SQLITE_NULL ){ |
| 3749 | rc = SQLITE_CORRUPT_BKPT; |
| 3750 | } |
| 3751 | } |
| 3752 | } |
| 3753 | if( rc==SQLITE_OK && (pIn->iNext+nByte)>pIn->nData ){ |
| 3754 | rc = SQLITE_CORRUPT_BKPT; |
| 3755 | } |
| 3756 | } |
| 3757 | *pnByte = nByte; |
| 3758 | return rc; |
| 3759 | } |
| 3760 | |
| 3761 | /* |
| 3762 | ** The input pointer currently points to the second byte of a table-header. |
| 3763 | ** Specifically, to the following: |
| 3764 | ** |
| 3765 | ** + number of columns in table (varint) |
| 3766 | ** + array of PK flags (1 byte per column), |
| 3767 | ** + table name (nul terminated). |
| 3768 | ** |
| 3769 | ** This function decodes the table-header and populates the p->nCol, |
| 3770 | ** p->zTab and p->abPK[] variables accordingly. The p->apValue[] array is |
| 3771 | ** also allocated or resized according to the new value of p->nCol. The |
| 3772 | ** input pointer is left pointing to the byte following the table header. |
| 3773 | ** |
| 3774 | ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code |
| 3775 | ** is returned and the final values of the various fields enumerated above |
| 3776 | ** are undefined. |
| 3777 | */ |
| 3778 | static int sessionChangesetReadTblhdr(sqlite3_changeset_iter *p){ |
| 3779 | int rc; |
| 3780 | int nCopy; |
| 3781 | assert( p->rc==SQLITE_OK ); |
| 3782 | |
| 3783 | rc = sessionChangesetBufferTblhdr(&p->in, &nCopy); |
| 3784 | if( rc==SQLITE_OK ){ |
| 3785 | int nByte; |
| 3786 | int nVarint; |
| 3787 | nVarint = sessionVarintGet(&p->in.aData[p->in.iNext], &p->nCol); |
| 3788 | if( p->nCol>0 ){ |
| 3789 | nCopy -= nVarint; |
| 3790 | p->in.iNext += nVarint; |
| 3791 | nByte = p->nCol * sizeof(sqlite3_value*) * 2 + nCopy; |
| 3792 | p->tblhdr.nBuf = 0; |
| 3793 | sessionBufferGrow(&p->tblhdr, nByte, &rc); |
| 3794 | }else{ |
| 3795 | rc = SQLITE_CORRUPT_BKPT; |
| 3796 | } |
| 3797 | } |
| 3798 | |
| 3799 | if( rc==SQLITE_OK ){ |
| 3800 | size_t iPK = sizeof(sqlite3_value*)*p->nCol*2; |
| 3801 | memset(p->tblhdr.aBuf, 0, iPK); |
| 3802 | memcpy(&p->tblhdr.aBuf[iPK], &p->in.aData[p->in.iNext], nCopy); |
| 3803 | p->in.iNext += nCopy; |
| 3804 | } |
| 3805 | |
| 3806 | p->apValue = (sqlite3_value**)p->tblhdr.aBuf; |
| 3807 | if( p->apValue==0 ){ |
| 3808 | p->abPK = 0; |
| 3809 | p->zTab = 0; |
| 3810 | }else{ |
| 3811 | p->abPK = (u8*)&p->apValue[p->nCol*2]; |
| 3812 | p->zTab = p->abPK ? (char*)&p->abPK[p->nCol] : 0; |
| 3813 | } |
| 3814 | return (p->rc = rc); |
| 3815 | } |
| 3816 | |
| 3817 | /* |
| 3818 | ** Advance the changeset iterator to the next change. The differences between |
| 3819 | ** this function and sessionChangesetNext() are that |
| 3820 | ** |
| 3821 | ** * If pbEmpty is not NULL and the change is a no-op UPDATE (an UPDATE |
| 3822 | ** that modifies no columns), this function sets (*pbEmpty) to 1. |
| 3823 | ** |
| 3824 | ** * If the iterator is configured to skip no-op UPDATEs, |
| 3825 | ** sessionChangesetNext() does that. This function does not. |
| 3826 | */ |
| 3827 | static int sessionChangesetNextOne( |
| 3828 | sqlite3_changeset_iter *p, /* Changeset iterator */ |
| 3829 | u8 **paRec, /* If non-NULL, store record pointer here */ |
| 3830 | int *pnRec, /* If non-NULL, store size of record here */ |
| 3831 | int *pbNew, /* If non-NULL, true if new table */ |
| 3832 | int *pbEmpty |
| 3833 | ){ |
| 3834 | int i; |
| 3835 | u8 op; |
| 3836 | |
| 3837 | assert( (paRec==0 && pnRec==0) || (paRec && pnRec) ); |
| 3838 | assert( pbEmpty==0 || *pbEmpty==0 ); |
| 3839 | |
| 3840 | /* If the iterator is in the error-state, return immediately. */ |
| 3841 | if( p->rc!=SQLITE_OK ) return p->rc; |
| 3842 | |
| 3843 | /* Free the current contents of p->apValue[], if any. */ |
| 3844 | if( p->apValue ){ |
| 3845 | for(i=0; i<p->nCol*2; i++){ |
| 3846 | sqlite3ValueFree(p->apValue[i]); |
| 3847 | } |
| 3848 | memset(p->apValue, 0, sizeof(sqlite3_value*)*p->nCol*2); |
| 3849 | } |
| 3850 | |
| 3851 | /* Make sure the buffer contains at least 2 bytes of input data, or all |
| 3852 | ** remaining data if there are less than 2 bytes available. This is |
| 3853 | ** sufficient either for the 'T' or 'P' byte that begins a new table, |
| 3854 | ** or for the "op" and "bIndirect" single bytes otherwise. */ |
| 3855 | p->rc = sessionInputBuffer(&p->in, 2); |
| 3856 | if( p->rc!=SQLITE_OK ) return p->rc; |
| 3857 | |
| 3858 | p->in.iCurrent = p->in.iNext; |
| 3859 | sessionDiscardData(&p->in); |
| 3860 | |
| 3861 | /* If the iterator is already at the end of the changeset, return DONE. */ |
| 3862 | if( p->in.iNext>=p->in.nData ){ |
| 3863 | return SQLITE_DONE; |
| 3864 | } |
| 3865 | |
| 3866 | op = p->in.aData[p->in.iNext++]; |
| 3867 | while( op=='T' || op=='P' ){ |
| 3868 | if( pbNew ) *pbNew = 1; |
| 3869 | p->bPatchset = (op=='P'); |
| 3870 | if( sessionChangesetReadTblhdr(p) ) return p->rc; |
| 3871 | if( (p->rc = sessionInputBuffer(&p->in, 2)) ) return p->rc; |
| 3872 | p->in.iCurrent = p->in.iNext; |
| 3873 | if( p->in.iNext>=p->in.nData ) return SQLITE_DONE; |
| 3874 | op = p->in.aData[p->in.iNext++]; |
| 3875 | } |
| 3876 | |
| 3877 | if( p->zTab==0 || (p->bPatchset && p->bInvert) ){ |
| 3878 | /* The first record in the changeset is not a table header. Must be a |
| 3879 | ** corrupt changeset. */ |
| 3880 | assert( p->in.iNext==1 || p->zTab ); |
| 3881 | return (p->rc = SQLITE_CORRUPT_BKPT); |
| 3882 | } |
| 3883 | |
| 3884 | if( (op!=SQLITE_UPDATE && op!=SQLITE_DELETE && op!=SQLITE_INSERT) |
| 3885 | || (p->in.iNext>=p->in.nData) |
| 3886 | ){ |
| 3887 | return (p->rc = SQLITE_CORRUPT_BKPT); |
| 3888 | } |
| 3889 | p->op = op; |
| 3890 | p->bIndirect = p->in.aData[p->in.iNext++]; |
| 3891 | |
| 3892 | if( paRec ){ |
| 3893 | int nVal; /* Number of values to buffer */ |
| 3894 | if( p->bPatchset==0 && op==SQLITE_UPDATE ){ |
| 3895 | nVal = p->nCol * 2; |
| 3896 | }else if( p->bPatchset && op==SQLITE_DELETE ){ |
| 3897 | nVal = 0; |
| 3898 | for(i=0; i<p->nCol; i++) if( p->abPK[i] ) nVal++; |
| 3899 | }else{ |
| 3900 | nVal = p->nCol; |
| 3901 | } |
| 3902 | p->rc = sessionChangesetBufferRecord(&p->in, nVal, pnRec); |
| 3903 | if( p->rc!=SQLITE_OK ) return p->rc; |
| 3904 | *paRec = &p->in.aData[p->in.iNext]; |
| 3905 | p->in.iNext += *pnRec; |
| 3906 | }else{ |
| 3907 | sqlite3_value **apOld = (p->bInvert ? &p->apValue[p->nCol] : p->apValue); |
| 3908 | sqlite3_value **apNew = (p->bInvert ? p->apValue : &p->apValue[p->nCol]); |
| 3909 | |
| 3910 | /* If this is an UPDATE or DELETE, read the old.* record. */ |
| 3911 | if( p->op!=SQLITE_INSERT && (p->bPatchset==0 || p->op==SQLITE_DELETE) ){ |
| 3912 | u8 *abPK = p->bPatchset ? p->abPK : 0; |
| 3913 | p->rc = sessionReadRecord(&p->in, p->nCol, abPK, apOld, 0); |
| 3914 | if( p->rc!=SQLITE_OK ) return p->rc; |
| 3915 | } |
| 3916 | |
| 3917 | /* If this is an INSERT or UPDATE, read the new.* record. */ |
| 3918 | if( p->op!=SQLITE_DELETE ){ |
| 3919 | p->rc = sessionReadRecord(&p->in, p->nCol, 0, apNew, pbEmpty); |
| 3920 | if( p->rc!=SQLITE_OK ) return p->rc; |
| 3921 | } |
| 3922 | |
| 3923 | if( (p->bPatchset || p->bInvert) && p->op==SQLITE_UPDATE ){ |
| 3924 | /* If this is an UPDATE that is part of a patchset, then all PK and |
| 3925 | ** modified fields are present in the new.* record. The old.* record |
| 3926 | ** is currently completely empty. This block shifts the PK fields from |
| 3927 | ** new.* to old.*, to accommodate the code that reads these arrays. */ |
| 3928 | for(i=0; i<p->nCol; i++){ |
| 3929 | assert( p->bPatchset==0 || p->apValue[i]==0 ); |
| 3930 | if( p->abPK[i] ){ |
| 3931 | assert( p->apValue[i]==0 ); |
| 3932 | p->apValue[i] = p->apValue[i+p->nCol]; |
| 3933 | if( p->apValue[i]==0 ) return (p->rc = SQLITE_CORRUPT_BKPT); |
| 3934 | p->apValue[i+p->nCol] = 0; |
| 3935 | } |
| 3936 | } |
| 3937 | }else if( p->bInvert ){ |
| 3938 | if( p->op==SQLITE_INSERT ) p->op = SQLITE_DELETE; |
| 3939 | else if( p->op==SQLITE_DELETE ) p->op = SQLITE_INSERT; |
| 3940 | } |
| 3941 | |
| 3942 | /* If this is an UPDATE that is part of a changeset, then check that |
| 3943 | ** there are no fields in the old.* record that are not (a) PK fields, |
| 3944 | ** or (b) also present in the new.* record. |
| 3945 | ** |
| 3946 | ** Such records are technically corrupt, but the rebaser was at one |
| 3947 | ** point generating them. Under most circumstances this is benign, but |
| 3948 | ** can cause spurious SQLITE_RANGE errors when applying the changeset. |
| 3949 | ** |
| 3950 | ** Also check that all PK fields are present in the old.* record. If |
| 3951 | ** they are not, the changeset is corrupt. */ |
| 3952 | if( p->bPatchset==0 && p->op==SQLITE_UPDATE){ |
| 3953 | for(i=0; i<p->nCol; i++){ |
| 3954 | if( p->abPK[i] && p->apValue[i]==0 ){ |
| 3955 | return (p->rc = SQLITE_CORRUPT_BKPT); |
| 3956 | } |
| 3957 | if( p->abPK[i]==0 && p->apValue[i+p->nCol]==0 ){ |
| 3958 | sqlite3ValueFree(p->apValue[i]); |
| 3959 | p->apValue[i] = 0; |
| 3960 | } |
| 3961 | } |
| 3962 | } |
| 3963 | } |
| 3964 | |
| 3965 | return SQLITE_ROW; |
| 3966 | } |
| 3967 | |
| 3968 | /* |
| 3969 | ** Advance the changeset iterator to the next change. |
| 3970 | ** |
| 3971 | ** If both paRec and pnRec are NULL, then this function works like the public |
| 3972 | ** API sqlite3changeset_next(). If SQLITE_ROW is returned, then the |
| 3973 | ** sqlite3changeset_new() and old() APIs may be used to query for values. |
| 3974 | ** |
| 3975 | ** Otherwise, if paRec and pnRec are not NULL, then a pointer to the change |
| 3976 | ** record is written to *paRec before returning and the number of bytes in |
| 3977 | ** the record to *pnRec. |
| 3978 | ** |
| 3979 | ** Either way, this function returns SQLITE_ROW if the iterator is |
| 3980 | ** successfully advanced to the next change in the changeset, an SQLite |
| 3981 | ** error code if an error occurs, or SQLITE_DONE if there are no further |
| 3982 | ** changes in the changeset. |
| 3983 | */ |
| 3984 | static int sessionChangesetNext( |
| 3985 | sqlite3_changeset_iter *p, /* Changeset iterator */ |
| 3986 | u8 **paRec, /* If non-NULL, store record pointer here */ |
| 3987 | int *pnRec, /* If non-NULL, store size of record here */ |
| 3988 | int *pbNew /* If non-NULL, true if new table */ |
| 3989 | ){ |
| 3990 | int bEmpty; |
| 3991 | int rc; |
| 3992 | do { |
| 3993 | bEmpty = 0; |
| 3994 | rc = sessionChangesetNextOne(p, paRec, pnRec, pbNew, &bEmpty); |
| 3995 | }while( rc==SQLITE_ROW && p->bSkipEmpty && bEmpty); |
| 3996 | return rc; |
| 3997 | } |
| 3998 | |
| 3999 | /* |
| 4000 | ** Advance an iterator created by sqlite3changeset_start() to the next |
| 4001 | ** change in the changeset. This function may return SQLITE_ROW, SQLITE_DONE |
| 4002 | ** or SQLITE_CORRUPT. |
| 4003 | ** |
| 4004 | ** This function may not be called on iterators passed to a conflict handler |
| 4005 | ** callback by changeset_apply(). |
| 4006 | */ |
| 4007 | int sqlite3changeset_next(sqlite3_changeset_iter *p){ |
| 4008 | return sessionChangesetNext(p, 0, 0, 0); |
| 4009 | } |
| 4010 | |
| 4011 | /* |
| 4012 | ** The following function extracts information on the current change |
| 4013 | ** from a changeset iterator. It may only be called after changeset_next() |
| 4014 | ** has returned SQLITE_ROW. |
| 4015 | */ |
| 4016 | int sqlite3changeset_op( |
| 4017 | sqlite3_changeset_iter *pIter, /* Iterator handle */ |
| 4018 | const char **pzTab, /* OUT: Pointer to table name */ |
| 4019 | int *pnCol, /* OUT: Number of columns in table */ |
| 4020 | int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */ |
| 4021 | int *pbIndirect /* OUT: True if change is indirect */ |
| 4022 | ){ |
| 4023 | *pOp = pIter->op; |
| 4024 | *pnCol = pIter->nCol; |
| 4025 | *pzTab = pIter->zTab; |
| 4026 | if( pbIndirect ) *pbIndirect = pIter->bIndirect; |
| 4027 | return SQLITE_OK; |
| 4028 | } |
| 4029 | |
| 4030 | /* |
| 4031 | ** Return information regarding the PRIMARY KEY and number of columns in |
| 4032 | ** the database table affected by the change that pIter currently points |
| 4033 | ** to. This function may only be called after changeset_next() returns |
| 4034 | ** SQLITE_ROW. |
| 4035 | */ |
| 4036 | int sqlite3changeset_pk( |
| 4037 | sqlite3_changeset_iter *pIter, /* Iterator object */ |
| 4038 | unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */ |
| 4039 | int *pnCol /* OUT: Number of entries in output array */ |
| 4040 | ){ |
| 4041 | *pabPK = pIter->abPK; |
| 4042 | if( pnCol ) *pnCol = pIter->nCol; |
| 4043 | return SQLITE_OK; |
| 4044 | } |
| 4045 | |
| 4046 | /* |
| 4047 | ** This function may only be called while the iterator is pointing to an |
| 4048 | ** SQLITE_UPDATE or SQLITE_DELETE change (see sqlite3changeset_op()). |
| 4049 | ** Otherwise, SQLITE_MISUSE is returned. |
| 4050 | ** |
| 4051 | ** It sets *ppValue to point to an sqlite3_value structure containing the |
| 4052 | ** iVal'th value in the old.* record. Or, if that particular value is not |
| 4053 | ** included in the record (because the change is an UPDATE and the field |
| 4054 | ** was not modified and is not a PK column), set *ppValue to NULL. |
| 4055 | ** |
| 4056 | ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is |
| 4057 | ** not modified. Otherwise, SQLITE_OK. |
| 4058 | */ |
| 4059 | int sqlite3changeset_old( |
| 4060 | sqlite3_changeset_iter *pIter, /* Changeset iterator */ |
| 4061 | int iVal, /* Index of old.* value to retrieve */ |
| 4062 | sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */ |
| 4063 | ){ |
| 4064 | if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_DELETE ){ |
| 4065 | return SQLITE_MISUSE; |
| 4066 | } |
| 4067 | if( iVal<0 || iVal>=pIter->nCol ){ |
| 4068 | return SQLITE_RANGE; |
| 4069 | } |
| 4070 | *ppValue = pIter->apValue[iVal]; |
| 4071 | return SQLITE_OK; |
| 4072 | } |
| 4073 | |
| 4074 | /* |
| 4075 | ** This function may only be called while the iterator is pointing to an |
| 4076 | ** SQLITE_UPDATE or SQLITE_INSERT change (see sqlite3changeset_op()). |
| 4077 | ** Otherwise, SQLITE_MISUSE is returned. |
| 4078 | ** |
| 4079 | ** It sets *ppValue to point to an sqlite3_value structure containing the |
| 4080 | ** iVal'th value in the new.* record. Or, if that particular value is not |
| 4081 | ** included in the record (because the change is an UPDATE and the field |
| 4082 | ** was not modified), set *ppValue to NULL. |
| 4083 | ** |
| 4084 | ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is |
| 4085 | ** not modified. Otherwise, SQLITE_OK. |
| 4086 | */ |
| 4087 | int sqlite3changeset_new( |
| 4088 | sqlite3_changeset_iter *pIter, /* Changeset iterator */ |
| 4089 | int iVal, /* Index of new.* value to retrieve */ |
| 4090 | sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */ |
| 4091 | ){ |
| 4092 | if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_INSERT ){ |
| 4093 | return SQLITE_MISUSE; |
| 4094 | } |
| 4095 | if( iVal<0 || iVal>=pIter->nCol ){ |
| 4096 | return SQLITE_RANGE; |
| 4097 | } |
| 4098 | *ppValue = pIter->apValue[pIter->nCol+iVal]; |
| 4099 | return SQLITE_OK; |
| 4100 | } |
| 4101 | |
| 4102 | /* |
| 4103 | ** The following two macros are used internally. They are similar to the |
| 4104 | ** sqlite3changeset_new() and sqlite3changeset_old() functions, except that |
| 4105 | ** they omit all error checking and return a pointer to the requested value. |
| 4106 | */ |
| 4107 | #define sessionChangesetNew(pIter, iVal) (pIter)->apValue[(pIter)->nCol+(iVal)] |
| 4108 | #define sessionChangesetOld(pIter, iVal) (pIter)->apValue[(iVal)] |
| 4109 | |
| 4110 | /* |
| 4111 | ** This function may only be called with a changeset iterator that has been |
| 4112 | ** passed to an SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT |
| 4113 | ** conflict-handler function. Otherwise, SQLITE_MISUSE is returned. |
| 4114 | ** |
| 4115 | ** If successful, *ppValue is set to point to an sqlite3_value structure |
| 4116 | ** containing the iVal'th value of the conflicting record. |
| 4117 | ** |
| 4118 | ** If value iVal is out-of-range or some other error occurs, an SQLite error |
| 4119 | ** code is returned. Otherwise, SQLITE_OK. |
| 4120 | */ |
| 4121 | int sqlite3changeset_conflict( |
| 4122 | sqlite3_changeset_iter *pIter, /* Changeset iterator */ |
| 4123 | int iVal, /* Index of conflict record value to fetch */ |
| 4124 | sqlite3_value **ppValue /* OUT: Value from conflicting row */ |
| 4125 | ){ |
| 4126 | if( !pIter->pConflict ){ |
| 4127 | return SQLITE_MISUSE; |
| 4128 | } |
| 4129 | if( iVal<0 || iVal>=pIter->nCol ){ |
| 4130 | return SQLITE_RANGE; |
| 4131 | } |
| 4132 | *ppValue = sqlite3_column_value(pIter->pConflict, iVal); |
| 4133 | return SQLITE_OK; |
| 4134 | } |
| 4135 | |
| 4136 | /* |
| 4137 | ** This function may only be called with an iterator passed to an |
| 4138 | ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case |
| 4139 | ** it sets the output variable to the total number of known foreign key |
| 4140 | ** violations in the destination database and returns SQLITE_OK. |
| 4141 | ** |
| 4142 | ** In all other cases this function returns SQLITE_MISUSE. |
| 4143 | */ |
| 4144 | int sqlite3changeset_fk_conflicts( |
| 4145 | sqlite3_changeset_iter *pIter, /* Changeset iterator */ |
| 4146 | int *pnOut /* OUT: Number of FK violations */ |
| 4147 | ){ |
| 4148 | if( pIter->pConflict || pIter->apValue ){ |
| 4149 | return SQLITE_MISUSE; |
| 4150 | } |
| 4151 | *pnOut = pIter->nCol; |
| 4152 | return SQLITE_OK; |
| 4153 | } |
| 4154 | |
| 4155 | |
| 4156 | /* |
| 4157 | ** Finalize an iterator allocated with sqlite3changeset_start(). |
| 4158 | ** |
| 4159 | ** This function may not be called on iterators passed to a conflict handler |
| 4160 | ** callback by changeset_apply(). |
| 4161 | */ |
| 4162 | int sqlite3changeset_finalize(sqlite3_changeset_iter *p){ |
| 4163 | int rc = SQLITE_OK; |
| 4164 | if( p ){ |
| 4165 | int i; /* Used to iterate through p->apValue[] */ |
| 4166 | rc = p->rc; |
| 4167 | if( p->apValue ){ |
| 4168 | for(i=0; i<p->nCol*2; i++) sqlite3ValueFree(p->apValue[i]); |
| 4169 | } |
| 4170 | sqlite3_free(p->tblhdr.aBuf); |
| 4171 | sqlite3_free(p->in.buf.aBuf); |
| 4172 | sqlite3_free(p); |
| 4173 | } |
| 4174 | return rc; |
| 4175 | } |
| 4176 | |
| 4177 | static int sessionChangesetInvert( |
| 4178 | SessionInput *pInput, /* Input changeset */ |
| 4179 | int (*xOutput)(void *pOut, const void *pData, int nData), |
| 4180 | void *pOut, |
| 4181 | int *pnInverted, /* OUT: Number of bytes in output changeset */ |
| 4182 | void **ppInverted /* OUT: Inverse of pChangeset */ |
| 4183 | ){ |
| 4184 | int rc = SQLITE_OK; /* Return value */ |
| 4185 | SessionBuffer sOut; /* Output buffer */ |
| 4186 | int nCol = 0; /* Number of cols in current table */ |
| 4187 | u8 *abPK = 0; /* PK array for current table */ |
| 4188 | sqlite3_value **apVal = 0; /* Space for values for UPDATE inversion */ |
| 4189 | SessionBuffer sPK = {0, 0, 0}; /* PK array for current table */ |
| 4190 | |
| 4191 | /* Initialize the output buffer */ |
| 4192 | memset(&sOut, 0, sizeof(SessionBuffer)); |
| 4193 | |
| 4194 | /* Zero the output variables in case an error occurs. */ |
| 4195 | if( ppInverted ){ |
| 4196 | *ppInverted = 0; |
| 4197 | *pnInverted = 0; |
| 4198 | } |
| 4199 | |
| 4200 | while( 1 ){ |
| 4201 | u8 eType; |
| 4202 | |
| 4203 | /* Test for EOF. */ |
| 4204 | if( (rc = sessionInputBuffer(pInput, 2)) ) goto finished_invert; |
| 4205 | if( pInput->iNext+1>=pInput->nData ){ |
| 4206 | if( pInput->iNext!=pInput->nData ){ |
| 4207 | rc = SQLITE_CORRUPT_BKPT; |
| 4208 | goto finished_invert; |
| 4209 | } |
| 4210 | break; |
| 4211 | } |
| 4212 | eType = pInput->aData[pInput->iNext]; |
| 4213 | |
| 4214 | switch( eType ){ |
| 4215 | case 'T': { |
| 4216 | /* A 'table' record consists of: |
| 4217 | ** |
| 4218 | ** * A constant 'T' character, |
| 4219 | ** * Number of columns in said table (a varint), |
| 4220 | ** * An array of nCol bytes (sPK), |
| 4221 | ** * A nul-terminated table name. |
| 4222 | */ |
| 4223 | int nByte; |
| 4224 | int nVar; |
| 4225 | pInput->iNext++; |
| 4226 | if( (rc = sessionChangesetBufferTblhdr(pInput, &nByte)) ){ |
| 4227 | goto finished_invert; |
| 4228 | } |
| 4229 | nVar = sessionVarintGet(&pInput->aData[pInput->iNext], &nCol); |
| 4230 | sPK.nBuf = 0; |
| 4231 | sessionAppendBlob(&sPK, &pInput->aData[pInput->iNext+nVar], nCol, &rc); |
| 4232 | sessionAppendByte(&sOut, eType, &rc); |
| 4233 | sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc); |
| 4234 | if( rc ) goto finished_invert; |
| 4235 | |
| 4236 | pInput->iNext += nByte; |
| 4237 | sqlite3_free(apVal); |
| 4238 | apVal = 0; |
| 4239 | abPK = sPK.aBuf; |
| 4240 | break; |
| 4241 | } |
| 4242 | |
| 4243 | case SQLITE_INSERT: |
| 4244 | case SQLITE_DELETE: { |
| 4245 | int nByte; |
| 4246 | int bIndirect = pInput->aData[pInput->iNext+1]; |
| 4247 | int eType2 = (eType==SQLITE_DELETE ? SQLITE_INSERT : SQLITE_DELETE); |
| 4248 | pInput->iNext += 2; |
| 4249 | assert( rc==SQLITE_OK ); |
| 4250 | rc = sessionChangesetBufferRecord(pInput, nCol, &nByte); |
| 4251 | sessionAppendByte(&sOut, eType2, &rc); |
| 4252 | sessionAppendByte(&sOut, bIndirect, &rc); |
| 4253 | sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc); |
| 4254 | pInput->iNext += nByte; |
| 4255 | if( rc ) goto finished_invert; |
| 4256 | break; |
| 4257 | } |
| 4258 | |
| 4259 | case SQLITE_UPDATE: { |
| 4260 | int iCol; |
| 4261 | |
| 4262 | if( 0==apVal ){ |
| 4263 | apVal = (sqlite3_value **)sqlite3_malloc64(sizeof(apVal[0])*nCol*2); |
| 4264 | if( 0==apVal ){ |
| 4265 | rc = SQLITE_NOMEM; |
| 4266 | goto finished_invert; |
| 4267 | } |
| 4268 | memset(apVal, 0, sizeof(apVal[0])*nCol*2); |
| 4269 | } |
| 4270 | |
| 4271 | /* Write the header for the new UPDATE change. Same as the original. */ |
| 4272 | sessionAppendByte(&sOut, eType, &rc); |
| 4273 | sessionAppendByte(&sOut, pInput->aData[pInput->iNext+1], &rc); |
| 4274 | |
| 4275 | /* Read the old.* and new.* records for the update change. */ |
| 4276 | pInput->iNext += 2; |
| 4277 | rc = sessionReadRecord(pInput, nCol, 0, &apVal[0], 0); |
| 4278 | if( rc==SQLITE_OK ){ |
| 4279 | rc = sessionReadRecord(pInput, nCol, 0, &apVal[nCol], 0); |
| 4280 | } |
| 4281 | |
| 4282 | /* Write the new old.* record. Consists of the PK columns from the |
| 4283 | ** original old.* record, and the other values from the original |
| 4284 | ** new.* record. */ |
| 4285 | for(iCol=0; iCol<nCol; iCol++){ |
| 4286 | sqlite3_value *pVal = apVal[iCol + (abPK[iCol] ? 0 : nCol)]; |
| 4287 | sessionAppendValue(&sOut, pVal, &rc); |
| 4288 | } |
| 4289 | |
| 4290 | /* Write the new new.* record. Consists of a copy of all values |
| 4291 | ** from the original old.* record, except for the PK columns, which |
| 4292 | ** are set to "undefined". */ |
| 4293 | for(iCol=0; iCol<nCol; iCol++){ |
| 4294 | sqlite3_value *pVal = (abPK[iCol] ? 0 : apVal[iCol]); |
| 4295 | sessionAppendValue(&sOut, pVal, &rc); |
| 4296 | } |
| 4297 | |
| 4298 | for(iCol=0; iCol<nCol*2; iCol++){ |
| 4299 | sqlite3ValueFree(apVal[iCol]); |
| 4300 | } |
| 4301 | memset(apVal, 0, sizeof(apVal[0])*nCol*2); |
| 4302 | if( rc!=SQLITE_OK ){ |
| 4303 | goto finished_invert; |
| 4304 | } |
| 4305 | |
| 4306 | break; |
| 4307 | } |
| 4308 | |
| 4309 | default: |
| 4310 | rc = SQLITE_CORRUPT_BKPT; |
| 4311 | goto finished_invert; |
| 4312 | } |
| 4313 | |
| 4314 | assert( rc==SQLITE_OK ); |
| 4315 | if( xOutput && sOut.nBuf>=sessions_strm_chunk_size ){ |
| 4316 | rc = xOutput(pOut, sOut.aBuf, sOut.nBuf); |
| 4317 | sOut.nBuf = 0; |
| 4318 | if( rc!=SQLITE_OK ) goto finished_invert; |
| 4319 | } |
| 4320 | } |
| 4321 | |
| 4322 | assert( rc==SQLITE_OK ); |
| 4323 | if( pnInverted && ALWAYS(ppInverted) ){ |
| 4324 | *pnInverted = sOut.nBuf; |
| 4325 | *ppInverted = sOut.aBuf; |
| 4326 | sOut.aBuf = 0; |
| 4327 | }else if( sOut.nBuf>0 && ALWAYS(xOutput!=0) ){ |
| 4328 | rc = xOutput(pOut, sOut.aBuf, sOut.nBuf); |
| 4329 | } |
| 4330 | |
| 4331 | finished_invert: |
| 4332 | sqlite3_free(sOut.aBuf); |
| 4333 | sqlite3_free(apVal); |
| 4334 | sqlite3_free(sPK.aBuf); |
| 4335 | return rc; |
| 4336 | } |
| 4337 | |
| 4338 | |
| 4339 | /* |
| 4340 | ** Invert a changeset object. |
| 4341 | */ |
| 4342 | int sqlite3changeset_invert( |
| 4343 | int nChangeset, /* Number of bytes in input */ |
| 4344 | const void *pChangeset, /* Input changeset */ |
| 4345 | int *pnInverted, /* OUT: Number of bytes in output changeset */ |
| 4346 | void **ppInverted /* OUT: Inverse of pChangeset */ |
| 4347 | ){ |
| 4348 | SessionInput sInput; |
| 4349 | |
| 4350 | /* Set up the input stream */ |
| 4351 | memset(&sInput, 0, sizeof(SessionInput)); |
| 4352 | sInput.nData = nChangeset; |
| 4353 | sInput.aData = (u8*)pChangeset; |
| 4354 | |
| 4355 | return sessionChangesetInvert(&sInput, 0, 0, pnInverted, ppInverted); |
| 4356 | } |
| 4357 | |
| 4358 | /* |
| 4359 | ** Streaming version of sqlite3changeset_invert(). |
| 4360 | */ |
| 4361 | int sqlite3changeset_invert_strm( |
| 4362 | int (*xInput)(void *pIn, void *pData, int *pnData), |
| 4363 | void *pIn, |
| 4364 | int (*xOutput)(void *pOut, const void *pData, int nData), |
| 4365 | void *pOut |
| 4366 | ){ |
| 4367 | SessionInput sInput; |
| 4368 | int rc; |
| 4369 | |
| 4370 | /* Set up the input stream */ |
| 4371 | memset(&sInput, 0, sizeof(SessionInput)); |
| 4372 | sInput.xInput = xInput; |
| 4373 | sInput.pIn = pIn; |
| 4374 | |
| 4375 | rc = sessionChangesetInvert(&sInput, xOutput, pOut, 0, 0); |
| 4376 | sqlite3_free(sInput.buf.aBuf); |
| 4377 | return rc; |
| 4378 | } |
| 4379 | |
| 4380 | |
| 4381 | typedef struct SessionUpdate SessionUpdate; |
| 4382 | struct SessionUpdate { |
| 4383 | sqlite3_stmt *pStmt; |
| 4384 | u32 *aMask; |
| 4385 | SessionUpdate *pNext; |
| 4386 | }; |
| 4387 | |
| 4388 | typedef struct SessionApplyCtx SessionApplyCtx; |
| 4389 | struct SessionApplyCtx { |
| 4390 | sqlite3 *db; |
| 4391 | sqlite3_stmt *pDelete; /* DELETE statement */ |
| 4392 | sqlite3_stmt *pInsert; /* INSERT statement */ |
| 4393 | sqlite3_stmt *pSelect; /* SELECT statement */ |
| 4394 | int nCol; /* Size of azCol[] and abPK[] arrays */ |
| 4395 | const char **azCol; /* Array of column names */ |
| 4396 | u8 *abPK; /* Boolean array - true if column is in PK */ |
| 4397 | u32 *aUpdateMask; /* Used by sessionUpdateFind */ |
| 4398 | SessionUpdate *pUp; |
| 4399 | int bStat1; /* True if table is sqlite_stat1 */ |
| 4400 | int bDeferConstraints; /* True to defer constraints */ |
| 4401 | int bInvertConstraints; /* Invert when iterating constraints buffer */ |
| 4402 | SessionBuffer constraints; /* Deferred constraints are stored here */ |
| 4403 | SessionBuffer rebase; /* Rebase information (if any) here */ |
| 4404 | u8 bRebaseStarted; /* If table header is already in rebase */ |
| 4405 | u8 bRebase; /* True to collect rebase information */ |
| 4406 | u8 bIgnoreNoop; /* True to ignore no-op conflicts */ |
| 4407 | u8 bNoUpdateLoop; /* No update-loop processing */ |
| 4408 | int bRowid; |
| 4409 | char *zErr; /* Error message, if any */ |
| 4410 | }; |
| 4411 | |
| 4412 | /* Number of prepared UPDATE statements to cache. */ |
| 4413 | #define SESSION_UPDATE_CACHE_SZ 12 |
| 4414 | |
| 4415 | /* |
| 4416 | ** Find a prepared UPDATE statement suitable for the UPDATE step currently |
| 4417 | ** being visited by the iterator. The UPDATE is of the form: |
| 4418 | ** |
| 4419 | ** UPDATE tbl SET col = ?, col2 = ? WHERE pk1 IS ? AND pk2 IS ? |
| 4420 | */ |
| 4421 | static int sessionUpdateFind( |
| 4422 | sqlite3_changeset_iter *pIter, |
| 4423 | SessionApplyCtx *p, |
| 4424 | int bPatchset, |
| 4425 | sqlite3_stmt **ppStmt |
| 4426 | ){ |
| 4427 | int rc = SQLITE_OK; |
| 4428 | SessionUpdate *pUp = 0; |
| 4429 | int nCol = pIter->nCol; |
| 4430 | int nU32 = (pIter->nCol+33)/32; |
| 4431 | int ii; |
| 4432 | |
| 4433 | if( p->aUpdateMask==0 ){ |
| 4434 | p->aUpdateMask = sqlite3_malloc(nU32*sizeof(u32)); |
| 4435 | if( p->aUpdateMask==0 ){ |
| 4436 | rc = SQLITE_NOMEM; |
| 4437 | } |
| 4438 | } |
| 4439 | |
| 4440 | if( rc==SQLITE_OK ){ |
| 4441 | memset(p->aUpdateMask, 0, nU32*sizeof(u32)); |
| 4442 | rc = SQLITE_CORRUPT; |
| 4443 | for(ii=0; ii<pIter->nCol; ii++){ |
| 4444 | if( sessionChangesetNew(pIter, ii) ){ |
| 4445 | p->aUpdateMask[ii/32] |= (1<<(ii%32)); |
| 4446 | rc = SQLITE_OK; |
| 4447 | } |
| 4448 | } |
| 4449 | } |
| 4450 | |
| 4451 | if( rc==SQLITE_OK ){ |
| 4452 | if( bPatchset ) p->aUpdateMask[nCol/32] |= (1<<(nCol%32)); |
| 4453 | |
| 4454 | if( p->pUp ){ |
| 4455 | int nUp = 0; |
| 4456 | SessionUpdate **pp = &p->pUp; |
| 4457 | while( 1 ){ |
| 4458 | nUp++; |
| 4459 | if( 0==memcmp(p->aUpdateMask, (*pp)->aMask, nU32*sizeof(u32)) ){ |
| 4460 | pUp = *pp; |
| 4461 | *pp = pUp->pNext; |
| 4462 | pUp->pNext = p->pUp; |
| 4463 | p->pUp = pUp; |
| 4464 | break; |
| 4465 | } |
| 4466 | |
| 4467 | if( (*pp)->pNext ){ |
| 4468 | pp = &(*pp)->pNext; |
| 4469 | }else{ |
| 4470 | if( nUp>=SESSION_UPDATE_CACHE_SZ ){ |
| 4471 | sqlite3_finalize((*pp)->pStmt); |
| 4472 | sqlite3_free(*pp); |
| 4473 | *pp = 0; |
| 4474 | } |
| 4475 | break; |
| 4476 | } |
| 4477 | } |
| 4478 | } |
| 4479 | |
| 4480 | if( pUp==0 ){ |
| 4481 | int nByte = sizeof(SessionUpdate) * nU32*sizeof(u32); |
| 4482 | int bStat1 = (sqlite3_stricmp(pIter->zTab, "sqlite_stat1")==0); |
| 4483 | pUp = (SessionUpdate*)sqlite3_malloc(nByte); |
| 4484 | if( pUp==0 ){ |
| 4485 | rc = SQLITE_NOMEM; |
| 4486 | }else{ |
| 4487 | const char *zSep = ""; |
| 4488 | SessionBuffer buf; |
| 4489 | |
| 4490 | memset(&buf, 0, sizeof(buf)); |
| 4491 | pUp->aMask = (u32*)&pUp[1]; |
| 4492 | memcpy(pUp->aMask, p->aUpdateMask, nU32*sizeof(u32)); |
| 4493 | |
| 4494 | sessionAppendStr(&buf, "UPDATE main.", &rc); |
| 4495 | sessionAppendIdent(&buf, pIter->zTab, &rc); |
| 4496 | sessionAppendStr(&buf, " SET ", &rc); |
| 4497 | |
| 4498 | /* Create the assignments part of the UPDATE */ |
| 4499 | for(ii=0; ii<pIter->nCol; ii++){ |
| 4500 | if( p->abPK[ii]==0 && sessionChangesetNew(pIter, ii) ){ |
| 4501 | sessionAppendStr(&buf, zSep, &rc); |
| 4502 | sessionAppendIdent(&buf, p->azCol[ii], &rc); |
| 4503 | sessionAppendStr(&buf, " = ?", &rc); |
| 4504 | sessionAppendInteger(&buf, ii*2+1, &rc); |
| 4505 | zSep = ", "; |
| 4506 | } |
| 4507 | } |
| 4508 | |
| 4509 | /* Create the WHERE clause part of the UPDATE */ |
| 4510 | zSep = ""; |
| 4511 | sessionAppendStr(&buf, " WHERE ", &rc); |
| 4512 | for(ii=0; ii<pIter->nCol; ii++){ |
| 4513 | if( p->abPK[ii] || (bPatchset==0 && sessionChangesetOld(pIter, ii)) ){ |
| 4514 | sessionAppendStr(&buf, zSep, &rc); |
| 4515 | if( bStat1 && ii==1 ){ |
| 4516 | assert( sqlite3_stricmp(p->azCol[ii], "idx")==0 ); |
| 4517 | sessionAppendStr(&buf, |
| 4518 | "idx IS CASE " |
| 4519 | "WHEN length(?4)=0 AND typeof(?4)='blob' THEN NULL " |
| 4520 | "ELSE ?4 END ", &rc |
| 4521 | ); |
| 4522 | }else{ |
| 4523 | sessionAppendIdent(&buf, p->azCol[ii], &rc); |
| 4524 | sessionAppendStr(&buf, " IS ?", &rc); |
| 4525 | sessionAppendInteger(&buf, ii*2+2, &rc); |
| 4526 | } |
| 4527 | zSep = " AND "; |
| 4528 | } |
| 4529 | } |
| 4530 | |
| 4531 | if( rc==SQLITE_OK ){ |
| 4532 | char *zSql = (char*)buf.aBuf; |
| 4533 | rc = sqlite3_prepare_v2(p->db, zSql, buf.nBuf, &pUp->pStmt, 0); |
| 4534 | } |
| 4535 | |
| 4536 | if( rc!=SQLITE_OK ){ |
| 4537 | sqlite3_free(pUp); |
| 4538 | pUp = 0; |
| 4539 | }else{ |
| 4540 | pUp->pNext = p->pUp; |
| 4541 | p->pUp = pUp; |
| 4542 | } |
| 4543 | sqlite3_free(buf.aBuf); |
| 4544 | } |
| 4545 | } |
| 4546 | } |
| 4547 | |
| 4548 | assert( (rc==SQLITE_OK)==(pUp!=0) ); |
| 4549 | if( pUp ){ |
| 4550 | *ppStmt = pUp->pStmt; |
| 4551 | }else{ |
| 4552 | *ppStmt = 0; |
| 4553 | } |
| 4554 | return rc; |
| 4555 | } |
| 4556 | |
| 4557 | /* |
| 4558 | ** Free all cached UPDATE statements. |
| 4559 | */ |
| 4560 | static void sessionUpdateFree(SessionApplyCtx *p){ |
| 4561 | SessionUpdate *pUp; |
| 4562 | SessionUpdate *pNext; |
| 4563 | for(pUp=p->pUp; pUp; pUp=pNext){ |
| 4564 | pNext = pUp->pNext; |
| 4565 | sqlite3_finalize(pUp->pStmt); |
| 4566 | sqlite3_free(pUp); |
| 4567 | } |
| 4568 | p->pUp = 0; |
| 4569 | sqlite3_free(p->aUpdateMask); |
| 4570 | p->aUpdateMask = 0; |
| 4571 | } |
| 4572 | |
| 4573 | /* |
| 4574 | ** Formulate a statement to DELETE a row from database db. Assuming a table |
| 4575 | ** structure like this: |
| 4576 | ** |
| 4577 | ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c)); |
| 4578 | ** |
| 4579 | ** The DELETE statement looks like this: |
| 4580 | ** |
| 4581 | ** DELETE FROM x WHERE a = :1 AND c = :3 AND (:5 OR b IS :2 AND d IS :4) |
| 4582 | ** |
| 4583 | ** Variable :5 (nCol+1) is a boolean. It should be set to 0 if we require |
| 4584 | ** matching b and d values, or 1 otherwise. The second case comes up if the |
| 4585 | ** conflict handler is invoked with NOTFOUND and returns CHANGESET_REPLACE. |
| 4586 | ** |
| 4587 | ** If successful, SQLITE_OK is returned and SessionApplyCtx.pDelete is left |
| 4588 | ** pointing to the prepared version of the SQL statement. |
| 4589 | */ |
| 4590 | static int sessionDeleteRow( |
| 4591 | sqlite3 *db, /* Database handle */ |
| 4592 | const char *zTab, /* Table name */ |
| 4593 | SessionApplyCtx *p /* Session changeset-apply context */ |
| 4594 | ){ |
| 4595 | int i; |
| 4596 | const char *zSep = ""; |
| 4597 | int rc = SQLITE_OK; |
| 4598 | SessionBuffer buf = {0, 0, 0}; |
| 4599 | int nPk = 0; |
| 4600 | |
| 4601 | sessionAppendStr(&buf, "DELETE FROM main.", &rc); |
| 4602 | sessionAppendIdent(&buf, zTab, &rc); |
| 4603 | sessionAppendStr(&buf, " WHERE ", &rc); |
| 4604 | |
| 4605 | for(i=0; i<p->nCol; i++){ |
| 4606 | if( p->abPK[i] ){ |
| 4607 | nPk++; |
| 4608 | sessionAppendStr(&buf, zSep, &rc); |
| 4609 | sessionAppendIdent(&buf, p->azCol[i], &rc); |
| 4610 | sessionAppendStr(&buf, " = ?", &rc); |
| 4611 | sessionAppendInteger(&buf, i+1, &rc); |
| 4612 | zSep = " AND "; |
| 4613 | } |
| 4614 | } |
| 4615 | |
| 4616 | if( nPk<p->nCol ){ |
| 4617 | sessionAppendStr(&buf, " AND (?", &rc); |
| 4618 | sessionAppendInteger(&buf, p->nCol+1, &rc); |
| 4619 | sessionAppendStr(&buf, " OR ", &rc); |
| 4620 | |
| 4621 | zSep = ""; |
| 4622 | for(i=0; i<p->nCol; i++){ |
| 4623 | if( !p->abPK[i] ){ |
| 4624 | sessionAppendStr(&buf, zSep, &rc); |
| 4625 | sessionAppendIdent(&buf, p->azCol[i], &rc); |
| 4626 | sessionAppendStr(&buf, " IS ?", &rc); |
| 4627 | sessionAppendInteger(&buf, i+1, &rc); |
| 4628 | zSep = "AND "; |
| 4629 | } |
| 4630 | } |
| 4631 | sessionAppendStr(&buf, ")", &rc); |
| 4632 | } |
| 4633 | |
| 4634 | if( rc==SQLITE_OK ){ |
| 4635 | rc = sessionPrepare(db, &p->pDelete, &p->zErr, (char*)buf.aBuf); |
| 4636 | } |
| 4637 | sqlite3_free(buf.aBuf); |
| 4638 | |
| 4639 | return rc; |
| 4640 | } |
| 4641 | |
| 4642 | /* |
| 4643 | ** Formulate and prepare an SQL statement to query table zTab by primary |
| 4644 | ** key. Assuming the following table structure: |
| 4645 | ** |
| 4646 | ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c)); |
| 4647 | ** |
| 4648 | ** The SELECT statement looks like this: |
| 4649 | ** |
| 4650 | ** SELECT * FROM x WHERE a = ?1 AND c = ?3 |
| 4651 | ** |
| 4652 | ** If successful, SQLITE_OK is returned and SessionApplyCtx.pSelect is left |
| 4653 | ** pointing to the prepared version of the SQL statement. |
| 4654 | */ |
| 4655 | static int sessionSelectRow( |
| 4656 | sqlite3 *db, /* Database handle */ |
| 4657 | const char *zTab, /* Table name */ |
| 4658 | SessionApplyCtx *p /* Session changeset-apply context */ |
| 4659 | ){ |
| 4660 | /* TODO */ |
| 4661 | return sessionSelectStmt(db, p->bIgnoreNoop, |
| 4662 | "main", zTab, p->bRowid, p->nCol, p->azCol, p->abPK, &p->pSelect, &p->zErr |
| 4663 | ); |
| 4664 | } |
| 4665 | |
| 4666 | /* |
| 4667 | ** Formulate and prepare an INSERT statement to add a record to table zTab. |
| 4668 | ** For example: |
| 4669 | ** |
| 4670 | ** INSERT INTO main."zTab" VALUES(?1, ?2, ?3 ...); |
| 4671 | ** |
| 4672 | ** If successful, SQLITE_OK is returned and SessionApplyCtx.pInsert is left |
| 4673 | ** pointing to the prepared version of the SQL statement. |
| 4674 | */ |
| 4675 | static int sessionInsertRow( |
| 4676 | sqlite3 *db, /* Database handle */ |
| 4677 | const char *zTab, /* Table name */ |
| 4678 | SessionApplyCtx *p /* Session changeset-apply context */ |
| 4679 | ){ |
| 4680 | int rc = SQLITE_OK; |
| 4681 | int i; |
| 4682 | SessionBuffer buf = {0, 0, 0}; |
| 4683 | |
| 4684 | sessionAppendStr(&buf, "INSERT INTO main.", &rc); |
| 4685 | sessionAppendIdent(&buf, zTab, &rc); |
| 4686 | sessionAppendStr(&buf, "(", &rc); |
| 4687 | for(i=0; i<p->nCol; i++){ |
| 4688 | if( i!=0 ) sessionAppendStr(&buf, ", ", &rc); |
| 4689 | sessionAppendIdent(&buf, p->azCol[i], &rc); |
| 4690 | } |
| 4691 | |
| 4692 | sessionAppendStr(&buf, ") VALUES(?", &rc); |
| 4693 | for(i=1; i<p->nCol; i++){ |
| 4694 | sessionAppendStr(&buf, ", ?", &rc); |
| 4695 | } |
| 4696 | sessionAppendStr(&buf, ")", &rc); |
| 4697 | |
| 4698 | if( rc==SQLITE_OK ){ |
| 4699 | rc = sessionPrepare(db, &p->pInsert, &p->zErr, (char*)buf.aBuf); |
| 4700 | } |
| 4701 | sqlite3_free(buf.aBuf); |
| 4702 | return rc; |
| 4703 | } |
| 4704 | |
| 4705 | /* |
| 4706 | ** Prepare statements for applying changes to the sqlite_stat1 table. |
| 4707 | ** These are similar to those created by sessionSelectRow(), |
| 4708 | ** sessionInsertRow(), sessionUpdateRow() and sessionDeleteRow() for |
| 4709 | ** other tables. |
| 4710 | */ |
| 4711 | static int sessionStat1Sql(sqlite3 *db, SessionApplyCtx *p){ |
| 4712 | int rc = sessionSelectRow(db, "sqlite_stat1", p); |
| 4713 | if( rc==SQLITE_OK ){ |
| 4714 | rc = sessionPrepare(db, &p->pInsert, 0, |
| 4715 | "INSERT INTO main.sqlite_stat1 VALUES(?1, " |
| 4716 | "CASE WHEN length(?2)=0 AND typeof(?2)='blob' THEN NULL ELSE ?2 END, " |
| 4717 | "?3)" |
| 4718 | ); |
| 4719 | } |
| 4720 | if( rc==SQLITE_OK ){ |
| 4721 | rc = sessionPrepare(db, &p->pDelete, 0, |
| 4722 | "DELETE FROM main.sqlite_stat1 WHERE tbl=?1 AND idx IS " |
| 4723 | "CASE WHEN length(?2)=0 AND typeof(?2)='blob' THEN NULL ELSE ?2 END " |
| 4724 | "AND (?4 OR stat IS ?3)" |
| 4725 | ); |
| 4726 | } |
| 4727 | return rc; |
| 4728 | } |
| 4729 | |
| 4730 | /* |
| 4731 | ** A wrapper around sqlite3_bind_value() that detects an extra problem. |
| 4732 | ** See comments in the body of this function for details. |
| 4733 | */ |
| 4734 | static int sessionBindValue( |
| 4735 | sqlite3_stmt *pStmt, /* Statement to bind value to */ |
| 4736 | int i, /* Parameter number to bind to */ |
| 4737 | sqlite3_value *pVal /* Value to bind */ |
| 4738 | ){ |
| 4739 | int eType = sqlite3_value_type(pVal); |
| 4740 | /* COVERAGE: The (pVal->z==0) branch is never true using current versions |
| 4741 | ** of SQLite. If a malloc fails in an sqlite3_value_xxx() function, either |
| 4742 | ** the (pVal->z) variable remains as it was or the type of the value is |
| 4743 | ** set to SQLITE_NULL. */ |
| 4744 | if( (eType==SQLITE_TEXT || eType==SQLITE_BLOB) && pVal->z==0 ){ |
| 4745 | /* This condition occurs when an earlier OOM in a call to |
| 4746 | ** sqlite3_value_text() or sqlite3_value_blob() (perhaps from within |
| 4747 | ** a conflict-handler) has zeroed the pVal->z pointer. Return NOMEM. */ |
| 4748 | return SQLITE_NOMEM; |
| 4749 | } |
| 4750 | return sqlite3_bind_value(pStmt, i, pVal); |
| 4751 | } |
| 4752 | |
| 4753 | /* |
| 4754 | ** Iterator pIter must point to an SQLITE_INSERT entry. This function |
| 4755 | ** transfers new.* values from the current iterator entry to statement |
| 4756 | ** pStmt. The table being inserted into has nCol columns. |
| 4757 | ** |
| 4758 | ** New.* value $i from the iterator is bound to variable ($i+1) of |
| 4759 | ** statement pStmt. If parameter abPK is NULL, all values from 0 to (nCol-1) |
| 4760 | ** are transfered to the statement. Otherwise, if abPK is not NULL, it points |
| 4761 | ** to an array nCol elements in size. In this case only those values for |
| 4762 | ** which abPK[$i] is true are read from the iterator and bound to the |
| 4763 | ** statement. |
| 4764 | ** |
| 4765 | ** An SQLite error code is returned if an error occurs. Otherwise, SQLITE_OK. |
| 4766 | */ |
| 4767 | static int sessionBindRow( |
| 4768 | sqlite3_changeset_iter *pIter, /* Iterator to read values from */ |
| 4769 | int(*xValue)(sqlite3_changeset_iter *, int, sqlite3_value **), |
| 4770 | int nCol, /* Number of columns */ |
| 4771 | u8 *abPK, /* If not NULL, bind only if true */ |
| 4772 | sqlite3_stmt *pStmt /* Bind values to this statement */ |
| 4773 | ){ |
| 4774 | int i; |
| 4775 | int rc = SQLITE_OK; |
| 4776 | |
| 4777 | /* Neither sqlite3changeset_old or sqlite3changeset_new can fail if the |
| 4778 | ** argument iterator points to a suitable entry. Make sure that xValue |
| 4779 | ** is one of these to guarantee that it is safe to ignore the return |
| 4780 | ** in the code below. */ |
| 4781 | assert( xValue==sqlite3changeset_old || xValue==sqlite3changeset_new ); |
| 4782 | |
| 4783 | for(i=0; rc==SQLITE_OK && i<nCol; i++){ |
| 4784 | if( !abPK || abPK[i] ){ |
| 4785 | sqlite3_value *pVal = 0; |
| 4786 | (void)xValue(pIter, i, &pVal); |
| 4787 | if( pVal==0 ){ |
| 4788 | /* The value in the changeset was "undefined". This indicates a |
| 4789 | ** corrupt changeset blob. */ |
| 4790 | rc = SQLITE_CORRUPT_BKPT; |
| 4791 | }else{ |
| 4792 | rc = sessionBindValue(pStmt, i+1, pVal); |
| 4793 | } |
| 4794 | } |
| 4795 | } |
| 4796 | return rc; |
| 4797 | } |
| 4798 | |
| 4799 | /* |
| 4800 | ** SQL statement pSelect is as generated by the sessionSelectRow() function. |
| 4801 | ** This function binds the primary key values from the change that changeset |
| 4802 | ** iterator pIter points to to the SELECT and attempts to seek to the table |
| 4803 | ** entry. If a row is found, the SELECT statement left pointing at the row |
| 4804 | ** and SQLITE_ROW is returned. Otherwise, if no row is found and no error |
| 4805 | ** has occured, the statement is reset and SQLITE_OK is returned. If an |
| 4806 | ** error occurs, the statement is reset and an SQLite error code is returned. |
| 4807 | ** |
| 4808 | ** If this function returns SQLITE_ROW, the caller must eventually reset() |
| 4809 | ** statement pSelect. If any other value is returned, the statement does |
| 4810 | ** not require a reset(). |
| 4811 | ** |
| 4812 | ** If the iterator currently points to an INSERT record, bind values from the |
| 4813 | ** new.* record to the SELECT statement. Or, if it points to a DELETE or |
| 4814 | ** UPDATE, bind values from the old.* record. |
| 4815 | */ |
| 4816 | static int sessionSeekToRow( |
| 4817 | sqlite3_changeset_iter *pIter, /* Changeset iterator */ |
| 4818 | SessionApplyCtx *p |
| 4819 | ){ |
| 4820 | sqlite3_stmt *pSelect = p->pSelect; |
| 4821 | int rc; /* Return code */ |
| 4822 | int nCol; /* Number of columns in table */ |
| 4823 | int op; /* Changset operation (SQLITE_UPDATE etc.) */ |
| 4824 | const char *zDummy; /* Unused */ |
| 4825 | |
| 4826 | sqlite3_clear_bindings(pSelect); |
| 4827 | sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0); |
| 4828 | rc = sessionBindRow(pIter, |
| 4829 | op==SQLITE_INSERT ? sqlite3changeset_new : sqlite3changeset_old, |
| 4830 | nCol, p->abPK, pSelect |
| 4831 | ); |
| 4832 | |
| 4833 | if( op!=SQLITE_DELETE && p->bIgnoreNoop ){ |
| 4834 | int ii; |
| 4835 | for(ii=0; rc==SQLITE_OK && ii<nCol; ii++){ |
| 4836 | if( p->abPK[ii]==0 ){ |
| 4837 | sqlite3_value *pVal = 0; |
| 4838 | sqlite3changeset_new(pIter, ii, &pVal); |
| 4839 | sqlite3_bind_int(pSelect, ii+1+nCol, (pVal==0)); |
| 4840 | if( pVal ) rc = sessionBindValue(pSelect, ii+1, pVal); |
| 4841 | } |
| 4842 | } |
| 4843 | } |
| 4844 | |
| 4845 | if( rc==SQLITE_OK ){ |
| 4846 | rc = sqlite3_step(pSelect); |
| 4847 | if( rc!=SQLITE_ROW ) rc = sqlite3_reset(pSelect); |
| 4848 | } |
| 4849 | |
| 4850 | return rc; |
| 4851 | } |
| 4852 | |
| 4853 | /* |
| 4854 | ** This function is called from within sqlite3changeset_apply_v2() when |
| 4855 | ** a conflict is encountered and resolved using conflict resolution |
| 4856 | ** mode eType (either SQLITE_CHANGESET_OMIT or SQLITE_CHANGESET_REPLACE).. |
| 4857 | ** It adds a conflict resolution record to the buffer in |
| 4858 | ** SessionApplyCtx.rebase, which will eventually be returned to the caller |
| 4859 | ** of apply_v2() as the "rebase" buffer. |
| 4860 | ** |
| 4861 | ** Return SQLITE_OK if successful, or an SQLite error code otherwise. |
| 4862 | */ |
| 4863 | static int sessionRebaseAdd( |
| 4864 | SessionApplyCtx *p, /* Apply context */ |
| 4865 | int eType, /* Conflict resolution (OMIT or REPLACE) */ |
| 4866 | sqlite3_changeset_iter *pIter /* Iterator pointing at current change */ |
| 4867 | ){ |
| 4868 | int rc = SQLITE_OK; |
| 4869 | if( p->bRebase ){ |
| 4870 | int i; |
| 4871 | int eOp = pIter->op; |
| 4872 | if( p->bRebaseStarted==0 ){ |
| 4873 | /* Append a table-header to the rebase buffer */ |
| 4874 | const char *zTab = pIter->zTab; |
| 4875 | sessionAppendByte(&p->rebase, 'T', &rc); |
| 4876 | sessionAppendVarint(&p->rebase, p->nCol, &rc); |
| 4877 | sessionAppendBlob(&p->rebase, p->abPK, p->nCol, &rc); |
| 4878 | sessionAppendBlob(&p->rebase, (u8*)zTab, (int)strlen(zTab)+1, &rc); |
| 4879 | p->bRebaseStarted = 1; |
| 4880 | } |
| 4881 | |
| 4882 | assert( eType==SQLITE_CHANGESET_REPLACE||eType==SQLITE_CHANGESET_OMIT ); |
| 4883 | assert( eOp==SQLITE_DELETE || eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE ); |
| 4884 | |
| 4885 | sessionAppendByte(&p->rebase, |
| 4886 | (eOp==SQLITE_DELETE ? SQLITE_DELETE : SQLITE_INSERT), &rc |
| 4887 | ); |
| 4888 | sessionAppendByte(&p->rebase, (eType==SQLITE_CHANGESET_REPLACE), &rc); |
| 4889 | for(i=0; i<p->nCol; i++){ |
| 4890 | sqlite3_value *pVal = 0; |
| 4891 | if( eOp==SQLITE_DELETE || (eOp==SQLITE_UPDATE && p->abPK[i]) ){ |
| 4892 | sqlite3changeset_old(pIter, i, &pVal); |
| 4893 | }else{ |
| 4894 | sqlite3changeset_new(pIter, i, &pVal); |
| 4895 | } |
| 4896 | sessionAppendValue(&p->rebase, pVal, &rc); |
| 4897 | } |
| 4898 | } |
| 4899 | return rc; |
| 4900 | } |
| 4901 | |
| 4902 | /* |
| 4903 | ** Invoke the conflict handler for the change that the changeset iterator |
| 4904 | ** currently points to. |
| 4905 | ** |
| 4906 | ** Argument eType must be either CHANGESET_DATA or CHANGESET_CONFLICT. |
| 4907 | ** If argument pbReplace is NULL, then the type of conflict handler invoked |
| 4908 | ** depends solely on eType, as follows: |
| 4909 | ** |
| 4910 | ** eType value Value passed to xConflict |
| 4911 | ** ------------------------------------------------- |
| 4912 | ** CHANGESET_DATA CHANGESET_NOTFOUND |
| 4913 | ** CHANGESET_CONFLICT CHANGESET_CONSTRAINT |
| 4914 | ** |
| 4915 | ** Or, if pbReplace is not NULL, then an attempt is made to find an existing |
| 4916 | ** record with the same primary key as the record about to be deleted, updated |
| 4917 | ** or inserted. If such a record can be found, it is available to the conflict |
| 4918 | ** handler as the "conflicting" record. In this case the type of conflict |
| 4919 | ** handler invoked is as follows: |
| 4920 | ** |
| 4921 | ** eType value PK Record found? Value passed to xConflict |
| 4922 | ** ---------------------------------------------------------------- |
| 4923 | ** CHANGESET_DATA Yes CHANGESET_DATA |
| 4924 | ** CHANGESET_DATA No CHANGESET_NOTFOUND |
| 4925 | ** CHANGESET_CONFLICT Yes CHANGESET_CONFLICT |
| 4926 | ** CHANGESET_CONFLICT No CHANGESET_CONSTRAINT |
| 4927 | ** |
| 4928 | ** If pbReplace is not NULL, and a record with a matching PK is found, and |
| 4929 | ** the conflict handler function returns SQLITE_CHANGESET_REPLACE, *pbReplace |
| 4930 | ** is set to non-zero before returning SQLITE_OK. |
| 4931 | ** |
| 4932 | ** If the conflict handler returns SQLITE_CHANGESET_ABORT, SQLITE_ABORT is |
| 4933 | ** returned. Or, if the conflict handler returns an invalid value, |
| 4934 | ** SQLITE_MISUSE. If the conflict handler returns SQLITE_CHANGESET_OMIT, |
| 4935 | ** this function returns SQLITE_OK. |
| 4936 | */ |
| 4937 | static int sessionConflictHandler( |
| 4938 | int eType, /* Either CHANGESET_DATA or CONFLICT */ |
| 4939 | SessionApplyCtx *p, /* changeset_apply() context */ |
| 4940 | sqlite3_changeset_iter *pIter, /* Changeset iterator */ |
| 4941 | int(*xConflict)(void *, int, sqlite3_changeset_iter*), |
| 4942 | void *pCtx, /* First argument for conflict handler */ |
| 4943 | int *pbReplace /* OUT: Set to true if PK row is found */ |
| 4944 | ){ |
| 4945 | int res = SQLITE_CHANGESET_OMIT;/* Value returned by conflict handler */ |
| 4946 | int rc; |
| 4947 | int nCol; |
| 4948 | int op; |
| 4949 | const char *zDummy; |
| 4950 | |
| 4951 | sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0); |
| 4952 | |
| 4953 | assert( eType==SQLITE_CHANGESET_CONFLICT || eType==SQLITE_CHANGESET_DATA ); |
| 4954 | assert( SQLITE_CHANGESET_CONFLICT+1==SQLITE_CHANGESET_CONSTRAINT ); |
| 4955 | assert( SQLITE_CHANGESET_DATA+1==SQLITE_CHANGESET_NOTFOUND ); |
| 4956 | |
| 4957 | /* Bind the new.* PRIMARY KEY values to the SELECT statement. */ |
| 4958 | if( pbReplace ){ |
| 4959 | rc = sessionSeekToRow(pIter, p); |
| 4960 | }else{ |
| 4961 | rc = SQLITE_OK; |
| 4962 | } |
| 4963 | |
| 4964 | if( rc==SQLITE_ROW ){ |
| 4965 | /* There exists another row with the new.* primary key. */ |
| 4966 | if( 0==p->bIgnoreNoop |
| 4967 | || 0==sqlite3_column_int(p->pSelect, sqlite3_column_count(p->pSelect)-1) |
| 4968 | ){ |
| 4969 | pIter->pConflict = p->pSelect; |
| 4970 | res = xConflict(pCtx, eType, pIter); |
| 4971 | pIter->pConflict = 0; |
| 4972 | } |
| 4973 | rc = sqlite3_reset(p->pSelect); |
| 4974 | }else if( rc==SQLITE_OK ){ |
| 4975 | if( p->bDeferConstraints && eType==SQLITE_CHANGESET_CONFLICT ){ |
| 4976 | /* Instead of invoking the conflict handler, append the change blob |
| 4977 | ** to the SessionApplyCtx.constraints buffer. */ |
| 4978 | u8 *aBlob = &pIter->in.aData[pIter->in.iCurrent]; |
| 4979 | int nBlob = pIter->in.iNext - pIter->in.iCurrent; |
| 4980 | sessionAppendBlob(&p->constraints, aBlob, nBlob, &rc); |
| 4981 | return rc; |
| 4982 | }else if( p->bIgnoreNoop==0 || op!=SQLITE_DELETE |
| 4983 | || eType==SQLITE_CHANGESET_CONFLICT |
| 4984 | ){ |
| 4985 | /* No other row with the new.* primary key. */ |
| 4986 | res = xConflict(pCtx, eType+1, pIter); |
| 4987 | if( res==SQLITE_CHANGESET_REPLACE ) rc = SQLITE_MISUSE; |
| 4988 | } |
| 4989 | } |
| 4990 | |
| 4991 | if( rc==SQLITE_OK ){ |
| 4992 | switch( res ){ |
| 4993 | case SQLITE_CHANGESET_REPLACE: |
| 4994 | assert( pbReplace ); |
| 4995 | *pbReplace = 1; |
| 4996 | break; |
| 4997 | |
| 4998 | case SQLITE_CHANGESET_OMIT: |
| 4999 | break; |
| 5000 | |
| 5001 | case SQLITE_CHANGESET_ABORT: |
| 5002 | rc = SQLITE_ABORT; |
| 5003 | break; |
| 5004 | |
| 5005 | default: |
| 5006 | rc = SQLITE_MISUSE; |
| 5007 | break; |
| 5008 | } |
| 5009 | if( rc==SQLITE_OK ){ |
| 5010 | rc = sessionRebaseAdd(p, res, pIter); |
| 5011 | } |
| 5012 | } |
| 5013 | |
| 5014 | return rc; |
| 5015 | } |
| 5016 | |
| 5017 | /* |
| 5018 | ** Attempt to apply the change that the iterator passed as the first argument |
| 5019 | ** currently points to to the database. If a conflict is encountered, invoke |
| 5020 | ** the conflict handler callback. |
| 5021 | ** |
| 5022 | ** If argument pbRetry is NULL, then ignore any CHANGESET_DATA conflict. If |
| 5023 | ** one is encountered, update or delete the row with the matching primary key |
| 5024 | ** instead. Or, if pbRetry is not NULL and a CHANGESET_DATA conflict occurs, |
| 5025 | ** invoke the conflict handler. If it returns CHANGESET_REPLACE, set *pbRetry |
| 5026 | ** to true before returning. In this case the caller will invoke this function |
| 5027 | ** again, this time with pbRetry set to NULL. |
| 5028 | ** |
| 5029 | ** If argument pbReplace is NULL and a CHANGESET_CONFLICT conflict is |
| 5030 | ** encountered invoke the conflict handler with CHANGESET_CONSTRAINT instead. |
| 5031 | ** Or, if pbReplace is not NULL, invoke it with CHANGESET_CONFLICT. If such |
| 5032 | ** an invocation returns SQLITE_CHANGESET_REPLACE, set *pbReplace to true |
| 5033 | ** before retrying. In this case the caller attempts to remove the conflicting |
| 5034 | ** row before invoking this function again, this time with pbReplace set |
| 5035 | ** to NULL. |
| 5036 | ** |
| 5037 | ** If any conflict handler returns SQLITE_CHANGESET_ABORT, this function |
| 5038 | ** returns SQLITE_ABORT. Otherwise, if no error occurs, SQLITE_OK is |
| 5039 | ** returned. |
| 5040 | */ |
| 5041 | static int sessionApplyOneOp( |
| 5042 | sqlite3_changeset_iter *pIter, /* Changeset iterator */ |
| 5043 | SessionApplyCtx *p, /* changeset_apply() context */ |
| 5044 | int(*xConflict)(void *, int, sqlite3_changeset_iter *), |
| 5045 | void *pCtx, /* First argument for the conflict handler */ |
| 5046 | int *pbReplace, /* OUT: True to remove PK row and retry */ |
| 5047 | int *pbRetry /* OUT: True to retry. */ |
| 5048 | ){ |
| 5049 | const char *zDummy; |
| 5050 | int op; |
| 5051 | int nCol; |
| 5052 | int rc = SQLITE_OK; |
| 5053 | |
| 5054 | assert( p->pDelete && p->pInsert && p->pSelect ); |
| 5055 | assert( p->azCol && p->abPK ); |
| 5056 | assert( !pbReplace || *pbReplace==0 ); |
| 5057 | |
| 5058 | sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0); |
| 5059 | |
| 5060 | if( op==SQLITE_DELETE ){ |
| 5061 | |
| 5062 | /* Bind values to the DELETE statement. If conflict handling is required, |
| 5063 | ** bind values for all columns and set bound variable (nCol+1) to true. |
| 5064 | ** Or, if conflict handling is not required, bind just the PK column |
| 5065 | ** values and, if it exists, set (nCol+1) to false. Conflict handling |
| 5066 | ** is not required if: |
| 5067 | ** |
| 5068 | ** * this is a patchset, or |
| 5069 | ** * (pbRetry==0), or |
| 5070 | ** * all columns of the table are PK columns (in this case there is |
| 5071 | ** no (nCol+1) variable to bind to). |
| 5072 | */ |
| 5073 | u8 *abPK = (pIter->bPatchset ? p->abPK : 0); |
| 5074 | rc = sessionBindRow(pIter, sqlite3changeset_old, nCol, abPK, p->pDelete); |
| 5075 | if( rc==SQLITE_OK && sqlite3_bind_parameter_count(p->pDelete)>nCol ){ |
| 5076 | rc = sqlite3_bind_int(p->pDelete, nCol+1, (pbRetry==0 || abPK)); |
| 5077 | } |
| 5078 | if( rc!=SQLITE_OK ) return rc; |
| 5079 | |
| 5080 | sqlite3_step(p->pDelete); |
| 5081 | rc = sqlite3_reset(p->pDelete); |
| 5082 | if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){ |
| 5083 | rc = sessionConflictHandler( |
| 5084 | SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry |
| 5085 | ); |
| 5086 | }else if( (rc&0xff)==SQLITE_CONSTRAINT ){ |
| 5087 | rc = sessionConflictHandler( |
| 5088 | SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0 |
| 5089 | ); |
| 5090 | } |
| 5091 | |
| 5092 | }else if( op==SQLITE_UPDATE ){ |
| 5093 | int i; |
| 5094 | sqlite3_stmt *pUp = 0; |
| 5095 | int bPatchset = (pbRetry==0 || pIter->bPatchset); |
| 5096 | |
| 5097 | rc = sessionUpdateFind(pIter, p, bPatchset, &pUp); |
| 5098 | |
| 5099 | /* Bind values to the UPDATE statement. */ |
| 5100 | for(i=0; rc==SQLITE_OK && i<nCol; i++){ |
| 5101 | sqlite3_value *pOld = sessionChangesetOld(pIter, i); |
| 5102 | sqlite3_value *pNew = sessionChangesetNew(pIter, i); |
| 5103 | if( pOld && (p->abPK[i] || bPatchset==0) ){ |
| 5104 | rc = sessionBindValue(pUp, i*2+2, pOld); |
| 5105 | } |
| 5106 | if( rc==SQLITE_OK && pNew ){ |
| 5107 | rc = sessionBindValue(pUp, i*2+1, pNew); |
| 5108 | } |
| 5109 | } |
| 5110 | if( rc!=SQLITE_OK ) return rc; |
| 5111 | |
| 5112 | /* Attempt the UPDATE. In the case of a NOTFOUND or DATA conflict, |
| 5113 | ** the result will be SQLITE_OK with 0 rows modified. */ |
| 5114 | sqlite3_step(pUp); |
| 5115 | rc = sqlite3_reset(pUp); |
| 5116 | |
| 5117 | if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){ |
| 5118 | /* A NOTFOUND or DATA error. Search the table to see if it contains |
| 5119 | ** a row with a matching primary key. If so, this is a DATA conflict. |
| 5120 | ** Otherwise, if there is no primary key match, it is a NOTFOUND. */ |
| 5121 | |
| 5122 | rc = sessionConflictHandler( |
| 5123 | SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry |
| 5124 | ); |
| 5125 | |
| 5126 | }else if( (rc&0xff)==SQLITE_CONSTRAINT ){ |
| 5127 | /* This is always a CONSTRAINT conflict. */ |
| 5128 | rc = sessionConflictHandler( |
| 5129 | SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0 |
| 5130 | ); |
| 5131 | } |
| 5132 | |
| 5133 | }else{ |
| 5134 | assert( op==SQLITE_INSERT ); |
| 5135 | if( p->bStat1 ){ |
| 5136 | /* Check if there is a conflicting row. For sqlite_stat1, this needs |
| 5137 | ** to be done using a SELECT, as there is no PRIMARY KEY in the |
| 5138 | ** database schema to throw an exception if a duplicate is inserted. */ |
| 5139 | rc = sessionSeekToRow(pIter, p); |
| 5140 | if( rc==SQLITE_ROW ){ |
| 5141 | rc = SQLITE_CONSTRAINT; |
| 5142 | sqlite3_reset(p->pSelect); |
| 5143 | } |
| 5144 | } |
| 5145 | |
| 5146 | if( rc==SQLITE_OK ){ |
| 5147 | rc = sessionBindRow(pIter, sqlite3changeset_new, nCol, 0, p->pInsert); |
| 5148 | if( rc!=SQLITE_OK ) return rc; |
| 5149 | |
| 5150 | sqlite3_step(p->pInsert); |
| 5151 | rc = sqlite3_reset(p->pInsert); |
| 5152 | } |
| 5153 | |
| 5154 | if( (rc&0xff)==SQLITE_CONSTRAINT ){ |
| 5155 | rc = sessionConflictHandler( |
| 5156 | SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, pbReplace |
| 5157 | ); |
| 5158 | } |
| 5159 | } |
| 5160 | |
| 5161 | return rc; |
| 5162 | } |
| 5163 | |
| 5164 | /* |
| 5165 | ** Attempt to apply the change that the iterator passed as the first argument |
| 5166 | ** currently points to to the database. If a conflict is encountered, invoke |
| 5167 | ** the conflict handler callback. |
| 5168 | ** |
| 5169 | ** The difference between this function and sessionApplyOne() is that this |
| 5170 | ** function handles the case where the conflict-handler is invoked and |
| 5171 | ** returns SQLITE_CHANGESET_REPLACE - indicating that the change should be |
| 5172 | ** retried in some manner. |
| 5173 | */ |
| 5174 | static int sessionApplyOneWithRetry( |
| 5175 | sqlite3 *db, /* Apply change to "main" db of this handle */ |
| 5176 | sqlite3_changeset_iter *pIter, /* Changeset iterator to read change from */ |
| 5177 | SessionApplyCtx *pApply, /* Apply context */ |
| 5178 | int(*xConflict)(void*, int, sqlite3_changeset_iter*), |
| 5179 | void *pCtx /* First argument passed to xConflict */ |
| 5180 | ){ |
| 5181 | int bReplace = 0; |
| 5182 | int bRetry = 0; |
| 5183 | int rc; |
| 5184 | |
| 5185 | rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, &bReplace, &bRetry); |
| 5186 | if( rc==SQLITE_OK ){ |
| 5187 | /* If the bRetry flag is set, the change has not been applied due to an |
| 5188 | ** SQLITE_CHANGESET_DATA problem (i.e. this is an UPDATE or DELETE and |
| 5189 | ** a row with the correct PK is present in the db, but one or more other |
| 5190 | ** fields do not contain the expected values) and the conflict handler |
| 5191 | ** returned SQLITE_CHANGESET_REPLACE. In this case retry the operation, |
| 5192 | ** but pass NULL as the final argument so that sessionApplyOneOp() ignores |
| 5193 | ** the SQLITE_CHANGESET_DATA problem. */ |
| 5194 | if( bRetry ){ |
| 5195 | assert( pIter->op==SQLITE_UPDATE || pIter->op==SQLITE_DELETE ); |
| 5196 | rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0); |
| 5197 | } |
| 5198 | |
| 5199 | /* If the bReplace flag is set, the change is an INSERT that has not |
| 5200 | ** been performed because the database already contains a row with the |
| 5201 | ** specified primary key and the conflict handler returned |
| 5202 | ** SQLITE_CHANGESET_REPLACE. In this case remove the conflicting row |
| 5203 | ** before reattempting the INSERT. */ |
| 5204 | else if( bReplace ){ |
| 5205 | assert( pIter->op==SQLITE_INSERT ); |
| 5206 | rc = sqlite3_exec(db, "SAVEPOINT replace_op", 0, 0, 0); |
| 5207 | if( rc==SQLITE_OK ){ |
| 5208 | int rc2; |
| 5209 | rc = sessionBindRow(pIter, |
| 5210 | sqlite3changeset_new, pApply->nCol, pApply->abPK, pApply->pDelete); |
| 5211 | sqlite3_bind_int(pApply->pDelete, pApply->nCol+1, 1); |
| 5212 | if( rc==SQLITE_OK ){ |
| 5213 | sqlite3_step(pApply->pDelete); |
| 5214 | rc = sqlite3_reset(pApply->pDelete); |
| 5215 | } |
| 5216 | if( rc==SQLITE_OK ){ |
| 5217 | rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0); |
| 5218 | } |
| 5219 | if( rc!=SQLITE_OK ){ |
| 5220 | sqlite3_exec(db, "ROLLBACK TO replace_op", 0, 0, 0); |
| 5221 | } |
| 5222 | rc2 = sqlite3_exec(db, "RELEASE replace_op", 0, 0, 0); |
| 5223 | if( rc==SQLITE_OK ) rc = rc2; |
| 5224 | } |
| 5225 | } |
| 5226 | } |
| 5227 | |
| 5228 | return rc; |
| 5229 | } |
| 5230 | |
| 5231 | /* |
| 5232 | ** Create an iterator to iterate through the retry buffer pRetry. |
| 5233 | */ |
| 5234 | static int sessionRetryIterInit( |
| 5235 | SessionBuffer *pRetry, /* Buffer to iterate through */ |
| 5236 | int bPatchset, /* True for patchset, false for changeset */ |
| 5237 | const char *zTab, /* Table name */ |
| 5238 | SessionApplyCtx *pApply, /* Session apply context */ |
| 5239 | sqlite3_changeset_iter **ppIter /* OUT: New iterator */ |
| 5240 | ){ |
| 5241 | sqlite3_changeset_iter *pRet = 0; |
| 5242 | int rc = SQLITE_OK; |
| 5243 | |
| 5244 | rc = sessionChangesetStart( |
| 5245 | &pRet, 0, 0, pRetry->nBuf, pRetry->aBuf, pApply->bInvertConstraints, 1 |
| 5246 | ); |
| 5247 | if( rc==SQLITE_OK ){ |
| 5248 | size_t nByte = 2*pApply->nCol*sizeof(sqlite3_value*); |
| 5249 | pRet->bPatchset = bPatchset; |
| 5250 | pRet->zTab = (char*)zTab; |
| 5251 | pRet->nCol = pApply->nCol; |
| 5252 | pRet->abPK = pApply->abPK; |
| 5253 | sessionBufferGrow(&pRet->tblhdr, nByte, &rc); |
| 5254 | pRet->apValue = (sqlite3_value**)pRet->tblhdr.aBuf; |
| 5255 | if( rc==SQLITE_OK ){ |
| 5256 | memset(pRet->apValue, 0, nByte); |
| 5257 | }else{ |
| 5258 | sqlite3changeset_finalize(pRet); |
| 5259 | pRet = 0; |
| 5260 | } |
| 5261 | } |
| 5262 | |
| 5263 | *ppIter = pRet; |
| 5264 | return rc; |
| 5265 | } |
| 5266 | |
| 5267 | /* |
| 5268 | ** Attempt to apply all the changes in retry buffer pRetry to the database. |
| 5269 | ** Except, if parameter iSkip is greater than or equal to 0, skip change |
| 5270 | ** iSkip. |
| 5271 | */ |
| 5272 | static int sessionApplyRetryBuffer( |
| 5273 | SessionBuffer *pRetry, /* Buffer to apply changes from */ |
| 5274 | int iSkip, /* If >=0, index of change to omit */ |
| 5275 | sqlite3 *db, /* Database handle */ |
| 5276 | int bPatchset, /* True for patchset, false for changeset */ |
| 5277 | const char *zTab, /* Name of table to write to */ |
| 5278 | SessionApplyCtx *pApply, /* Apply context */ |
| 5279 | int(*xConflict)(void*, int, sqlite3_changeset_iter*), |
| 5280 | void *pCtx /* First argument passed to xConflict */ |
| 5281 | ){ |
| 5282 | int rc = SQLITE_OK; |
| 5283 | int rc2 = SQLITE_OK; |
| 5284 | int ii = 0; |
| 5285 | sqlite3_changeset_iter *pIter = 0; |
| 5286 | |
| 5287 | assert( pApply->constraints.nBuf==0 ); |
| 5288 | |
| 5289 | rc = sessionRetryIterInit(pRetry, bPatchset, zTab, pApply, &pIter); |
| 5290 | |
| 5291 | for(ii=0; rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter); ii++){ |
| 5292 | if( ii!=iSkip ){ |
| 5293 | rc = sessionApplyOneWithRetry(db, pIter, pApply, xConflict, pCtx); |
| 5294 | } |
| 5295 | } |
| 5296 | |
| 5297 | rc2 = sqlite3changeset_finalize(pIter); |
| 5298 | if( rc==SQLITE_OK ) rc = rc2; |
| 5299 | assert( pApply->bDeferConstraints || pApply->constraints.nBuf==0 ); |
| 5300 | |
| 5301 | return rc; |
| 5302 | } |
| 5303 | |
| 5304 | /* |
| 5305 | ** Buffer aUnique[] is pApply->nCol entries in size. This function sets |
| 5306 | ** aUnique[i] to true if column i of table zTab in the "main" database |
| 5307 | ** of db is part of at least one UNIQUE constraint, or to false otherwise. |
| 5308 | ** |
| 5309 | ** If the table has a unique index on an expression, or a partial unique |
| 5310 | ** index, all entries of aUnique[] are set to true. |
| 5311 | ** |
| 5312 | ** SQLITE_OK is returned if successful, or an SQLite error code otherwise. |
| 5313 | */ |
| 5314 | static int sessionUniqueColumns( |
| 5315 | sqlite3 *db, /* Database handle */ |
| 5316 | const char *zTab, /* Table name */ |
| 5317 | SessionApplyCtx *pApply, /* Apply context */ |
| 5318 | u8 *aUnique /* OUT: Array of pApply->nCol flags */ |
| 5319 | ){ |
| 5320 | sqlite3_stmt *pList = 0; /* PRAGMA index_list */ |
| 5321 | int rc = SQLITE_OK; |
| 5322 | |
| 5323 | /* Ordinary PRAGMA statements are used here instead of the equivalent |
| 5324 | ** table-valued functions (pragma_index_list() etc.) so that this works |
| 5325 | ** in builds with SQLITE_OMIT_VIRTUALTABLE defined. */ |
| 5326 | memset(aUnique, 0, pApply->nCol); |
| 5327 | sessionPrepareMprintf(&rc, db, &pList, &pApply->zErr, |
| 5328 | "PRAGMA main.index_list(%Q)", zTab |
| 5329 | ); |
| 5330 | while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pList) ){ |
| 5331 | /* Columns of PRAGMA index_list are (seq, name, unique, origin, partial) */ |
| 5332 | const char *zIdx = (const char*)sqlite3_column_text(pList, 1); |
| 5333 | int bUnique = sqlite3_column_int(pList, 2); |
| 5334 | int bPartial = sqlite3_column_int(pList, 4); |
| 5335 | sqlite3_stmt *pInfo = 0; /* PRAGMA index_xinfo */ |
| 5336 | |
| 5337 | if( bUnique==0 ) continue; |
| 5338 | sessionPrepareMprintf(&rc, db, &pInfo, &pApply->zErr, |
| 5339 | "PRAGMA main.index_xinfo(%Q)", zIdx |
| 5340 | ); |
| 5341 | while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pInfo) ){ |
| 5342 | /* Columns of PRAGMA index_xinfo are (seqno, cid, name, desc, coll, key)*/ |
| 5343 | int iCid = sqlite3_column_int(pInfo, 1); |
| 5344 | const char *zCol = (const char*)sqlite3_column_text(pInfo, 2); |
| 5345 | int bKey = sqlite3_column_int(pInfo, 5); |
| 5346 | int ii; |
| 5347 | if( bKey==0 ) continue; |
| 5348 | for(ii=0; ii<pApply->nCol; ii++){ |
| 5349 | if( bPartial |
| 5350 | || iCid==-2 |
| 5351 | || (zCol && 0==sqlite3_stricmp(zCol, pApply->azCol[ii])) |
| 5352 | ){ |
| 5353 | aUnique[ii] = 1; |
| 5354 | } |
| 5355 | } |
| 5356 | } |
| 5357 | if( rc==SQLITE_OK ){ |
| 5358 | rc = sqlite3_finalize(pInfo); |
| 5359 | }else{ |
| 5360 | sqlite3_finalize(pInfo); |
| 5361 | } |
| 5362 | } |
| 5363 | if( rc==SQLITE_OK ){ |
| 5364 | rc = sqlite3_finalize(pList); |
| 5365 | }else{ |
| 5366 | sqlite3_finalize(pList); |
| 5367 | } |
| 5368 | |
| 5369 | return rc; |
| 5370 | } |
| 5371 | |
| 5372 | /* |
| 5373 | ** Iterator pUp points to an UPDATE change. This function updates the |
| 5374 | ** affected row to set each column modified by the UPDATE change that |
| 5375 | ** is also part of at least one UNIQUE constraint to a "random" value, |
| 5376 | ** and creates another UPDATE statement that may be used to later set |
| 5377 | ** all columns modified by pUp to the actual values required by pUp. |
| 5378 | ** |
| 5379 | ** Each random value has the same type as the final value required by |
| 5380 | ** pUp for the same column: |
| 5381 | ** |
| 5382 | ** NULL -> NULL |
| 5383 | ** INTEGER -> random() |
| 5384 | ** REAL -> random() |
| 5385 | ** TEXT -> CAST(random() AS TEXT) |
| 5386 | ** BLOB -> unhex(hex(random())) |
| 5387 | ** |
| 5388 | ** If none of the columns modified by pUp are part of a UNIQUE constraint, |
| 5389 | ** then SQLITE_CONSTRAINT is returned. |
| 5390 | ** |
| 5391 | ** If successful, SQLITE_OK is returned and output variable (*ppUpdate) |
| 5392 | ** is left pointing to a prepared UPDATE statement. It is the responsibility |
| 5393 | ** of the caller to eventually free this statement using sqlite3_finalize(). |
| 5394 | ** Or, if an error occurs, an SQLite error code is returned and (*ppUpdate) |
| 5395 | ** set to NULL. pApply->zErr may be set to an error message in this case. |
| 5396 | ** Except - it is guaranteed that pApply->zErr is not set if SQLITE_CONSTRAINT |
| 5397 | ** is returned. |
| 5398 | */ |
| 5399 | static int sessionUpdateToUpdate( |
| 5400 | sqlite3 *db, /* Database to write to */ |
| 5401 | const char *zTab, /* Table name */ |
| 5402 | SessionApplyCtx *pApply, /* Apply context */ |
| 5403 | sqlite3_changeset_iter *pUp, /* Iterator pointing to UPDATE change */ |
| 5404 | sqlite3_stmt **ppUpdate /* OUT: UPDATE statement */ |
| 5405 | ){ |
| 5406 | sqlite3_stmt *pRet = 0; /* UPDATE to set the final values */ |
| 5407 | sqlite3_stmt *pRand = 0; /* UPDATE to set random values */ |
| 5408 | int rc = SQLITE_OK; |
| 5409 | u8 *aUnique = 0; /* aUnique[i] true if col i is UNIQUE */ |
| 5410 | SessionBuffer randset = {0, 0, 0}; |
| 5411 | SessionBuffer upset = {0, 0, 0}; |
| 5412 | SessionBuffer where = {0, 0, 0}; |
| 5413 | int ii; |
| 5414 | |
| 5415 | aUnique = (u8*)sqlite3_malloc64(pApply->nCol); |
| 5416 | if( aUnique==0 ){ |
| 5417 | rc = SQLITE_NOMEM; |
| 5418 | }else{ |
| 5419 | rc = sessionUniqueColumns(db, zTab, pApply, aUnique); |
| 5420 | } |
| 5421 | |
| 5422 | /* Assuming a table structure like this: |
| 5423 | ** |
| 5424 | ** CREATE TABLE x(a, b UNIQUE, c, d UNIQUE, e, PRIMARY KEY(a, c)); |
| 5425 | ** |
| 5426 | ** and an UPDATE change that sets column b to an integer, column d to |
| 5427 | ** a text value and column e to any value, the two statements prepared |
| 5428 | ** are: |
| 5429 | ** |
| 5430 | ** UPDATE main.x SET b = random(), d = CAST(random() AS TEXT) |
| 5431 | ** WHERE a IS ?1 AND c IS ?3 |
| 5432 | ** UPDATE main.x SET b = ?2, d = ?4, e = ?5 WHERE a IS ?1 AND c IS ?3 |
| 5433 | */ |
| 5434 | for(ii=0; rc==SQLITE_OK && ii<pApply->nCol; ii++){ |
| 5435 | sqlite3_value *pNew = 0; |
| 5436 | if( pApply->abPK[ii] ){ |
| 5437 | if( where.nBuf>0 ) sessionAppendStr(&where, " AND ", &rc); |
| 5438 | sessionAppendIdent(&where, pApply->azCol[ii], &rc); |
| 5439 | sessionAppendPrintf(&where, &rc, " IS ?%d", ii+1); |
| 5440 | }else if( (pNew = sessionChangesetNew(pUp, ii))!=0 ){ |
| 5441 | if( aUnique[ii] ){ |
| 5442 | const char *zRand = 0; |
| 5443 | switch( sqlite3_value_type(pNew) ){ |
| 5444 | case SQLITE_NULL: zRand = "NULL"; break; |
| 5445 | case SQLITE_TEXT: zRand = "CAST(random() AS TEXT)"; break; |
| 5446 | case SQLITE_BLOB: zRand = "unhex(hex(random()))"; break; |
| 5447 | default: zRand = "random()"; break; |
| 5448 | } |
| 5449 | if( randset.nBuf>0 ) sessionAppendStr(&randset, ", ", &rc); |
| 5450 | sessionAppendIdent(&randset, pApply->azCol[ii], &rc); |
| 5451 | sessionAppendStr(&randset, " = ", &rc); |
| 5452 | sessionAppendStr(&randset, zRand, &rc); |
| 5453 | } |
| 5454 | if( upset.nBuf>0 ) sessionAppendStr(&upset, ", ", &rc); |
| 5455 | sessionAppendIdent(&upset, pApply->azCol[ii], &rc); |
| 5456 | sessionAppendPrintf(&upset, &rc, " = ?%d", ii+1); |
| 5457 | } |
| 5458 | } |
| 5459 | |
| 5460 | if( rc==SQLITE_OK && randset.nBuf==0 ){ |
| 5461 | /* None of the columns modified by this change are part of a UNIQUE |
| 5462 | ** constraint. So setting them to random values cannot help resolve |
| 5463 | ** a constraint conflict. Report this as a constraint failure. */ |
| 5464 | rc = SQLITE_CONSTRAINT; |
| 5465 | } |
| 5466 | |
| 5467 | sessionPrepareMprintf(&rc, db, &pRand, &pApply->zErr, |
| 5468 | "UPDATE main.\"%w\" SET %s WHERE %s", |
| 5469 | zTab, (char*)randset.aBuf, (char*)where.aBuf |
| 5470 | ); |
| 5471 | sessionPrepareMprintf(&rc, db, &pRet, &pApply->zErr, |
| 5472 | "UPDATE main.\"%w\" SET %s WHERE %s", |
| 5473 | zTab, (char*)upset.aBuf, (char*)where.aBuf |
| 5474 | ); |
| 5475 | |
| 5476 | /* Bind the PK values to both statements, and the new.* values to pRet. */ |
| 5477 | if( rc==SQLITE_OK ){ |
| 5478 | rc = sessionBindRow( |
| 5479 | pUp, sqlite3changeset_old, pApply->nCol, pApply->abPK, pRand |
| 5480 | ); |
| 5481 | } |
| 5482 | if( rc==SQLITE_OK ){ |
| 5483 | rc = sessionBindRow( |
| 5484 | pUp, sqlite3changeset_old, pApply->nCol, pApply->abPK, pRet |
| 5485 | ); |
| 5486 | } |
| 5487 | for(ii=0; rc==SQLITE_OK && ii<pApply->nCol; ii++){ |
| 5488 | sqlite3_value *pNew = sessionChangesetNew(pUp, ii); |
| 5489 | if( pApply->abPK[ii]==0 && pNew ){ |
| 5490 | rc = sessionBindValue(pRet, ii+1, pNew); |
| 5491 | } |
| 5492 | } |
| 5493 | |
| 5494 | /* Evaluate the statement to set each modified column of the row to a random |
| 5495 | ** value. If this fails with a constraint error, SQLITE_CONSTRAINT is |
| 5496 | ** returned to the caller, but pApply->zErr is not set. */ |
| 5497 | if( rc==SQLITE_OK ){ |
| 5498 | sqlite3_step(pRand); |
| 5499 | rc = sqlite3_reset(pRand); |
| 5500 | } |
| 5501 | sqlite3_finalize(pRand); |
| 5502 | |
| 5503 | if( rc!=SQLITE_OK ){ |
| 5504 | sqlite3_finalize(pRet); |
| 5505 | pRet = 0; |
| 5506 | } |
| 5507 | *ppUpdate = pRet; |
| 5508 | |
| 5509 | sqlite3_free(aUnique); |
| 5510 | sqlite3_free(randset.aBuf); |
| 5511 | sqlite3_free(upset.aBuf); |
| 5512 | sqlite3_free(where.aBuf); |
| 5513 | |
| 5514 | return rc; |
| 5515 | } |
| 5516 | |
| 5517 | /* |
| 5518 | ** Retry the changes accumulated in the pApply->constraints buffer. The |
| 5519 | ** pApply->constraints buffer contains all changes to table zTab that |
| 5520 | ** could not be applied due to SQLITE_CONSTRAINT errors. This function |
| 5521 | ** attempts to apply them as follows: |
| 5522 | ** |
| 5523 | ** 1) It runs through the buffer and attempts to retry each change, |
| 5524 | ** removing any that are successfully applied from the buffer. This |
| 5525 | ** is repeated until no further progress can be made. |
| 5526 | ** |
| 5527 | ** 2) For each UPDATE change in the buffer, try the following in a |
| 5528 | ** savepoint transaction: |
| 5529 | ** |
| 5530 | ** a) UPDATE the affected row, setting each column modified by the |
| 5531 | ** UPDATE change to a random value, |
| 5532 | ** b) Attempt step (1) with remaining changes, |
| 5533 | ** c) Attempt to UPDATE the affected row again, this time setting |
| 5534 | ** each modified column to the value required by the UPDATE change. |
| 5535 | ** |
| 5536 | ** If both (a) and (c) succeed, the savepoint is committed and all |
| 5537 | ** successfully applied changes are removed from the buffer. Step (2) |
| 5538 | ** is then repeated. Otherwise, if either (a) or (c) fails with |
| 5539 | ** SQLITE_CONSTRAINT, the savepoint is rolled back and the next UPDATE |
| 5540 | ** in the buffer is tried. |
| 5541 | ** |
| 5542 | ** 3) Once step (2) has been attempted for each UPDATE in the change, |
| 5543 | ** a final attempt is made to apply each remaining change. This time, |
| 5544 | ** if an SQLITE_CONSTRAINT error is encountered, the conflict handler |
| 5545 | ** is invoked and the user has to decide whether to omit the change |
| 5546 | ** or rollback the entire _apply() operation. |
| 5547 | */ |
| 5548 | static int sessionRetryConstraints( |
| 5549 | sqlite3 *db, |
| 5550 | int bPatchset, |
| 5551 | const char *zTab, |
| 5552 | SessionApplyCtx *pApply, |
| 5553 | int(*xConflict)(void*, int, sqlite3_changeset_iter*), |
| 5554 | void *pCtx /* First argument passed to xConflict */ |
| 5555 | ){ |
| 5556 | int rc = SQLITE_OK; |
| 5557 | int iUpdate = 0; |
| 5558 | |
| 5559 | /* Step (1) */ |
| 5560 | while( pApply->constraints.nBuf ){ |
| 5561 | SessionBuffer cons = pApply->constraints; |
| 5562 | memset(&pApply->constraints, 0, sizeof(SessionBuffer)); |
| 5563 | |
| 5564 | rc = sessionApplyRetryBuffer( |
| 5565 | &cons, -1, db, bPatchset, zTab, pApply, xConflict, pCtx |
| 5566 | ); |
| 5567 | |
| 5568 | sqlite3_free(cons.aBuf); |
| 5569 | if( rc!=SQLITE_OK ) break; |
| 5570 | |
| 5571 | /* If no progress has been made this round, break out of the loop. */ |
| 5572 | if( pApply->constraints.nBuf>=cons.nBuf ) break; |
| 5573 | } |
| 5574 | |
| 5575 | /* Step (2) */ |
| 5576 | while( rc==SQLITE_OK && pApply->constraints.nBuf && !pApply->bNoUpdateLoop ){ |
| 5577 | SessionBuffer cons = {0, 0, 0}; |
| 5578 | sqlite3_changeset_iter *pUp = 0; |
| 5579 | sqlite3_stmt *pUpdate = 0; |
| 5580 | int iSkip = 0; |
| 5581 | int bConstraint = 0; /* True if an SQLITE_CONSTRAINT occurs */ |
| 5582 | |
| 5583 | rc = sessionRetryIterInit( |
| 5584 | &pApply->constraints, bPatchset, zTab, pApply, &pUp |
| 5585 | ); |
| 5586 | if( rc==SQLITE_OK ){ |
| 5587 | int iThis = -1; |
| 5588 | while( SQLITE_ROW==sqlite3changeset_next(pUp) ){ |
| 5589 | if( pUp->op==SQLITE_UPDATE ) iThis++; |
| 5590 | if( iThis==iUpdate ) break; |
| 5591 | iSkip++; |
| 5592 | } |
| 5593 | if( iThis==iUpdate ){ |
| 5594 | rc = sqlite3_exec(db, "SAVEPOINT update_op", 0, 0, 0); |
| 5595 | if( rc==SQLITE_OK ){ |
| 5596 | rc = sessionUpdateToUpdate(db, zTab, pApply, pUp, &pUpdate); |
| 5597 | if( (rc&0xff)==SQLITE_CONSTRAINT ){ |
| 5598 | bConstraint = 1; |
| 5599 | rc = SQLITE_OK; |
| 5600 | } |
| 5601 | } |
| 5602 | } |
| 5603 | sqlite3changeset_finalize(pUp); |
| 5604 | if( iThis!=iUpdate ) break; |
| 5605 | } |
| 5606 | |
| 5607 | if( rc==SQLITE_OK ){ |
| 5608 | cons = pApply->constraints; |
| 5609 | if( bConstraint ){ |
| 5610 | memset(&pApply->constraints, 0, sizeof(SessionBuffer)); |
| 5611 | } |
| 5612 | |
| 5613 | while( rc==SQLITE_OK && pApply->constraints.nBuf>0 ){ |
| 5614 | SessionBuffer app = pApply->constraints; |
| 5615 | memset(&pApply->constraints, 0, sizeof(SessionBuffer)); |
| 5616 | rc = sessionApplyRetryBuffer( |
| 5617 | &app, iSkip, db, bPatchset, zTab, pApply, xConflict, pCtx |
| 5618 | ); |
| 5619 | if( app.aBuf!=cons.aBuf ){ |
| 5620 | sqlite3_free(app.aBuf); |
| 5621 | } |
| 5622 | if( pApply->constraints.nBuf>=app.nBuf ){ |
| 5623 | break; |
| 5624 | } |
| 5625 | iSkip = -1; |
| 5626 | } |
| 5627 | } |
| 5628 | |
| 5629 | iUpdate++; |
| 5630 | if( rc==SQLITE_OK ){ |
| 5631 | if( bConstraint==0 ){ |
| 5632 | sqlite3_step(pUpdate); |
| 5633 | rc = sqlite3_finalize(pUpdate); |
| 5634 | pUpdate = 0; |
| 5635 | if( (rc&0xff)==SQLITE_CONSTRAINT ){ |
| 5636 | bConstraint = 1; |
| 5637 | rc = SQLITE_OK; |
| 5638 | } |
| 5639 | } |
| 5640 | if( bConstraint ){ |
| 5641 | rc = sqlite3_exec(db, "ROLLBACK TO update_op", 0, 0, 0); |
| 5642 | sqlite3_free(pApply->constraints.aBuf); |
| 5643 | pApply->constraints = cons; |
| 5644 | memset(&cons, 0, sizeof(cons)); |
| 5645 | }else if( rc==SQLITE_OK ){ |
| 5646 | iUpdate = 0; |
| 5647 | } |
| 5648 | if( rc==SQLITE_OK ){ |
| 5649 | rc = sqlite3_exec(db, "RELEASE update_op", 0, 0, 0); |
| 5650 | } |
| 5651 | } |
| 5652 | sqlite3_finalize(pUpdate); |
| 5653 | |
| 5654 | sqlite3_free(cons.aBuf); |
| 5655 | } |
| 5656 | |
| 5657 | /* Step (3) */ |
| 5658 | if( rc==SQLITE_OK && pApply->constraints.nBuf ){ |
| 5659 | SessionBuffer cons = pApply->constraints; |
| 5660 | memset(&pApply->constraints, 0, sizeof(SessionBuffer)); |
| 5661 | pApply->bDeferConstraints = 0; |
| 5662 | rc = sessionApplyRetryBuffer( |
| 5663 | &cons, -1, db, bPatchset, zTab, pApply, xConflict, pCtx |
| 5664 | ); |
| 5665 | sqlite3_free(cons.aBuf); |
| 5666 | } |
| 5667 | |
| 5668 | return rc; |
| 5669 | } |
| 5670 | |
| 5671 | /* |
| 5672 | ** Argument pIter is a changeset iterator that has been initialized, but |
| 5673 | ** not yet passed to sqlite3changeset_next(). This function applies the |
| 5674 | ** changeset to the main database attached to handle "db". The supplied |
| 5675 | ** conflict handler callback is invoked to resolve any conflicts encountered |
| 5676 | ** while applying the change. |
| 5677 | */ |
| 5678 | static int sessionChangesetApply( |
| 5679 | sqlite3 *db, /* Apply change to "main" db of this handle */ |
| 5680 | sqlite3_changeset_iter *pIter, /* Changeset to apply */ |
| 5681 | int(*xFilter)( |
| 5682 | void *pCtx, /* Copy of sixth arg to _apply() */ |
| 5683 | const char *zTab /* Table name */ |
| 5684 | ), |
| 5685 | int(*xFilterIter)( |
| 5686 | void *pCtx, /* Copy of sixth arg to _apply() */ |
| 5687 | sqlite3_changeset_iter *p |
| 5688 | ), |
| 5689 | int(*xConflict)( |
| 5690 | void *pCtx, /* Copy of fifth arg to _apply() */ |
| 5691 | int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ |
| 5692 | sqlite3_changeset_iter *p /* Handle describing change and conflict */ |
| 5693 | ), |
| 5694 | void *pCtx, /* First argument passed to xConflict */ |
| 5695 | void **ppRebase, int *pnRebase, /* OUT: Rebase information */ |
| 5696 | int flags /* SESSION_APPLY_XXX flags */ |
| 5697 | ){ |
| 5698 | int schemaMismatch = 0; |
| 5699 | int rc = SQLITE_OK; /* Return code */ |
| 5700 | const char *zTab = 0; /* Name of current table */ |
| 5701 | SessionApplyCtx sApply; /* changeset_apply() context object */ |
| 5702 | int bPatchset; |
| 5703 | u64 savedFlag = db->flags & SQLITE_FkNoAction; |
| 5704 | int bNew = 0; /* True for first entry of new table */ |
| 5705 | |
| 5706 | assert( xConflict!=0 ); |
| 5707 | |
| 5708 | sqlite3_mutex_enter(sqlite3_db_mutex(db)); |
| 5709 | if( flags & SQLITE_CHANGESETAPPLY_FKNOACTION ){ |
| 5710 | db->flags |= ((u64)SQLITE_FkNoAction); |
| 5711 | db->aDb[0].pSchema->schema_cookie -= 32; |
| 5712 | } |
| 5713 | |
| 5714 | pIter->in.bNoDiscard = 1; |
| 5715 | memset(&sApply, 0, sizeof(sApply)); |
| 5716 | sApply.bRebase = (ppRebase && pnRebase); |
| 5717 | sApply.bInvertConstraints = !!(flags & SQLITE_CHANGESETAPPLY_INVERT); |
| 5718 | sApply.bIgnoreNoop = !!(flags & SQLITE_CHANGESETAPPLY_IGNORENOOP); |
| 5719 | sApply.bNoUpdateLoop = !!(flags & SQLITE_CHANGESETAPPLY_NOUPDATELOOP); |
| 5720 | if( (flags & SQLITE_CHANGESETAPPLY_NOSAVEPOINT)==0 ){ |
| 5721 | rc = sqlite3_exec(db, "SAVEPOINT changeset_apply", 0, 0, 0); |
| 5722 | } |
| 5723 | if( rc==SQLITE_OK ){ |
| 5724 | rc = sqlite3_exec(db, "PRAGMA defer_foreign_keys = 1", 0, 0, 0); |
| 5725 | } |
| 5726 | while( rc==SQLITE_OK && SQLITE_ROW==sessionChangesetNext(pIter, 0, 0,&bNew) ){ |
| 5727 | int nCol; |
| 5728 | int op; |
| 5729 | const char *zNew; |
| 5730 | |
| 5731 | sqlite3changeset_op(pIter, &zNew, &nCol, &op, 0); |
| 5732 | |
| 5733 | if( bNew ){ |
| 5734 | u8 *abPK; |
| 5735 | bNew = 0; |
| 5736 | |
| 5737 | rc = sessionRetryConstraints( |
| 5738 | db, pIter->bPatchset, zTab, &sApply, xConflict, pCtx |
| 5739 | ); |
| 5740 | if( rc!=SQLITE_OK ) break; |
| 5741 | |
| 5742 | sessionUpdateFree(&sApply); |
| 5743 | sqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */ |
| 5744 | sqlite3_finalize(sApply.pDelete); |
| 5745 | sqlite3_finalize(sApply.pInsert); |
| 5746 | sqlite3_finalize(sApply.pSelect); |
| 5747 | sApply.db = db; |
| 5748 | sApply.pDelete = 0; |
| 5749 | sApply.pInsert = 0; |
| 5750 | sApply.pSelect = 0; |
| 5751 | sApply.nCol = 0; |
| 5752 | sApply.azCol = 0; |
| 5753 | sApply.abPK = 0; |
| 5754 | sApply.bStat1 = 0; |
| 5755 | sApply.bDeferConstraints = 1; |
| 5756 | sApply.bRebaseStarted = 0; |
| 5757 | sApply.bRowid = 0; |
| 5758 | memset(&sApply.constraints, 0, sizeof(SessionBuffer)); |
| 5759 | |
| 5760 | /* If an xFilter() callback was specified, invoke it now. If the |
| 5761 | ** xFilter callback returns zero, skip this table. If it returns |
| 5762 | ** non-zero, proceed. */ |
| 5763 | schemaMismatch = (xFilter && (0==xFilter(pCtx, zNew))); |
| 5764 | if( schemaMismatch ){ |
| 5765 | zTab = sqlite3_mprintf("%s", zNew); |
| 5766 | if( zTab==0 ){ |
| 5767 | rc = SQLITE_NOMEM; |
| 5768 | break; |
| 5769 | } |
| 5770 | sApply.azCol = (const char **)zTab; |
| 5771 | }else{ |
| 5772 | int nMinCol = 0; |
| 5773 | int i; |
| 5774 | |
| 5775 | sqlite3changeset_pk(pIter, &abPK, 0); |
| 5776 | rc = sessionTableInfo(0, db, "main", zNew, |
| 5777 | &sApply.nCol, 0, &zTab, &sApply.azCol, 0, 0, |
| 5778 | &sApply.abPK, &sApply.bRowid |
| 5779 | ); |
| 5780 | if( rc!=SQLITE_OK ) break; |
| 5781 | for(i=0; i<sApply.nCol; i++){ |
| 5782 | if( sApply.abPK[i] ) nMinCol = i+1; |
| 5783 | } |
| 5784 | |
| 5785 | if( sApply.nCol==0 ){ |
| 5786 | schemaMismatch = 1; |
| 5787 | sqlite3_log(SQLITE_SCHEMA, |
| 5788 | "sqlite3changeset_apply(): no such table: %s", zTab |
| 5789 | ); |
| 5790 | } |
| 5791 | else if( sApply.nCol<nCol ){ |
| 5792 | schemaMismatch = 1; |
| 5793 | sqlite3_log(SQLITE_SCHEMA, |
| 5794 | "sqlite3changeset_apply(): table %s has %d columns, " |
| 5795 | "expected %d or more", |
| 5796 | zTab, sApply.nCol, nCol |
| 5797 | ); |
| 5798 | } |
| 5799 | else if( nCol<nMinCol || memcmp(sApply.abPK, abPK, nCol)!=0 ){ |
| 5800 | schemaMismatch = 1; |
| 5801 | sqlite3_log(SQLITE_SCHEMA, "sqlite3changeset_apply(): " |
| 5802 | "primary key mismatch for table %s", zTab |
| 5803 | ); |
| 5804 | } |
| 5805 | else{ |
| 5806 | sApply.nCol = nCol; |
| 5807 | if( 0==sqlite3_stricmp(zTab, "sqlite_stat1") ){ |
| 5808 | if( (rc = sessionStat1Sql(db, &sApply) ) ){ |
| 5809 | break; |
| 5810 | } |
| 5811 | sApply.bStat1 = 1; |
| 5812 | }else{ |
| 5813 | if( (rc = sessionSelectRow(db, zTab, &sApply)) |
| 5814 | || (rc = sessionDeleteRow(db, zTab, &sApply)) |
| 5815 | || (rc = sessionInsertRow(db, zTab, &sApply)) |
| 5816 | ){ |
| 5817 | break; |
| 5818 | } |
| 5819 | sApply.bStat1 = 0; |
| 5820 | } |
| 5821 | } |
| 5822 | } |
| 5823 | } |
| 5824 | |
| 5825 | /* If there is a schema mismatch on the current table, proceed to the |
| 5826 | ** next change. A log message has already been issued. */ |
| 5827 | if( schemaMismatch ) continue; |
| 5828 | |
| 5829 | /* If this is a call to apply_v3(), invoke xFilterIter here. */ |
| 5830 | if( xFilterIter && 0==xFilterIter(pCtx, pIter) ) continue; |
| 5831 | |
| 5832 | rc = sessionApplyOneWithRetry(db, pIter, &sApply, xConflict, pCtx); |
| 5833 | } |
| 5834 | |
| 5835 | bPatchset = pIter->bPatchset; |
| 5836 | if( rc==SQLITE_OK ){ |
| 5837 | rc = sqlite3changeset_finalize(pIter); |
| 5838 | }else{ |
| 5839 | sqlite3changeset_finalize(pIter); |
| 5840 | } |
| 5841 | |
| 5842 | if( rc==SQLITE_OK ){ |
| 5843 | rc = sessionRetryConstraints(db, bPatchset, zTab, &sApply, xConflict, pCtx); |
| 5844 | } |
| 5845 | |
| 5846 | if( rc==SQLITE_OK ){ |
| 5847 | int nFk, notUsed; |
| 5848 | sqlite3_db_status(db, SQLITE_DBSTATUS_DEFERRED_FKS, &nFk, ¬Used, 0); |
| 5849 | if( nFk!=0 ){ |
| 5850 | int res = SQLITE_CHANGESET_ABORT; |
| 5851 | sqlite3_changeset_iter sIter; |
| 5852 | memset(&sIter, 0, sizeof(sIter)); |
| 5853 | sIter.nCol = nFk; |
| 5854 | res = xConflict(pCtx, SQLITE_CHANGESET_FOREIGN_KEY, &sIter); |
| 5855 | if( res!=SQLITE_CHANGESET_OMIT ){ |
| 5856 | rc = SQLITE_CONSTRAINT; |
| 5857 | } |
| 5858 | } |
| 5859 | } |
| 5860 | |
| 5861 | { |
| 5862 | int rc2 = sqlite3_exec(db, "PRAGMA defer_foreign_keys = 0", 0, 0, 0); |
| 5863 | if( rc==SQLITE_OK ) rc = rc2; |
| 5864 | } |
| 5865 | |
| 5866 | if( (flags & SQLITE_CHANGESETAPPLY_NOSAVEPOINT)==0 ){ |
| 5867 | if( rc==SQLITE_OK ){ |
| 5868 | rc = sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0); |
| 5869 | } |
| 5870 | if( rc!=SQLITE_OK ){ |
| 5871 | sqlite3_exec(db, "ROLLBACK TO changeset_apply", 0, 0, 0); |
| 5872 | sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0); |
| 5873 | } |
| 5874 | } |
| 5875 | |
| 5876 | assert( sApply.bRebase || sApply.rebase.nBuf==0 ); |
| 5877 | if( rc==SQLITE_OK && bPatchset==0 && sApply.bRebase ){ |
| 5878 | assert( ppRebase!=0 && pnRebase!=0 ); |
| 5879 | *ppRebase = (void*)sApply.rebase.aBuf; |
| 5880 | *pnRebase = sApply.rebase.nBuf; |
| 5881 | sApply.rebase.aBuf = 0; |
| 5882 | } |
| 5883 | sessionUpdateFree(&sApply); |
| 5884 | sqlite3_finalize(sApply.pInsert); |
| 5885 | sqlite3_finalize(sApply.pDelete); |
| 5886 | sqlite3_finalize(sApply.pSelect); |
| 5887 | sqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */ |
| 5888 | sqlite3_free((char*)sApply.constraints.aBuf); |
| 5889 | sqlite3_free((char*)sApply.rebase.aBuf); |
| 5890 | |
| 5891 | if( (flags & SQLITE_CHANGESETAPPLY_FKNOACTION) && savedFlag==0 ){ |
| 5892 | assert( db->flags & SQLITE_FkNoAction ); |
| 5893 | db->flags &= ~((u64)SQLITE_FkNoAction); |
| 5894 | db->aDb[0].pSchema->schema_cookie -= 32; |
| 5895 | } |
| 5896 | |
| 5897 | assert( rc!=SQLITE_OK || sApply.zErr==0 ); |
| 5898 | sqlite3_set_errmsg(db, rc, sApply.zErr); |
| 5899 | sqlite3_free(sApply.zErr); |
| 5900 | |
| 5901 | sqlite3_mutex_leave(sqlite3_db_mutex(db)); |
| 5902 | return rc; |
| 5903 | } |
| 5904 | |
| 5905 | /* |
| 5906 | ** This function is called by all six sqlite3changeset_apply() variants: |
| 5907 | ** |
| 5908 | ** + sqlite3changeset_apply() |
| 5909 | ** + sqlite3changeset_apply_v2() |
| 5910 | ** + sqlite3changeset_apply_v3() |
| 5911 | ** + sqlite3changeset_apply_strm() |
| 5912 | ** + sqlite3changeset_apply_strm_v2() |
| 5913 | ** + sqlite3changeset_apply_strm_v3() |
| 5914 | ** |
| 5915 | ** Arguments passed to this function are as follows: |
| 5916 | ** |
| 5917 | ** db: |
| 5918 | ** Database handle to apply changeset to main database of. |
| 5919 | ** |
| 5920 | ** nChangeset/pChangeset: |
| 5921 | ** These are both passed zero for the streaming variants. For the normal |
| 5922 | ** apply() functions, these are passed the size of and the buffer containing |
| 5923 | ** the changeset, respectively. |
| 5924 | ** |
| 5925 | ** xInput/pIn: |
| 5926 | ** These are both passed zero for the normal variants. For the streaming |
| 5927 | ** apply() functions, these are passed the input callback and context |
| 5928 | ** pointer, respectively. |
| 5929 | ** |
| 5930 | ** xFilter: |
| 5931 | ** The filter function as passed to apply() or apply_v2() (to filter by |
| 5932 | ** table name), if any. This is always NULL for apply_v3() calls. |
| 5933 | ** |
| 5934 | ** xFilterIter: |
| 5935 | ** The filter function as passed to apply_v3(), if any. |
| 5936 | ** |
| 5937 | ** xConflict: |
| 5938 | ** The conflict handler callback (must not be NULL). |
| 5939 | ** |
| 5940 | ** pCtx: |
| 5941 | ** The context pointer passed to the xFilter and xConflict handler callbacks. |
| 5942 | ** |
| 5943 | ** ppRebase, pnRebase: |
| 5944 | ** Zero for apply(). The rebase changeset output pointers, if any, for |
| 5945 | ** apply_v2() and apply_v3(). |
| 5946 | ** |
| 5947 | ** flags: |
| 5948 | ** Zero for apply(). The flags parameter for apply_v2() and apply_v3(). |
| 5949 | */ |
| 5950 | static int sessionChangesetApplyV23( |
| 5951 | sqlite3 *db, /* Apply change to "main" db of this handle */ |
| 5952 | int nChangeset, /* Size of changeset in bytes */ |
| 5953 | void *pChangeset, /* Changeset blob */ |
| 5954 | int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */ |
| 5955 | void *pIn, /* First arg for xInput */ |
| 5956 | int(*xFilter)( |
| 5957 | void *pCtx, /* Copy of sixth arg to _apply() */ |
| 5958 | const char *zTab /* Table name */ |
| 5959 | ), |
| 5960 | int(*xFilterIter)( |
| 5961 | void *pCtx, /* Copy of sixth arg to _apply() */ |
| 5962 | sqlite3_changeset_iter *p /* Handle describing current change */ |
| 5963 | ), |
| 5964 | int(*xConflict)( |
| 5965 | void *pCtx, /* Copy of sixth arg to _apply() */ |
| 5966 | int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ |
| 5967 | sqlite3_changeset_iter *p /* Handle describing change and conflict */ |
| 5968 | ), |
| 5969 | void *pCtx, /* First argument passed to xConflict */ |
| 5970 | void **ppRebase, int *pnRebase, |
| 5971 | int flags |
| 5972 | ){ |
| 5973 | sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */ |
| 5974 | int bInverse = !!(flags & SQLITE_CHANGESETAPPLY_INVERT); |
| 5975 | int rc = sessionChangesetStart( |
| 5976 | &pIter, xInput, pIn, nChangeset, pChangeset, bInverse, 1 |
| 5977 | ); |
| 5978 | if( rc==SQLITE_OK ){ |
| 5979 | rc = sessionChangesetApply(db, pIter, |
| 5980 | xFilter, xFilterIter, xConflict, pCtx, ppRebase, pnRebase, flags |
| 5981 | ); |
| 5982 | } |
| 5983 | return rc; |
| 5984 | } |
| 5985 | |
| 5986 | /* |
| 5987 | ** Apply the changeset passed via pChangeset/nChangeset to the main |
| 5988 | ** database attached to handle "db". |
| 5989 | */ |
| 5990 | int sqlite3changeset_apply_v2( |
| 5991 | sqlite3 *db, /* Apply change to "main" db of this handle */ |
| 5992 | int nChangeset, /* Size of changeset in bytes */ |
| 5993 | void *pChangeset, /* Changeset blob */ |
| 5994 | int(*xFilter)( |
| 5995 | void *pCtx, /* Copy of sixth arg to _apply() */ |
| 5996 | const char *zTab /* Table name */ |
| 5997 | ), |
| 5998 | int(*xConflict)( |
| 5999 | void *pCtx, /* Copy of sixth arg to _apply() */ |
| 6000 | int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ |
| 6001 | sqlite3_changeset_iter *p /* Handle describing change and conflict */ |
| 6002 | ), |
| 6003 | void *pCtx, /* First argument passed to xConflict */ |
| 6004 | void **ppRebase, int *pnRebase, |
| 6005 | int flags |
| 6006 | ){ |
| 6007 | return sessionChangesetApplyV23(db, |
| 6008 | nChangeset, pChangeset, 0, 0, |
| 6009 | xFilter, 0, xConflict, pCtx, |
| 6010 | ppRebase, pnRebase, flags |
| 6011 | ); |
| 6012 | } |
| 6013 | |
| 6014 | /* |
| 6015 | ** Apply the changeset passed via pChangeset/nChangeset to the main |
| 6016 | ** database attached to handle "db". |
| 6017 | */ |
| 6018 | int sqlite3changeset_apply_v3( |
| 6019 | sqlite3 *db, /* Apply change to "main" db of this handle */ |
| 6020 | int nChangeset, /* Size of changeset in bytes */ |
| 6021 | void *pChangeset, /* Changeset blob */ |
| 6022 | int(*xFilter)( |
| 6023 | void *pCtx, /* Copy of sixth arg to _apply() */ |
| 6024 | sqlite3_changeset_iter *p /* Handle describing current change */ |
| 6025 | ), |
| 6026 | int(*xConflict)( |
| 6027 | void *pCtx, /* Copy of sixth arg to _apply() */ |
| 6028 | int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ |
| 6029 | sqlite3_changeset_iter *p /* Handle describing change and conflict */ |
| 6030 | ), |
| 6031 | void *pCtx, /* First argument passed to xConflict */ |
| 6032 | void **ppRebase, int *pnRebase, |
| 6033 | int flags |
| 6034 | ){ |
| 6035 | return sessionChangesetApplyV23(db, |
| 6036 | nChangeset, pChangeset, 0, 0, |
| 6037 | 0, xFilter, xConflict, pCtx, |
| 6038 | ppRebase, pnRebase, flags |
| 6039 | ); |
| 6040 | } |
| 6041 | |
| 6042 | /* |
| 6043 | ** Apply the changeset passed via pChangeset/nChangeset to the main database |
| 6044 | ** attached to handle "db". Invoke the supplied conflict handler callback |
| 6045 | ** to resolve any conflicts encountered while applying the change. |
| 6046 | */ |
| 6047 | int sqlite3changeset_apply( |
| 6048 | sqlite3 *db, /* Apply change to "main" db of this handle */ |
| 6049 | int nChangeset, /* Size of changeset in bytes */ |
| 6050 | void *pChangeset, /* Changeset blob */ |
| 6051 | int(*xFilter)( |
| 6052 | void *pCtx, /* Copy of sixth arg to _apply() */ |
| 6053 | const char *zTab /* Table name */ |
| 6054 | ), |
| 6055 | int(*xConflict)( |
| 6056 | void *pCtx, /* Copy of fifth arg to _apply() */ |
| 6057 | int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ |
| 6058 | sqlite3_changeset_iter *p /* Handle describing change and conflict */ |
| 6059 | ), |
| 6060 | void *pCtx /* First argument passed to xConflict */ |
| 6061 | ){ |
| 6062 | return sessionChangesetApplyV23(db, |
| 6063 | nChangeset, pChangeset, 0, 0, |
| 6064 | xFilter, 0, xConflict, pCtx, |
| 6065 | 0, 0, 0 |
| 6066 | ); |
| 6067 | } |
| 6068 | |
| 6069 | /* |
| 6070 | ** Apply the changeset passed via xInput/pIn to the main database |
| 6071 | ** attached to handle "db". Invoke the supplied conflict handler callback |
| 6072 | ** to resolve any conflicts encountered while applying the change. |
| 6073 | */ |
| 6074 | int sqlite3changeset_apply_v3_strm( |
| 6075 | sqlite3 *db, /* Apply change to "main" db of this handle */ |
| 6076 | int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */ |
| 6077 | void *pIn, /* First arg for xInput */ |
| 6078 | int(*xFilter)( |
| 6079 | void *pCtx, /* Copy of sixth arg to _apply() */ |
| 6080 | sqlite3_changeset_iter *p |
| 6081 | ), |
| 6082 | int(*xConflict)( |
| 6083 | void *pCtx, /* Copy of sixth arg to _apply() */ |
| 6084 | int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ |
| 6085 | sqlite3_changeset_iter *p /* Handle describing change and conflict */ |
| 6086 | ), |
| 6087 | void *pCtx, /* First argument passed to xConflict */ |
| 6088 | void **ppRebase, int *pnRebase, |
| 6089 | int flags |
| 6090 | ){ |
| 6091 | return sessionChangesetApplyV23(db, |
| 6092 | 0, 0, xInput, pIn, |
| 6093 | 0, xFilter, xConflict, pCtx, |
| 6094 | ppRebase, pnRebase, flags |
| 6095 | ); |
| 6096 | } |
| 6097 | int sqlite3changeset_apply_v2_strm( |
| 6098 | sqlite3 *db, /* Apply change to "main" db of this handle */ |
| 6099 | int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */ |
| 6100 | void *pIn, /* First arg for xInput */ |
| 6101 | int(*xFilter)( |
| 6102 | void *pCtx, /* Copy of sixth arg to _apply() */ |
| 6103 | const char *zTab /* Table name */ |
| 6104 | ), |
| 6105 | int(*xConflict)( |
| 6106 | void *pCtx, /* Copy of sixth arg to _apply() */ |
| 6107 | int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ |
| 6108 | sqlite3_changeset_iter *p /* Handle describing change and conflict */ |
| 6109 | ), |
| 6110 | void *pCtx, /* First argument passed to xConflict */ |
| 6111 | void **ppRebase, int *pnRebase, |
| 6112 | int flags |
| 6113 | ){ |
| 6114 | return sessionChangesetApplyV23(db, |
| 6115 | 0, 0, xInput, pIn, |
| 6116 | xFilter, 0, xConflict, pCtx, |
| 6117 | ppRebase, pnRebase, flags |
| 6118 | ); |
| 6119 | } |
| 6120 | int sqlite3changeset_apply_strm( |
| 6121 | sqlite3 *db, /* Apply change to "main" db of this handle */ |
| 6122 | int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */ |
| 6123 | void *pIn, /* First arg for xInput */ |
| 6124 | int(*xFilter)( |
| 6125 | void *pCtx, /* Copy of sixth arg to _apply() */ |
| 6126 | const char *zTab /* Table name */ |
| 6127 | ), |
| 6128 | int(*xConflict)( |
| 6129 | void *pCtx, /* Copy of sixth arg to _apply() */ |
| 6130 | int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ |
| 6131 | sqlite3_changeset_iter *p /* Handle describing change and conflict */ |
| 6132 | ), |
| 6133 | void *pCtx /* First argument passed to xConflict */ |
| 6134 | ){ |
| 6135 | return sessionChangesetApplyV23(db, |
| 6136 | 0, 0, xInput, pIn, |
| 6137 | xFilter, 0, xConflict, pCtx, |
| 6138 | 0, 0, 0 |
| 6139 | ); |
| 6140 | } |
| 6141 | |
| 6142 | /* |
| 6143 | ** The parts of the sqlite3_changegroup structure used by the |
| 6144 | ** sqlite3changegroup_change_xxx() APIs. |
| 6145 | */ |
| 6146 | typedef struct ChangeData ChangeData; |
| 6147 | struct ChangeData { |
| 6148 | SessionTable *pTab; |
| 6149 | int bIndirect; |
| 6150 | int eOp; |
| 6151 | |
| 6152 | int nBufAlloc; |
| 6153 | SessionBuffer *aBuf; |
| 6154 | SessionBuffer record; |
| 6155 | }; |
| 6156 | |
| 6157 | /* |
| 6158 | ** sqlite3_changegroup handle. |
| 6159 | */ |
| 6160 | struct sqlite3_changegroup { |
| 6161 | int rc; /* Error code */ |
| 6162 | int bPatch; /* True to accumulate patchsets */ |
| 6163 | SessionTable *pList; /* List of tables in current patch */ |
| 6164 | SessionBuffer rec; |
| 6165 | |
| 6166 | sqlite3 *db; /* Configured by changegroup_schema() */ |
| 6167 | char *zDb; /* Configured by changegroup_schema() */ |
| 6168 | ChangeData cd; /* Used by changegroup_change_xxx() APIs. */ |
| 6169 | }; |
| 6170 | |
| 6171 | /* |
| 6172 | ** This function is called to merge two changes to the same row together as |
| 6173 | ** part of an sqlite3changeset_concat() operation. A new change object is |
| 6174 | ** allocated and a pointer to it stored in *ppNew. |
| 6175 | ** |
| 6176 | ** Because they have been vetted by sqlite3changegroup_add() or similar, |
| 6177 | ** both the aRec[] change and the pExist change are safe to use without |
| 6178 | ** checking for buffer overflows. |
| 6179 | */ |
| 6180 | static int sessionChangeMerge( |
| 6181 | SessionTable *pTab, /* Table structure */ |
| 6182 | int bRebase, /* True for a rebase hash-table */ |
| 6183 | int bPatchset, /* True for patchsets */ |
| 6184 | SessionChange *pExist, /* Existing change */ |
| 6185 | int op2, /* Second change operation */ |
| 6186 | int bIndirect, /* True if second change is indirect */ |
| 6187 | u8 *aRec, /* Second change record */ |
| 6188 | int nRec, /* Number of bytes in aRec */ |
| 6189 | SessionChange **ppNew /* OUT: Merged change */ |
| 6190 | ){ |
| 6191 | SessionChange *pNew = 0; |
| 6192 | int rc = SQLITE_OK; |
| 6193 | assert( aRec!=0 ); |
| 6194 | |
| 6195 | if( !pExist ){ |
| 6196 | pNew = (SessionChange *)sqlite3_malloc64(sizeof(SessionChange) + nRec); |
| 6197 | if( !pNew ){ |
| 6198 | return SQLITE_NOMEM; |
| 6199 | } |
| 6200 | memset(pNew, 0, sizeof(SessionChange)); |
| 6201 | pNew->op = op2; |
| 6202 | pNew->bIndirect = bIndirect; |
| 6203 | pNew->aRecord = (u8*)&pNew[1]; |
| 6204 | if( bIndirect==0 || bRebase==0 ){ |
| 6205 | pNew->nRecord = nRec; |
| 6206 | memcpy(pNew->aRecord, aRec, nRec); |
| 6207 | }else{ |
| 6208 | int i; |
| 6209 | u8 *pIn = aRec; |
| 6210 | u8 *pOut = pNew->aRecord; |
| 6211 | for(i=0; i<pTab->nCol; i++){ |
| 6212 | int nIn = sessionSerialLen(pIn); |
| 6213 | if( *pIn==0 ){ |
| 6214 | *pOut++ = 0; |
| 6215 | }else if( pTab->abPK[i]==0 ){ |
| 6216 | *pOut++ = 0xFF; |
| 6217 | }else{ |
| 6218 | memcpy(pOut, pIn, nIn); |
| 6219 | pOut += nIn; |
| 6220 | } |
| 6221 | pIn += nIn; |
| 6222 | } |
| 6223 | pNew->nRecord = pOut - pNew->aRecord; |
| 6224 | } |
| 6225 | }else if( bRebase ){ |
| 6226 | if( pExist->op==SQLITE_DELETE && pExist->bIndirect ){ |
| 6227 | pNew = pExist; |
| 6228 | }else{ |
| 6229 | sqlite3_int64 nByte = nRec + pExist->nRecord + sizeof(SessionChange); |
| 6230 | pNew = (SessionChange*)sqlite3_malloc64(nByte); |
| 6231 | if( pNew==0 ){ |
| 6232 | rc = SQLITE_NOMEM; |
| 6233 | }else{ |
| 6234 | int i; |
| 6235 | u8 *a1 = pExist->aRecord; |
| 6236 | u8 *a2 = aRec; |
| 6237 | u8 *pOut; |
| 6238 | |
| 6239 | memset(pNew, 0, nByte); |
| 6240 | pNew->bIndirect = bIndirect || pExist->bIndirect; |
| 6241 | pNew->op = op2; |
| 6242 | pOut = pNew->aRecord = (u8*)&pNew[1]; |
| 6243 | |
| 6244 | for(i=0; i<pTab->nCol; i++){ |
| 6245 | int n1 = sessionSerialLen(a1); |
| 6246 | int n2 = sessionSerialLen(a2); |
| 6247 | if( *a1==0xFF || (pTab->abPK[i]==0 && bIndirect) ){ |
| 6248 | *pOut++ = 0xFF; |
| 6249 | }else if( *a2==0 ){ |
| 6250 | memcpy(pOut, a1, n1); |
| 6251 | pOut += n1; |
| 6252 | }else{ |
| 6253 | memcpy(pOut, a2, n2); |
| 6254 | pOut += n2; |
| 6255 | } |
| 6256 | a1 += n1; |
| 6257 | a2 += n2; |
| 6258 | } |
| 6259 | pNew->nRecord = pOut - pNew->aRecord; |
| 6260 | } |
| 6261 | sqlite3_free(pExist); |
| 6262 | } |
| 6263 | }else{ |
| 6264 | int op1 = pExist->op; |
| 6265 | |
| 6266 | /* |
| 6267 | ** op1=INSERT, op2=INSERT -> Unsupported. Discard op2. |
| 6268 | ** op1=INSERT, op2=UPDATE -> INSERT. |
| 6269 | ** op1=INSERT, op2=DELETE -> (none) |
| 6270 | ** |
| 6271 | ** op1=UPDATE, op2=INSERT -> Unsupported. Discard op2. |
| 6272 | ** op1=UPDATE, op2=UPDATE -> UPDATE. |
| 6273 | ** op1=UPDATE, op2=DELETE -> DELETE. |
| 6274 | ** |
| 6275 | ** op1=DELETE, op2=INSERT -> UPDATE. |
| 6276 | ** op1=DELETE, op2=UPDATE -> Unsupported. Discard op2. |
| 6277 | ** op1=DELETE, op2=DELETE -> Unsupported. Discard op2. |
| 6278 | */ |
| 6279 | if( (op1==SQLITE_INSERT && op2==SQLITE_INSERT) |
| 6280 | || (op1==SQLITE_UPDATE && op2==SQLITE_INSERT) |
| 6281 | || (op1==SQLITE_DELETE && op2==SQLITE_UPDATE) |
| 6282 | || (op1==SQLITE_DELETE && op2==SQLITE_DELETE) |
| 6283 | ){ |
| 6284 | pNew = pExist; |
| 6285 | }else if( op1==SQLITE_INSERT && op2==SQLITE_DELETE ){ |
| 6286 | sqlite3_free(pExist); |
| 6287 | assert( pNew==0 ); |
| 6288 | }else{ |
| 6289 | u8 *aExist = pExist->aRecord; |
| 6290 | sqlite3_int64 nByte; |
| 6291 | u8 *aCsr; |
| 6292 | |
| 6293 | /* Allocate a new SessionChange object. Ensure that the aRecord[] |
| 6294 | ** buffer of the new object is large enough to hold any record that |
| 6295 | ** may be generated by combining the input records. */ |
| 6296 | nByte = sizeof(SessionChange) + pExist->nRecord + nRec; |
| 6297 | pNew = (SessionChange *)sqlite3_malloc64(nByte); |
| 6298 | if( !pNew ){ |
| 6299 | sqlite3_free(pExist); |
| 6300 | return SQLITE_NOMEM; |
| 6301 | } |
| 6302 | memset(pNew, 0, sizeof(SessionChange)); |
| 6303 | pNew->bIndirect = (bIndirect && pExist->bIndirect); |
| 6304 | aCsr = pNew->aRecord = (u8 *)&pNew[1]; |
| 6305 | |
| 6306 | if( op1==SQLITE_INSERT ){ /* INSERT + UPDATE */ |
| 6307 | u8 *a1 = aRec; |
| 6308 | assert( op2==SQLITE_UPDATE ); |
| 6309 | pNew->op = SQLITE_INSERT; |
| 6310 | if( bPatchset==0 ) sessionSkipRecord(&a1, pTab->nCol); |
| 6311 | sessionMergeRecord(&aCsr, pTab->nCol, aExist, a1); |
| 6312 | }else if( op1==SQLITE_DELETE ){ /* DELETE + INSERT */ |
| 6313 | assert( op2==SQLITE_INSERT ); |
| 6314 | pNew->op = SQLITE_UPDATE; |
| 6315 | if( bPatchset ){ |
| 6316 | memcpy(aCsr, aRec, nRec); |
| 6317 | aCsr += nRec; |
| 6318 | }else{ |
| 6319 | if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aExist,0,aRec,0) ){ |
| 6320 | sqlite3_free(pNew); |
| 6321 | pNew = 0; |
| 6322 | } |
| 6323 | } |
| 6324 | }else if( op2==SQLITE_UPDATE ){ /* UPDATE + UPDATE */ |
| 6325 | u8 *a1 = aExist; |
| 6326 | u8 *a2 = aRec; |
| 6327 | assert( op1==SQLITE_UPDATE ); |
| 6328 | if( bPatchset==0 ){ |
| 6329 | sessionSkipRecord(&a1, pTab->nCol); |
| 6330 | sessionSkipRecord(&a2, pTab->nCol); |
| 6331 | } |
| 6332 | pNew->op = SQLITE_UPDATE; |
| 6333 | if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aRec, aExist,a1,a2) ){ |
| 6334 | sqlite3_free(pNew); |
| 6335 | pNew = 0; |
| 6336 | } |
| 6337 | }else{ /* UPDATE + DELETE */ |
| 6338 | assert( op1==SQLITE_UPDATE && op2==SQLITE_DELETE ); |
| 6339 | pNew->op = SQLITE_DELETE; |
| 6340 | if( bPatchset ){ |
| 6341 | memcpy(aCsr, aRec, nRec); |
| 6342 | aCsr += nRec; |
| 6343 | }else{ |
| 6344 | sessionMergeRecord(&aCsr, pTab->nCol, aRec, aExist); |
| 6345 | } |
| 6346 | } |
| 6347 | |
| 6348 | if( pNew ){ |
| 6349 | pNew->nRecord = (int)(aCsr - pNew->aRecord); |
| 6350 | } |
| 6351 | sqlite3_free(pExist); |
| 6352 | } |
| 6353 | } |
| 6354 | |
| 6355 | *ppNew = pNew; |
| 6356 | return rc; |
| 6357 | } |
| 6358 | |
| 6359 | /* |
| 6360 | ** Check if a changeset entry with nCol columns and the PK array passed |
| 6361 | ** as the final argument to this function is compatible with SessionTable |
| 6362 | ** pTab. If so, return 1. Otherwise, if they are incompatible in some way, |
| 6363 | ** return 0. |
| 6364 | */ |
| 6365 | static int sessionChangesetCheckCompat( |
| 6366 | SessionTable *pTab, |
| 6367 | int nCol, |
| 6368 | u8 *abPK |
| 6369 | ){ |
| 6370 | if( pTab->azCol && nCol<pTab->nCol ){ |
| 6371 | int ii; |
| 6372 | for(ii=0; ii<pTab->nCol; ii++){ |
| 6373 | u8 bPK = (ii < nCol) ? abPK[ii] : 0; |
| 6374 | if( pTab->abPK[ii]!=bPK ) return 0; |
| 6375 | } |
| 6376 | return 1; |
| 6377 | } |
| 6378 | return (pTab->nCol==nCol && 0==memcmp(abPK, pTab->abPK, nCol)); |
| 6379 | } |
| 6380 | |
| 6381 | static int sessionChangesetExtendRecord( |
| 6382 | sqlite3_changegroup *pGrp, |
| 6383 | SessionTable *pTab, |
| 6384 | int nCol, |
| 6385 | int op, |
| 6386 | const u8 *aRec, |
| 6387 | int nRec, |
| 6388 | SessionBuffer *pOut |
| 6389 | ){ |
| 6390 | int rc = SQLITE_OK; |
| 6391 | int ii = 0; |
| 6392 | |
| 6393 | assert( pTab->azCol ); |
| 6394 | assert( nCol<pTab->nCol ); |
| 6395 | |
| 6396 | pOut->nBuf = 0; |
| 6397 | if( op==SQLITE_INSERT || (op==SQLITE_DELETE && pGrp->bPatch==0) ){ |
| 6398 | /* Append the missing default column values to the record. */ |
| 6399 | sessionAppendBlob(pOut, aRec, nRec, &rc); |
| 6400 | if( rc==SQLITE_OK && pTab->pDfltStmt==0 ){ |
| 6401 | rc = sessionPrepareDfltStmt(pGrp->db, pTab, &pTab->pDfltStmt); |
| 6402 | if( rc==SQLITE_OK && SQLITE_ROW!=sqlite3_step(pTab->pDfltStmt) ){ |
| 6403 | rc = sqlite3_errcode(pGrp->db); |
| 6404 | } |
| 6405 | } |
| 6406 | for(ii=nCol; rc==SQLITE_OK && ii<pTab->nCol; ii++){ |
| 6407 | int eType = sqlite3_column_type(pTab->pDfltStmt, ii); |
| 6408 | sessionAppendByte(pOut, eType, &rc); |
| 6409 | switch( eType ){ |
| 6410 | case SQLITE_FLOAT: |
| 6411 | case SQLITE_INTEGER: { |
| 6412 | if( SQLITE_OK==sessionBufferGrow(pOut, 8, &rc) ){ |
| 6413 | if( eType==SQLITE_INTEGER ){ |
| 6414 | sqlite3_int64 iVal = sqlite3_column_int64(pTab->pDfltStmt, ii); |
| 6415 | sessionPutI64(&pOut->aBuf[pOut->nBuf], iVal); |
| 6416 | }else{ |
| 6417 | double rVal = sqlite3_column_double(pTab->pDfltStmt, ii); |
| 6418 | sessionPutDouble(&pOut->aBuf[pOut->nBuf], rVal); |
| 6419 | } |
| 6420 | pOut->nBuf += 8; |
| 6421 | } |
| 6422 | break; |
| 6423 | } |
| 6424 | |
| 6425 | case SQLITE_BLOB: |
| 6426 | case SQLITE_TEXT: { |
| 6427 | int n = sqlite3_column_bytes(pTab->pDfltStmt, ii); |
| 6428 | sessionAppendVarint(pOut, n, &rc); |
| 6429 | if( eType==SQLITE_TEXT ){ |
| 6430 | const u8 *z = (const u8*)sqlite3_column_text(pTab->pDfltStmt, ii); |
| 6431 | sessionAppendBlob(pOut, z, n, &rc); |
| 6432 | }else{ |
| 6433 | const u8 *z = (const u8*)sqlite3_column_blob(pTab->pDfltStmt, ii); |
| 6434 | sessionAppendBlob(pOut, z, n, &rc); |
| 6435 | } |
| 6436 | break; |
| 6437 | } |
| 6438 | |
| 6439 | default: |
| 6440 | assert( eType==SQLITE_NULL ); |
| 6441 | break; |
| 6442 | } |
| 6443 | } |
| 6444 | }else if( op==SQLITE_UPDATE ){ |
| 6445 | /* Append missing "undefined" entries to the old.* record. And, if this |
| 6446 | ** is an UPDATE, to the new.* record as well. */ |
| 6447 | int iOff = 0; |
| 6448 | if( pGrp->bPatch==0 ){ |
| 6449 | for(ii=0; ii<nCol; ii++){ |
| 6450 | iOff += sessionSerialLen(&aRec[iOff]); |
| 6451 | } |
| 6452 | sessionAppendBlob(pOut, aRec, iOff, &rc); |
| 6453 | for(ii=0; ii<(pTab->nCol-nCol); ii++){ |
| 6454 | sessionAppendByte(pOut, 0x00, &rc); |
| 6455 | } |
| 6456 | } |
| 6457 | |
| 6458 | sessionAppendBlob(pOut, &aRec[iOff], nRec-iOff, &rc); |
| 6459 | for(ii=0; ii<(pTab->nCol-nCol); ii++){ |
| 6460 | sessionAppendByte(pOut, 0x00, &rc); |
| 6461 | } |
| 6462 | }else{ |
| 6463 | assert( op==SQLITE_DELETE && pGrp->bPatch ); |
| 6464 | sessionAppendBlob(pOut, aRec, nRec, &rc); |
| 6465 | } |
| 6466 | |
| 6467 | return rc; |
| 6468 | } |
| 6469 | |
| 6470 | /* |
| 6471 | ** Locate or create a SessionTable object that may be used to add the |
| 6472 | ** change currently pointed to by iterator pIter to changegroup pGrp. |
| 6473 | ** If successful, set output variable (*ppTab) to point to the table |
| 6474 | ** object and return SQLITE_OK. Otherwise, if some error occurs, return |
| 6475 | ** an SQLite error code and leave (*ppTab) set to NULL. |
| 6476 | */ |
| 6477 | static int sessionChangesetFindTable( |
| 6478 | sqlite3_changegroup *pGrp, |
| 6479 | const char *zTab, |
| 6480 | sqlite3_changeset_iter *pIter, |
| 6481 | SessionTable **ppTab |
| 6482 | ){ |
| 6483 | int rc = SQLITE_OK; |
| 6484 | SessionTable *pTab = 0; |
| 6485 | int nTab = (int)strlen(zTab); |
| 6486 | u8 *abPK = 0; |
| 6487 | int nCol = 0; |
| 6488 | |
| 6489 | *ppTab = 0; |
| 6490 | |
| 6491 | /* Search the list for an existing table */ |
| 6492 | for(pTab = pGrp->pList; pTab; pTab=pTab->pNext){ |
| 6493 | if( 0==sqlite3_strnicmp(pTab->zName, zTab, nTab+1) ) break; |
| 6494 | } |
| 6495 | |
| 6496 | |
| 6497 | if( pIter ){ |
| 6498 | sqlite3changeset_pk(pIter, &abPK, &nCol); |
| 6499 | }else if( !pTab && !pGrp->db ){ |
| 6500 | return SQLITE_ERROR; |
| 6501 | } |
| 6502 | |
| 6503 | /* If one was not found above, create a new table now */ |
| 6504 | if( !pTab ){ |
| 6505 | SessionTable **ppNew; |
| 6506 | |
| 6507 | pTab = sqlite3_malloc64(sizeof(SessionTable) + nCol + nTab+1); |
| 6508 | if( !pTab ){ |
| 6509 | return SQLITE_NOMEM; |
| 6510 | } |
| 6511 | memset(pTab, 0, sizeof(SessionTable)); |
| 6512 | pTab->nCol = nCol; |
| 6513 | pTab->abPK = (u8*)&pTab[1]; |
| 6514 | if( nCol>0 ){ |
| 6515 | memcpy(pTab->abPK, abPK, nCol); |
| 6516 | } |
| 6517 | pTab->zName = (char*)&pTab->abPK[nCol]; |
| 6518 | memcpy(pTab->zName, zTab, nTab+1); |
| 6519 | |
| 6520 | if( pGrp->db ){ |
| 6521 | pTab->nCol = 0; |
| 6522 | rc = sessionInitTable(0, pTab, pGrp->db, pGrp->zDb); |
| 6523 | if( rc || pTab->nCol==0 ){ |
| 6524 | sqlite3_free(pTab->azCol); |
| 6525 | sqlite3_free(pTab); |
| 6526 | return rc ? rc : SQLITE_ERROR; |
| 6527 | } |
| 6528 | } |
| 6529 | |
| 6530 | /* The new object must be linked on to the end of the list, not |
| 6531 | ** simply added to the start of it. This is to ensure that the |
| 6532 | ** tables within the output of sqlite3changegroup_output() are in |
| 6533 | ** the right order. */ |
| 6534 | for(ppNew=&pGrp->pList; *ppNew; ppNew=&(*ppNew)->pNext); |
| 6535 | *ppNew = pTab; |
| 6536 | } |
| 6537 | |
| 6538 | /* Check that the table is compatible. */ |
| 6539 | if( pIter && !sessionChangesetCheckCompat(pTab, nCol, abPK) ){ |
| 6540 | rc = SQLITE_SCHEMA; |
| 6541 | } |
| 6542 | |
| 6543 | *ppTab = pTab; |
| 6544 | return rc; |
| 6545 | } |
| 6546 | |
| 6547 | /* |
| 6548 | ** Add a single change to the changegroup pGrp. |
| 6549 | */ |
| 6550 | static int sessionOneChangeToHash( |
| 6551 | sqlite3_changegroup *pGrp, /* Changegroup to update */ |
| 6552 | SessionTable *pTab, /* Table change pertains to */ |
| 6553 | int op, /* One of SQLITE_INSERT, UPDATE, DELETE */ |
| 6554 | int bIndirect, /* True to flag change as "indirect" */ |
| 6555 | int nCol, /* Number of columns in record(s) */ |
| 6556 | u8 *aRec, /* Serialized change record(s) */ |
| 6557 | int nRec, /* Size of aRec[] in bytes */ |
| 6558 | int bRebase /* True if this is a rebase blob */ |
| 6559 | ){ |
| 6560 | int rc = SQLITE_OK; |
| 6561 | int iHash = 0; |
| 6562 | SessionChange *pChange = 0; |
| 6563 | SessionChange *pExist = 0; |
| 6564 | SessionChange **pp = 0; |
| 6565 | |
| 6566 | assert( nRec>0 ); |
| 6567 | |
| 6568 | if( nCol<pTab->nCol ){ |
| 6569 | SessionBuffer *pBuf = &pGrp->rec; |
| 6570 | rc = sessionChangesetExtendRecord(pGrp, pTab, nCol, op, aRec, nRec, pBuf); |
| 6571 | aRec = pBuf->aBuf; |
| 6572 | nRec = pBuf->nBuf; |
| 6573 | assert( pGrp->db ); |
| 6574 | } |
| 6575 | |
| 6576 | if( rc==SQLITE_OK && sessionGrowHash(0, pGrp->bPatch, pTab) ){ |
| 6577 | rc = SQLITE_NOMEM; |
| 6578 | } |
| 6579 | |
| 6580 | if( rc==SQLITE_OK ){ |
| 6581 | /* Search for existing entry. If found, remove it from the hash table. |
| 6582 | ** Code below may link it back in. */ |
| 6583 | iHash = sessionChangeHash( |
| 6584 | pTab, (pGrp->bPatch && op==SQLITE_DELETE), aRec, pTab->nChange |
| 6585 | ); |
| 6586 | for(pp=&pTab->apChange[iHash]; *pp; pp=&(*pp)->pNext){ |
| 6587 | int bPkOnly1 = 0; |
| 6588 | int bPkOnly2 = 0; |
| 6589 | if( pGrp->bPatch ){ |
| 6590 | bPkOnly1 = (*pp)->op==SQLITE_DELETE; |
| 6591 | bPkOnly2 = op==SQLITE_DELETE; |
| 6592 | } |
| 6593 | if( sessionChangeEqual(pTab, bPkOnly1, (*pp)->aRecord, bPkOnly2, aRec) ){ |
| 6594 | pExist = *pp; |
| 6595 | *pp = (*pp)->pNext; |
| 6596 | pTab->nEntry--; |
| 6597 | break; |
| 6598 | } |
| 6599 | } |
| 6600 | } |
| 6601 | |
| 6602 | if( rc==SQLITE_OK ){ |
| 6603 | rc = sessionChangeMerge(pTab, bRebase, |
| 6604 | pGrp->bPatch, pExist, op, bIndirect, aRec, nRec, &pChange |
| 6605 | ); |
| 6606 | } |
| 6607 | if( rc==SQLITE_OK && pChange ){ |
| 6608 | pChange->pNext = pTab->apChange[iHash]; |
| 6609 | pTab->apChange[iHash] = pChange; |
| 6610 | pTab->nEntry++; |
| 6611 | } |
| 6612 | |
| 6613 | return rc; |
| 6614 | } |
| 6615 | |
| 6616 | /* |
| 6617 | ** Add the change currently indicated by iterator pIter to the hash table |
| 6618 | ** belonging to changegroup pGrp. |
| 6619 | */ |
| 6620 | static int sessionOneChangeIterToHash( |
| 6621 | sqlite3_changegroup *pGrp, |
| 6622 | sqlite3_changeset_iter *pIter, |
| 6623 | int bRebase |
| 6624 | ){ |
| 6625 | u8 *aRec = &pIter->in.aData[pIter->in.iCurrent + 2]; |
| 6626 | int nRec = (pIter->in.iNext - pIter->in.iCurrent) - 2; |
| 6627 | const char *zTab = 0; |
| 6628 | int nCol = 0; |
| 6629 | int op = 0; |
| 6630 | int bIndirect = 0; |
| 6631 | int rc = SQLITE_OK; |
| 6632 | SessionTable *pTab = 0; |
| 6633 | |
| 6634 | /* Ensure that only changesets, or only patchsets, but not a mixture |
| 6635 | ** of both, are being combined. It is an error to try to combine a |
| 6636 | ** changeset and a patchset. */ |
| 6637 | if( pGrp->pList==0 ){ |
| 6638 | pGrp->bPatch = pIter->bPatchset; |
| 6639 | }else if( pIter->bPatchset!=pGrp->bPatch ){ |
| 6640 | rc = SQLITE_ERROR; |
| 6641 | } |
| 6642 | |
| 6643 | if( rc==SQLITE_OK ){ |
| 6644 | sqlite3changeset_op(pIter, &zTab, &nCol, &op, &bIndirect); |
| 6645 | rc = sessionChangesetFindTable(pGrp, zTab, pIter, &pTab); |
| 6646 | } |
| 6647 | |
| 6648 | if( rc==SQLITE_OK ){ |
| 6649 | rc = sessionOneChangeToHash( |
| 6650 | pGrp, pTab, op, bIndirect, nCol, aRec, nRec, bRebase |
| 6651 | ); |
| 6652 | } |
| 6653 | |
| 6654 | if( rc==SQLITE_OK ) rc = pIter->rc; |
| 6655 | return rc; |
| 6656 | } |
| 6657 | |
| 6658 | /* |
| 6659 | ** Add all changes in the changeset traversed by the iterator passed as |
| 6660 | ** the first argument to the changegroup hash tables. |
| 6661 | */ |
| 6662 | static int sessionChangesetToHash( |
| 6663 | sqlite3_changeset_iter *pIter, /* Iterator to read from */ |
| 6664 | sqlite3_changegroup *pGrp, /* Changegroup object to add changeset to */ |
| 6665 | int bRebase /* True if hash table is for rebasing */ |
| 6666 | ){ |
| 6667 | u8 *aRec; |
| 6668 | int nRec; |
| 6669 | int rc = SQLITE_OK; |
| 6670 | |
| 6671 | pIter->in.bNoDiscard = 1; |
| 6672 | while( SQLITE_ROW==(sessionChangesetNext(pIter, &aRec, &nRec, 0)) ){ |
| 6673 | if( bRebase && pIter->bPatchset ){ |
| 6674 | /* A patchset may not be used as a rebase */ |
| 6675 | rc = SQLITE_ERROR; |
| 6676 | }else{ |
| 6677 | rc = sessionOneChangeIterToHash(pGrp, pIter, bRebase); |
| 6678 | } |
| 6679 | if( rc!=SQLITE_OK ) break; |
| 6680 | } |
| 6681 | |
| 6682 | if( rc==SQLITE_OK ) rc = pIter->rc; |
| 6683 | return rc; |
| 6684 | } |
| 6685 | |
| 6686 | /* |
| 6687 | ** Serialize a changeset (or patchset) based on all changesets (or patchsets) |
| 6688 | ** added to the changegroup object passed as the first argument. |
| 6689 | ** |
| 6690 | ** If xOutput is not NULL, then the changeset/patchset is returned to the |
| 6691 | ** user via one or more calls to xOutput, as with the other streaming |
| 6692 | ** interfaces. |
| 6693 | ** |
| 6694 | ** Or, if xOutput is NULL, then (*ppOut) is populated with a pointer to a |
| 6695 | ** buffer containing the output changeset before this function returns. In |
| 6696 | ** this case (*pnOut) is set to the size of the output buffer in bytes. It |
| 6697 | ** is the responsibility of the caller to free the output buffer using |
| 6698 | ** sqlite3_free() when it is no longer required. |
| 6699 | ** |
| 6700 | ** If successful, SQLITE_OK is returned. Or, if an error occurs, an SQLite |
| 6701 | ** error code. If an error occurs and xOutput is NULL, (*ppOut) and (*pnOut) |
| 6702 | ** are both set to 0 before returning. |
| 6703 | */ |
| 6704 | static int sessionChangegroupOutput( |
| 6705 | sqlite3_changegroup *pGrp, |
| 6706 | int (*xOutput)(void *pOut, const void *pData, int nData), |
| 6707 | void *pOut, |
| 6708 | int *pnOut, |
| 6709 | void **ppOut |
| 6710 | ){ |
| 6711 | int rc = SQLITE_OK; |
| 6712 | SessionBuffer buf = {0, 0, 0}; |
| 6713 | SessionTable *pTab; |
| 6714 | assert( xOutput==0 || (ppOut==0 && pnOut==0) ); |
| 6715 | |
| 6716 | /* Create the serialized output changeset based on the contents of the |
| 6717 | ** hash tables attached to the SessionTable objects in list p->pList. |
| 6718 | */ |
| 6719 | for(pTab=pGrp->pList; rc==SQLITE_OK && pTab; pTab=pTab->pNext){ |
| 6720 | int i; |
| 6721 | if( pTab->nEntry==0 ) continue; |
| 6722 | |
| 6723 | sessionAppendTableHdr(&buf, pGrp->bPatch, pTab, &rc); |
| 6724 | for(i=0; i<pTab->nChange; i++){ |
| 6725 | SessionChange *p; |
| 6726 | for(p=pTab->apChange[i]; p; p=p->pNext){ |
| 6727 | sessionAppendByte(&buf, p->op, &rc); |
| 6728 | sessionAppendByte(&buf, p->bIndirect, &rc); |
| 6729 | sessionAppendBlob(&buf, p->aRecord, p->nRecord, &rc); |
| 6730 | if( rc==SQLITE_OK && xOutput && buf.nBuf>=sessions_strm_chunk_size ){ |
| 6731 | rc = xOutput(pOut, buf.aBuf, buf.nBuf); |
| 6732 | buf.nBuf = 0; |
| 6733 | } |
| 6734 | } |
| 6735 | } |
| 6736 | } |
| 6737 | |
| 6738 | if( rc==SQLITE_OK ){ |
| 6739 | if( xOutput ){ |
| 6740 | if( buf.nBuf>0 ) rc = xOutput(pOut, buf.aBuf, buf.nBuf); |
| 6741 | }else if( ppOut ){ |
| 6742 | *ppOut = buf.aBuf; |
| 6743 | if( pnOut ) *pnOut = buf.nBuf; |
| 6744 | buf.aBuf = 0; |
| 6745 | } |
| 6746 | } |
| 6747 | sqlite3_free(buf.aBuf); |
| 6748 | |
| 6749 | return rc; |
| 6750 | } |
| 6751 | |
| 6752 | /* |
| 6753 | ** Allocate a new, empty, sqlite3_changegroup. |
| 6754 | */ |
| 6755 | int sqlite3changegroup_new(sqlite3_changegroup **pp){ |
| 6756 | int rc = SQLITE_OK; /* Return code */ |
| 6757 | sqlite3_changegroup *p; /* New object */ |
| 6758 | p = (sqlite3_changegroup*)sqlite3_malloc(sizeof(sqlite3_changegroup)); |
| 6759 | if( p==0 ){ |
| 6760 | rc = SQLITE_NOMEM; |
| 6761 | }else{ |
| 6762 | memset(p, 0, sizeof(sqlite3_changegroup)); |
| 6763 | } |
| 6764 | *pp = p; |
| 6765 | return rc; |
| 6766 | } |
| 6767 | |
| 6768 | /* |
| 6769 | ** Configure a changegroup object. |
| 6770 | */ |
| 6771 | int sqlite3changegroup_config( |
| 6772 | sqlite3_changegroup *pGrp, |
| 6773 | int op, |
| 6774 | void *pArg |
| 6775 | ){ |
| 6776 | int rc = SQLITE_OK; |
| 6777 | |
| 6778 | switch( op ){ |
| 6779 | case SQLITE_CHANGEGROUP_CONFIG_PATCHSET: { |
| 6780 | int arg = *(int*)pArg; |
| 6781 | if( pGrp->pList==0 && arg>=0 ){ |
| 6782 | pGrp->bPatch = (arg>0); |
| 6783 | } |
| 6784 | *(int*)pArg = pGrp->bPatch; |
| 6785 | break; |
| 6786 | } |
| 6787 | default: |
| 6788 | rc = SQLITE_MISUSE; |
| 6789 | break; |
| 6790 | } |
| 6791 | |
| 6792 | return rc; |
| 6793 | } |
| 6794 | |
| 6795 | /* |
| 6796 | ** Provide a database schema to the changegroup object. |
| 6797 | */ |
| 6798 | int sqlite3changegroup_schema( |
| 6799 | sqlite3_changegroup *pGrp, |
| 6800 | sqlite3 *db, |
| 6801 | const char *zDb |
| 6802 | ){ |
| 6803 | int rc = SQLITE_OK; |
| 6804 | |
| 6805 | if( pGrp->pList || pGrp->db ){ |
| 6806 | /* Cannot add a schema after one or more calls to sqlite3changegroup_add(), |
| 6807 | ** or after sqlite3changegroup_schema() has already been called. */ |
| 6808 | rc = SQLITE_MISUSE; |
| 6809 | }else{ |
| 6810 | pGrp->zDb = sqlite3_mprintf("%s", zDb); |
| 6811 | if( pGrp->zDb==0 ){ |
| 6812 | rc = SQLITE_NOMEM; |
| 6813 | }else{ |
| 6814 | pGrp->db = db; |
| 6815 | } |
| 6816 | } |
| 6817 | return rc; |
| 6818 | } |
| 6819 | |
| 6820 | /* |
| 6821 | ** Add the changeset currently stored in buffer pData, size nData bytes, |
| 6822 | ** to changeset-group p. |
| 6823 | */ |
| 6824 | int sqlite3changegroup_add(sqlite3_changegroup *pGrp, int nData, void *pData){ |
| 6825 | sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */ |
| 6826 | int rc; /* Return code */ |
| 6827 | |
| 6828 | rc = sqlite3changeset_start(&pIter, nData, pData); |
| 6829 | if( rc==SQLITE_OK ){ |
| 6830 | rc = sessionChangesetToHash(pIter, pGrp, 0); |
| 6831 | } |
| 6832 | sqlite3changeset_finalize(pIter); |
| 6833 | return rc; |
| 6834 | } |
| 6835 | |
| 6836 | /* |
| 6837 | ** Add a single change to a changeset-group. |
| 6838 | */ |
| 6839 | int sqlite3changegroup_add_change( |
| 6840 | sqlite3_changegroup *pGrp, |
| 6841 | sqlite3_changeset_iter *pIter |
| 6842 | ){ |
| 6843 | int rc = SQLITE_OK; |
| 6844 | |
| 6845 | if( pIter->in.iCurrent==pIter->in.iNext |
| 6846 | || pIter->rc!=SQLITE_OK |
| 6847 | || pIter->bInvert |
| 6848 | ){ |
| 6849 | /* Iterator does not point to any valid entry or is an INVERT iterator. */ |
| 6850 | rc = SQLITE_ERROR; |
| 6851 | }else{ |
| 6852 | pIter->in.bNoDiscard = 1; |
| 6853 | rc = sessionOneChangeIterToHash(pGrp, pIter, 0); |
| 6854 | } |
| 6855 | return rc; |
| 6856 | } |
| 6857 | |
| 6858 | /* |
| 6859 | ** Obtain a buffer containing a changeset representing the concatenation |
| 6860 | ** of all changesets added to the group so far. |
| 6861 | */ |
| 6862 | int sqlite3changegroup_output( |
| 6863 | sqlite3_changegroup *pGrp, |
| 6864 | int *pnData, |
| 6865 | void **ppData |
| 6866 | ){ |
| 6867 | return sessionChangegroupOutput(pGrp, 0, 0, pnData, ppData); |
| 6868 | } |
| 6869 | |
| 6870 | /* |
| 6871 | ** Streaming versions of changegroup_add(). |
| 6872 | */ |
| 6873 | int sqlite3changegroup_add_strm( |
| 6874 | sqlite3_changegroup *pGrp, |
| 6875 | int (*xInput)(void *pIn, void *pData, int *pnData), |
| 6876 | void *pIn |
| 6877 | ){ |
| 6878 | sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */ |
| 6879 | int rc; /* Return code */ |
| 6880 | |
| 6881 | rc = sqlite3changeset_start_strm(&pIter, xInput, pIn); |
| 6882 | if( rc==SQLITE_OK ){ |
| 6883 | rc = sessionChangesetToHash(pIter, pGrp, 0); |
| 6884 | } |
| 6885 | sqlite3changeset_finalize(pIter); |
| 6886 | return rc; |
| 6887 | } |
| 6888 | |
| 6889 | /* |
| 6890 | ** Streaming versions of changegroup_output(). |
| 6891 | */ |
| 6892 | int sqlite3changegroup_output_strm( |
| 6893 | sqlite3_changegroup *pGrp, |
| 6894 | int (*xOutput)(void *pOut, const void *pData, int nData), |
| 6895 | void *pOut |
| 6896 | ){ |
| 6897 | return sessionChangegroupOutput(pGrp, xOutput, pOut, 0, 0); |
| 6898 | } |
| 6899 | |
| 6900 | /* |
| 6901 | ** Delete a changegroup object. |
| 6902 | */ |
| 6903 | void sqlite3changegroup_delete(sqlite3_changegroup *pGrp){ |
| 6904 | if( pGrp ){ |
| 6905 | int ii; |
| 6906 | for(ii=0; ii<pGrp->cd.nBufAlloc; ii++){ |
| 6907 | sqlite3_free(pGrp->cd.aBuf[ii].aBuf); |
| 6908 | } |
| 6909 | sqlite3_free(pGrp->cd.record.aBuf); |
| 6910 | sqlite3_free(pGrp->cd.aBuf); |
| 6911 | sqlite3_free(pGrp->zDb); |
| 6912 | sessionDeleteTable(0, pGrp->pList); |
| 6913 | sqlite3_free(pGrp->rec.aBuf); |
| 6914 | sqlite3_free(pGrp); |
| 6915 | } |
| 6916 | } |
| 6917 | |
| 6918 | /* |
| 6919 | ** Combine two changesets together. |
| 6920 | */ |
| 6921 | int sqlite3changeset_concat( |
| 6922 | int nLeft, /* Number of bytes in lhs input */ |
| 6923 | void *pLeft, /* Lhs input changeset */ |
| 6924 | int nRight /* Number of bytes in rhs input */, |
| 6925 | void *pRight, /* Rhs input changeset */ |
| 6926 | int *pnOut, /* OUT: Number of bytes in output changeset */ |
| 6927 | void **ppOut /* OUT: changeset (left <concat> right) */ |
| 6928 | ){ |
| 6929 | sqlite3_changegroup *pGrp; |
| 6930 | int rc; |
| 6931 | |
| 6932 | rc = sqlite3changegroup_new(&pGrp); |
| 6933 | if( rc==SQLITE_OK ){ |
| 6934 | rc = sqlite3changegroup_add(pGrp, nLeft, pLeft); |
| 6935 | } |
| 6936 | if( rc==SQLITE_OK ){ |
| 6937 | rc = sqlite3changegroup_add(pGrp, nRight, pRight); |
| 6938 | } |
| 6939 | if( rc==SQLITE_OK ){ |
| 6940 | rc = sqlite3changegroup_output(pGrp, pnOut, ppOut); |
| 6941 | } |
| 6942 | sqlite3changegroup_delete(pGrp); |
| 6943 | |
| 6944 | return rc; |
| 6945 | } |
| 6946 | |
| 6947 | /* |
| 6948 | ** Streaming version of sqlite3changeset_concat(). |
| 6949 | */ |
| 6950 | int sqlite3changeset_concat_strm( |
| 6951 | int (*xInputA)(void *pIn, void *pData, int *pnData), |
| 6952 | void *pInA, |
| 6953 | int (*xInputB)(void *pIn, void *pData, int *pnData), |
| 6954 | void *pInB, |
| 6955 | int (*xOutput)(void *pOut, const void *pData, int nData), |
| 6956 | void *pOut |
| 6957 | ){ |
| 6958 | sqlite3_changegroup *pGrp; |
| 6959 | int rc; |
| 6960 | |
| 6961 | rc = sqlite3changegroup_new(&pGrp); |
| 6962 | if( rc==SQLITE_OK ){ |
| 6963 | rc = sqlite3changegroup_add_strm(pGrp, xInputA, pInA); |
| 6964 | } |
| 6965 | if( rc==SQLITE_OK ){ |
| 6966 | rc = sqlite3changegroup_add_strm(pGrp, xInputB, pInB); |
| 6967 | } |
| 6968 | if( rc==SQLITE_OK ){ |
| 6969 | rc = sqlite3changegroup_output_strm(pGrp, xOutput, pOut); |
| 6970 | } |
| 6971 | sqlite3changegroup_delete(pGrp); |
| 6972 | |
| 6973 | return rc; |
| 6974 | } |
| 6975 | |
| 6976 | /* |
| 6977 | ** Changeset rebaser handle. |
| 6978 | */ |
| 6979 | struct sqlite3_rebaser { |
| 6980 | sqlite3_changegroup grp; /* Hash table */ |
| 6981 | }; |
| 6982 | |
| 6983 | /* |
| 6984 | ** Buffers a1 and a2 must both contain a sessions module record nCol |
| 6985 | ** fields in size. This function appends an nCol sessions module |
| 6986 | ** record to buffer pBuf that is a copy of a1, except that for |
| 6987 | ** each field that is undefined in a1[], swap in the field from a2[]. |
| 6988 | */ |
| 6989 | static void sessionAppendRecordMerge( |
| 6990 | SessionBuffer *pBuf, /* Buffer to append to */ |
| 6991 | int nCol, /* Number of columns in each record */ |
| 6992 | u8 *a1, int n1, /* Record 1 */ |
| 6993 | u8 *a2, int n2, /* Record 2 */ |
| 6994 | int *pRc /* IN/OUT: error code */ |
| 6995 | ){ |
| 6996 | u8 *a1Eof = &a1[n1]; |
| 6997 | u8 *a2Eof = &a2[n2]; |
| 6998 | |
| 6999 | sessionBufferGrow(pBuf, (i64)n1+n2, pRc); |
| 7000 | if( *pRc==SQLITE_OK ){ |
| 7001 | int i; |
| 7002 | u8 *pOut = &pBuf->aBuf[pBuf->nBuf]; |
| 7003 | for(i=0; i<nCol; i++){ |
| 7004 | int nn1 = (a1<a1Eof ? sessionSerialLen(a1) : 0); |
| 7005 | int nn2 = (a2<a2Eof ? sessionSerialLen(a2) : 0); |
| 7006 | if( nn1==0 || (nn2>0 && (*a1==0 || *a1==0xFF)) ){ |
| 7007 | memcpy(pOut, a2, nn2); |
| 7008 | pOut += nn2; |
| 7009 | }else{ |
| 7010 | memcpy(pOut, a1, nn1); |
| 7011 | pOut += nn1; |
| 7012 | } |
| 7013 | a1 += nn1; |
| 7014 | a2 += nn2; |
| 7015 | } |
| 7016 | |
| 7017 | pBuf->nBuf = pOut-pBuf->aBuf; |
| 7018 | assert( pBuf->nBuf<=pBuf->nAlloc ); |
| 7019 | } |
| 7020 | } |
| 7021 | |
| 7022 | /* |
| 7023 | ** This function is called when rebasing a local UPDATE change against one |
| 7024 | ** or more remote UPDATE changes. The aRec/nRec buffer contains the current |
| 7025 | ** old.* and new.* records for the change. The rebase buffer (a single |
| 7026 | ** record) is in aChange/nChange. The rebased change is appended to buffer |
| 7027 | ** pBuf. |
| 7028 | ** |
| 7029 | ** Rebasing the UPDATE involves: |
| 7030 | ** |
| 7031 | ** * Removing any changes to fields for which the corresponding field |
| 7032 | ** in the rebase buffer is set to "replaced" (type 0xFF). If this |
| 7033 | ** means the UPDATE change updates no fields, nothing is appended |
| 7034 | ** to the output buffer. |
| 7035 | ** |
| 7036 | ** * For each field modified by the local change for which the |
| 7037 | ** corresponding field in the rebase buffer is not "undefined" (0x00) |
| 7038 | ** or "replaced" (0xFF), the old.* value is replaced by the value |
| 7039 | ** in the rebase buffer. |
| 7040 | */ |
| 7041 | static void sessionAppendPartialUpdate( |
| 7042 | SessionBuffer *pBuf, /* Append record here */ |
| 7043 | sqlite3_changeset_iter *pIter, /* Iterator pointed at local change */ |
| 7044 | u8 *aRec, int nRec, /* Local change */ |
| 7045 | u8 *aChange, int nChange, /* Record to rebase against */ |
| 7046 | int *pRc /* IN/OUT: Return Code */ |
| 7047 | ){ |
| 7048 | sessionBufferGrow(pBuf, (i64)2+nRec+nChange, pRc); |
| 7049 | if( *pRc==SQLITE_OK ){ |
| 7050 | int bData = 0; |
| 7051 | u8 *pOut = &pBuf->aBuf[pBuf->nBuf]; |
| 7052 | int i; |
| 7053 | u8 *a1 = aRec; |
| 7054 | u8 *a2 = aChange; |
| 7055 | u8 *a2Eof = &a2[nChange]; |
| 7056 | |
| 7057 | *pOut++ = SQLITE_UPDATE; |
| 7058 | *pOut++ = pIter->bIndirect; |
| 7059 | for(i=0; i<pIter->nCol; i++){ |
| 7060 | int n1 = sessionSerialLen(a1); |
| 7061 | int n2 = (a2>=a2Eof) ? 0 : sessionSerialLen(a2); |
| 7062 | if( n2<=0 || pIter->abPK[i] || a2[0]==0 ){ |
| 7063 | if( !pIter->abPK[i] && a1[0] ) bData = 1; |
| 7064 | memcpy(pOut, a1, n1); |
| 7065 | pOut += n1; |
| 7066 | }else if( a2[0]!=0xFF && a1[0] ){ |
| 7067 | bData = 1; |
| 7068 | memcpy(pOut, a2, n2); |
| 7069 | pOut += n2; |
| 7070 | }else{ |
| 7071 | *pOut++ = '\0'; |
| 7072 | } |
| 7073 | a1 += n1; |
| 7074 | a2 += n2; |
| 7075 | } |
| 7076 | if( bData ){ |
| 7077 | a2 = aChange; |
| 7078 | for(i=0; i<pIter->nCol; i++){ |
| 7079 | int n1 = sessionSerialLen(a1); |
| 7080 | int n2 = (a2>=a2Eof) ? 0 : sessionSerialLen(a2); |
| 7081 | if( pIter->abPK[i] || n2<=0 || a2[0]!=0xFF ){ |
| 7082 | memcpy(pOut, a1, n1); |
| 7083 | pOut += n1; |
| 7084 | }else{ |
| 7085 | *pOut++ = '\0'; |
| 7086 | } |
| 7087 | a1 += n1; |
| 7088 | a2 += n2; |
| 7089 | } |
| 7090 | pBuf->nBuf = (pOut - pBuf->aBuf); |
| 7091 | } |
| 7092 | } |
| 7093 | } |
| 7094 | |
| 7095 | /* |
| 7096 | ** pIter is configured to iterate through a changeset. This function rebases |
| 7097 | ** that changeset according to the current configuration of the rebaser |
| 7098 | ** object passed as the first argument. If no error occurs and argument xOutput |
| 7099 | ** is not NULL, then the changeset is returned to the caller by invoking |
| 7100 | ** xOutput zero or more times and SQLITE_OK returned. Or, if xOutput is NULL, |
| 7101 | ** then (*ppOut) is set to point to a buffer containing the rebased changeset |
| 7102 | ** before this function returns. In this case (*pnOut) is set to the size of |
| 7103 | ** the buffer in bytes. It is the responsibility of the caller to eventually |
| 7104 | ** free the (*ppOut) buffer using sqlite3_free(). |
| 7105 | ** |
| 7106 | ** If an error occurs, an SQLite error code is returned. If ppOut and |
| 7107 | ** pnOut are not NULL, then the two output parameters are set to 0 before |
| 7108 | ** returning. |
| 7109 | */ |
| 7110 | static int sessionRebase( |
| 7111 | sqlite3_rebaser *p, /* Rebaser hash table */ |
| 7112 | sqlite3_changeset_iter *pIter, /* Input data */ |
| 7113 | int (*xOutput)(void *pOut, const void *pData, int nData), |
| 7114 | void *pOut, /* Context for xOutput callback */ |
| 7115 | int *pnOut, /* OUT: Number of bytes in output changeset */ |
| 7116 | void **ppOut /* OUT: Inverse of pChangeset */ |
| 7117 | ){ |
| 7118 | int rc = SQLITE_OK; |
| 7119 | u8 *aRec = 0; |
| 7120 | int nRec = 0; |
| 7121 | int bNew = 0; |
| 7122 | SessionTable *pTab = 0; |
| 7123 | SessionBuffer sOut = {0,0,0}; |
| 7124 | |
| 7125 | while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec, &bNew) ){ |
| 7126 | SessionChange *pChange = 0; |
| 7127 | int bDone = 0; |
| 7128 | |
| 7129 | if( bNew ){ |
| 7130 | const char *zTab = pIter->zTab; |
| 7131 | for(pTab=p->grp.pList; pTab; pTab=pTab->pNext){ |
| 7132 | if( 0==sqlite3_stricmp(pTab->zName, zTab) ) break; |
| 7133 | } |
| 7134 | bNew = 0; |
| 7135 | |
| 7136 | /* A patchset may not be rebased */ |
| 7137 | if( pIter->bPatchset ){ |
| 7138 | rc = SQLITE_ERROR; |
| 7139 | } |
| 7140 | if( pTab && pTab->nCol>pIter->nCol ){ |
| 7141 | rc = SQLITE_SCHEMA; |
| 7142 | } |
| 7143 | |
| 7144 | /* Append a table header to the output for this new table */ |
| 7145 | sessionAppendByte(&sOut, pIter->bPatchset ? 'P' : 'T', &rc); |
| 7146 | sessionAppendVarint(&sOut, pIter->nCol, &rc); |
| 7147 | sessionAppendBlob(&sOut, pIter->abPK, pIter->nCol, &rc); |
| 7148 | sessionAppendBlob(&sOut,(u8*)pIter->zTab,(int)strlen(pIter->zTab)+1,&rc); |
| 7149 | } |
| 7150 | |
| 7151 | if( pTab && rc==SQLITE_OK ){ |
| 7152 | int iHash = sessionChangeHash(pTab, 0, aRec, pTab->nChange); |
| 7153 | |
| 7154 | for(pChange=pTab->apChange[iHash]; pChange; pChange=pChange->pNext){ |
| 7155 | if( sessionChangeEqual(pTab, 0, aRec, 0, pChange->aRecord) ){ |
| 7156 | break; |
| 7157 | } |
| 7158 | } |
| 7159 | } |
| 7160 | |
| 7161 | if( pChange ){ |
| 7162 | assert( pChange->op==SQLITE_DELETE || pChange->op==SQLITE_INSERT ); |
| 7163 | switch( pIter->op ){ |
| 7164 | case SQLITE_INSERT: |
| 7165 | if( pChange->op==SQLITE_INSERT ){ |
| 7166 | bDone = 1; |
| 7167 | if( pChange->bIndirect==0 ){ |
| 7168 | sessionAppendByte(&sOut, SQLITE_UPDATE, &rc); |
| 7169 | sessionAppendByte(&sOut, pIter->bIndirect, &rc); |
| 7170 | sessionAppendBlob(&sOut, pChange->aRecord, pChange->nRecord, &rc); |
| 7171 | sessionAppendBlob(&sOut, aRec, nRec, &rc); |
| 7172 | } |
| 7173 | } |
| 7174 | break; |
| 7175 | |
| 7176 | case SQLITE_UPDATE: |
| 7177 | bDone = 1; |
| 7178 | if( pChange->op==SQLITE_DELETE ){ |
| 7179 | if( pChange->bIndirect==0 ){ |
| 7180 | u8 *pCsr = aRec; |
| 7181 | sessionSkipRecord(&pCsr, pIter->nCol); |
| 7182 | sessionAppendByte(&sOut, SQLITE_INSERT, &rc); |
| 7183 | sessionAppendByte(&sOut, pIter->bIndirect, &rc); |
| 7184 | sessionAppendRecordMerge(&sOut, pIter->nCol, |
| 7185 | pCsr, nRec-(pCsr-aRec), |
| 7186 | pChange->aRecord, pChange->nRecord, &rc |
| 7187 | ); |
| 7188 | } |
| 7189 | }else{ |
| 7190 | sessionAppendPartialUpdate(&sOut, pIter, |
| 7191 | aRec, nRec, pChange->aRecord, pChange->nRecord, &rc |
| 7192 | ); |
| 7193 | } |
| 7194 | break; |
| 7195 | |
| 7196 | default: |
| 7197 | assert( pIter->op==SQLITE_DELETE ); |
| 7198 | bDone = 1; |
| 7199 | if( pChange->op==SQLITE_INSERT ){ |
| 7200 | sessionAppendByte(&sOut, SQLITE_DELETE, &rc); |
| 7201 | sessionAppendByte(&sOut, pIter->bIndirect, &rc); |
| 7202 | sessionAppendRecordMerge(&sOut, pIter->nCol, |
| 7203 | pChange->aRecord, pChange->nRecord, aRec, nRec, &rc |
| 7204 | ); |
| 7205 | } |
| 7206 | break; |
| 7207 | } |
| 7208 | } |
| 7209 | |
| 7210 | if( bDone==0 ){ |
| 7211 | sessionAppendByte(&sOut, pIter->op, &rc); |
| 7212 | sessionAppendByte(&sOut, pIter->bIndirect, &rc); |
| 7213 | sessionAppendBlob(&sOut, aRec, nRec, &rc); |
| 7214 | } |
| 7215 | if( rc==SQLITE_OK && xOutput && sOut.nBuf>sessions_strm_chunk_size ){ |
| 7216 | rc = xOutput(pOut, sOut.aBuf, sOut.nBuf); |
| 7217 | sOut.nBuf = 0; |
| 7218 | } |
| 7219 | if( rc ) break; |
| 7220 | } |
| 7221 | |
| 7222 | if( rc!=SQLITE_OK ){ |
| 7223 | sqlite3_free(sOut.aBuf); |
| 7224 | memset(&sOut, 0, sizeof(sOut)); |
| 7225 | } |
| 7226 | |
| 7227 | if( rc==SQLITE_OK ){ |
| 7228 | if( xOutput ){ |
| 7229 | if( sOut.nBuf>0 ){ |
| 7230 | rc = xOutput(pOut, sOut.aBuf, sOut.nBuf); |
| 7231 | } |
| 7232 | }else if( ppOut ){ |
| 7233 | *ppOut = (void*)sOut.aBuf; |
| 7234 | *pnOut = sOut.nBuf; |
| 7235 | sOut.aBuf = 0; |
| 7236 | } |
| 7237 | } |
| 7238 | sqlite3_free(sOut.aBuf); |
| 7239 | if( rc==SQLITE_OK ) rc = pIter->rc; |
| 7240 | return rc; |
| 7241 | } |
| 7242 | |
| 7243 | /* |
| 7244 | ** Create a new rebaser object. |
| 7245 | */ |
| 7246 | int sqlite3rebaser_create(sqlite3_rebaser **ppNew){ |
| 7247 | int rc = SQLITE_OK; |
| 7248 | sqlite3_rebaser *pNew; |
| 7249 | |
| 7250 | pNew = sqlite3_malloc(sizeof(sqlite3_rebaser)); |
| 7251 | if( pNew==0 ){ |
| 7252 | rc = SQLITE_NOMEM; |
| 7253 | }else{ |
| 7254 | memset(pNew, 0, sizeof(sqlite3_rebaser)); |
| 7255 | } |
| 7256 | *ppNew = pNew; |
| 7257 | return rc; |
| 7258 | } |
| 7259 | |
| 7260 | /* |
| 7261 | ** Call this one or more times to configure a rebaser. |
| 7262 | */ |
| 7263 | int sqlite3rebaser_configure( |
| 7264 | sqlite3_rebaser *p, |
| 7265 | int nRebase, const void *pRebase |
| 7266 | ){ |
| 7267 | int rc; /* Return code */ |
| 7268 | sqlite3_changeset_iter *pIter = 0; /* Iterator opened on pData/nData */ |
| 7269 | rc = sqlite3changeset_start(&pIter, nRebase, (void*)pRebase); |
| 7270 | if( rc==SQLITE_OK ){ |
| 7271 | rc = sessionChangesetToHash(pIter, &p->grp, 1); |
| 7272 | } |
| 7273 | sqlite3changeset_finalize(pIter); |
| 7274 | return rc; |
| 7275 | } |
| 7276 | |
| 7277 | /* |
| 7278 | ** Rebase a changeset according to current rebaser configuration |
| 7279 | */ |
| 7280 | int sqlite3rebaser_rebase( |
| 7281 | sqlite3_rebaser *p, |
| 7282 | int nIn, const void *pIn, |
| 7283 | int *pnOut, void **ppOut |
| 7284 | ){ |
| 7285 | sqlite3_changeset_iter *pIter = 0; /* Iterator to skip through input */ |
| 7286 | int rc = sqlite3changeset_start(&pIter, nIn, (void*)pIn); |
| 7287 | |
| 7288 | if( rc==SQLITE_OK ){ |
| 7289 | rc = sessionRebase(p, pIter, 0, 0, pnOut, ppOut); |
| 7290 | sqlite3changeset_finalize(pIter); |
| 7291 | } |
| 7292 | |
| 7293 | return rc; |
| 7294 | } |
| 7295 | |
| 7296 | /* |
| 7297 | ** Rebase a changeset according to current rebaser configuration |
| 7298 | */ |
| 7299 | int sqlite3rebaser_rebase_strm( |
| 7300 | sqlite3_rebaser *p, |
| 7301 | int (*xInput)(void *pIn, void *pData, int *pnData), |
| 7302 | void *pIn, |
| 7303 | int (*xOutput)(void *pOut, const void *pData, int nData), |
| 7304 | void *pOut |
| 7305 | ){ |
| 7306 | sqlite3_changeset_iter *pIter = 0; /* Iterator to skip through input */ |
| 7307 | int rc = sqlite3changeset_start_strm(&pIter, xInput, pIn); |
| 7308 | |
| 7309 | if( rc==SQLITE_OK ){ |
| 7310 | rc = sessionRebase(p, pIter, xOutput, pOut, 0, 0); |
| 7311 | sqlite3changeset_finalize(pIter); |
| 7312 | } |
| 7313 | |
| 7314 | return rc; |
| 7315 | } |
| 7316 | |
| 7317 | /* |
| 7318 | ** Destroy a rebaser object |
| 7319 | */ |
| 7320 | void sqlite3rebaser_delete(sqlite3_rebaser *p){ |
| 7321 | if( p ){ |
| 7322 | sessionDeleteTable(0, p->grp.pList); |
| 7323 | sqlite3_free(p->grp.rec.aBuf); |
| 7324 | sqlite3_free(p); |
| 7325 | } |
| 7326 | } |
| 7327 | |
| 7328 | /* |
| 7329 | ** Global configuration |
| 7330 | */ |
| 7331 | int sqlite3session_config(int op, void *pArg){ |
| 7332 | int rc = SQLITE_OK; |
| 7333 | switch( op ){ |
| 7334 | case SQLITE_SESSION_CONFIG_STRMSIZE: { |
| 7335 | int *pInt = (int*)pArg; |
| 7336 | if( *pInt>0 ){ |
| 7337 | sessions_strm_chunk_size = *pInt; |
| 7338 | } |
| 7339 | *pInt = sessions_strm_chunk_size; |
| 7340 | break; |
| 7341 | } |
| 7342 | default: |
| 7343 | rc = SQLITE_MISUSE; |
| 7344 | break; |
| 7345 | } |
| 7346 | return rc; |
| 7347 | } |
| 7348 | |
| 7349 | /* |
| 7350 | ** Begin adding a change to a changegroup object. |
| 7351 | */ |
| 7352 | int sqlite3changegroup_change_begin( |
| 7353 | sqlite3_changegroup *pGrp, |
| 7354 | int eOp, |
| 7355 | const char *zTab, |
| 7356 | int bIndirect, |
| 7357 | char **pzErr |
| 7358 | ){ |
| 7359 | SessionTable *pTab = 0; |
| 7360 | int rc = SQLITE_OK; |
| 7361 | |
| 7362 | if( pGrp->cd.pTab ){ |
| 7363 | rc = SQLITE_MISUSE; |
| 7364 | }else if( eOp!=SQLITE_INSERT && eOp!=SQLITE_UPDATE && eOp!=SQLITE_DELETE ){ |
| 7365 | rc = SQLITE_ERROR; |
| 7366 | }else{ |
| 7367 | rc = sessionChangesetFindTable(pGrp, zTab, 0, &pTab); |
| 7368 | if( pTab==0 && pzErr ){ |
| 7369 | *pzErr = sqlite3_mprintf("no such table: %s", zTab); |
| 7370 | } |
| 7371 | } |
| 7372 | if( rc==SQLITE_OK ){ |
| 7373 | int nReq = pTab->nCol * (eOp==SQLITE_UPDATE ? 2 : 1); |
| 7374 | |
| 7375 | if( pGrp->cd.nBufAlloc<nReq ){ |
| 7376 | SessionBuffer *aBuf = (SessionBuffer*)sqlite3_realloc( |
| 7377 | pGrp->cd.aBuf, nReq * sizeof(SessionBuffer) |
| 7378 | ); |
| 7379 | if( aBuf==0 ){ |
| 7380 | rc = SQLITE_NOMEM; |
| 7381 | }else{ |
| 7382 | memset(&aBuf[pGrp->cd.nBufAlloc], 0, |
| 7383 | sizeof(SessionBuffer) * (nReq - pGrp->cd.nBufAlloc) |
| 7384 | ); |
| 7385 | pGrp->cd.aBuf = aBuf; |
| 7386 | pGrp->cd.nBufAlloc = nReq; |
| 7387 | } |
| 7388 | } |
| 7389 | |
| 7390 | /* Only mark a change as under construction once the column buffers |
| 7391 | ** have been allocated. */ |
| 7392 | if( rc==SQLITE_OK ){ |
| 7393 | pGrp->cd.pTab = pTab; |
| 7394 | pGrp->cd.eOp = eOp; |
| 7395 | pGrp->cd.bIndirect = bIndirect; |
| 7396 | } |
| 7397 | |
| 7398 | #ifdef SQLITE_DEBUG |
| 7399 | { |
| 7400 | /* Assert that all column values are currently undefined */ |
| 7401 | int ii; |
| 7402 | for(ii=0; ii<pGrp->cd.nBufAlloc; ii++){ |
| 7403 | assert( pGrp->cd.aBuf[ii].nBuf==0 ); |
| 7404 | } |
| 7405 | } |
| 7406 | #endif |
| 7407 | } |
| 7408 | |
| 7409 | return rc; |
| 7410 | } |
| 7411 | |
| 7412 | /* |
| 7413 | ** This function does processing common to the _change_int64(), _change_text() |
| 7414 | ** and other similar APIs. |
| 7415 | */ |
| 7416 | static int checkChangeParams( |
| 7417 | sqlite3_changegroup *pGrp, |
| 7418 | int bNew, |
| 7419 | int iCol, |
| 7420 | sqlite3_int64 nReq, |
| 7421 | SessionBuffer **ppBuf |
| 7422 | ){ |
| 7423 | int rc = SQLITE_OK; |
| 7424 | if( pGrp->cd.pTab==0 ){ |
| 7425 | rc = SQLITE_MISUSE; |
| 7426 | }else if( iCol<0 || iCol>=pGrp->cd.pTab->nCol ){ |
| 7427 | rc = SQLITE_RANGE; |
| 7428 | }else if( |
| 7429 | (bNew && pGrp->cd.eOp==SQLITE_DELETE) |
| 7430 | || (!bNew && pGrp->cd.eOp==SQLITE_INSERT) |
| 7431 | ){ |
| 7432 | rc = SQLITE_ERROR; |
| 7433 | }else{ |
| 7434 | SessionBuffer *pBuf = &pGrp->cd.aBuf[iCol]; |
| 7435 | if( pGrp->cd.eOp==SQLITE_UPDATE && bNew ){ |
| 7436 | pBuf += pGrp->cd.pTab->nCol; |
| 7437 | } |
| 7438 | pBuf->nBuf = 0; |
| 7439 | if( sessionBufferGrow(pBuf, nReq, &rc)==0 ){ |
| 7440 | pBuf->nBuf = (int)nReq; |
| 7441 | } |
| 7442 | *ppBuf = pBuf; |
| 7443 | } |
| 7444 | return rc; |
| 7445 | } |
| 7446 | |
| 7447 | /* |
| 7448 | ** Configure the change currently under construction with an integer value. |
| 7449 | */ |
| 7450 | int sqlite3changegroup_change_int64( |
| 7451 | sqlite3_changegroup *pGrp, |
| 7452 | int bNew, |
| 7453 | int iCol, |
| 7454 | sqlite3_int64 iVal |
| 7455 | ){ |
| 7456 | int rc = SQLITE_OK; |
| 7457 | SessionBuffer *pBuf = 0; |
| 7458 | |
| 7459 | if( SQLITE_OK!=(rc = checkChangeParams(pGrp, bNew, iCol, 9, &pBuf)) ){ |
| 7460 | return rc; |
| 7461 | } |
| 7462 | |
| 7463 | pBuf->aBuf[0] = SQLITE_INTEGER; |
| 7464 | sessionPutI64(&pBuf->aBuf[1], iVal); |
| 7465 | return SQLITE_OK; |
| 7466 | } |
| 7467 | |
| 7468 | /* |
| 7469 | ** Configure the change currently under construction with a null value. |
| 7470 | */ |
| 7471 | int sqlite3changegroup_change_null( |
| 7472 | sqlite3_changegroup *pGrp, |
| 7473 | int bNew, |
| 7474 | int iCol |
| 7475 | ){ |
| 7476 | int rc = SQLITE_OK; |
| 7477 | SessionBuffer *pBuf = 0; |
| 7478 | |
| 7479 | if( SQLITE_OK!=(rc = checkChangeParams(pGrp, bNew, iCol, 1, &pBuf)) ){ |
| 7480 | return rc; |
| 7481 | } |
| 7482 | |
| 7483 | pBuf->aBuf[0] = SQLITE_NULL; |
| 7484 | return SQLITE_OK; |
| 7485 | } |
| 7486 | |
| 7487 | /* |
| 7488 | ** Configure the change currently under construction with a real value. |
| 7489 | */ |
| 7490 | int sqlite3changegroup_change_double( |
| 7491 | sqlite3_changegroup *pGrp, |
| 7492 | int bNew, |
| 7493 | int iCol, |
| 7494 | double fVal |
| 7495 | ){ |
| 7496 | int rc = SQLITE_OK; |
| 7497 | SessionBuffer *pBuf = 0; |
| 7498 | |
| 7499 | if( SQLITE_OK!=(rc = checkChangeParams(pGrp, bNew, iCol, 9, &pBuf)) ){ |
| 7500 | return rc; |
| 7501 | } |
| 7502 | |
| 7503 | pBuf->aBuf[0] = SQLITE_FLOAT; |
| 7504 | sessionPutDouble(&pBuf->aBuf[1], fVal); |
| 7505 | return SQLITE_OK; |
| 7506 | } |
| 7507 | |
| 7508 | /* |
| 7509 | ** Configure the change currently under construction with a text value. |
| 7510 | */ |
| 7511 | int sqlite3changegroup_change_text( |
| 7512 | sqlite3_changegroup *pGrp, |
| 7513 | int bNew, |
| 7514 | int iCol, |
| 7515 | const char *pVal, |
| 7516 | int nVal |
| 7517 | ){ |
| 7518 | sqlite3_int64 nText = nVal>=0 ? nVal : strlen(pVal); |
| 7519 | sqlite3_int64 nByte = 1 + sessionVarintLen(nText) + nText; |
| 7520 | int rc = SQLITE_OK; |
| 7521 | SessionBuffer *pBuf = 0; |
| 7522 | |
| 7523 | if( SQLITE_OK!=(rc = checkChangeParams(pGrp, bNew, iCol, nByte, &pBuf)) ){ |
| 7524 | return rc; |
| 7525 | } |
| 7526 | |
| 7527 | pBuf->aBuf[0] = SQLITE_TEXT; |
| 7528 | pBuf->nBuf = (1 + sessionVarintPut(&pBuf->aBuf[1], nText)); |
| 7529 | memcpy(&pBuf->aBuf[pBuf->nBuf], pVal, nText); |
| 7530 | pBuf->nBuf += nText; |
| 7531 | |
| 7532 | return SQLITE_OK; |
| 7533 | } |
| 7534 | |
| 7535 | /* |
| 7536 | ** Configure the change currently under construction with a blob value. |
| 7537 | */ |
| 7538 | int sqlite3changegroup_change_blob( |
| 7539 | sqlite3_changegroup *pGrp, |
| 7540 | int bNew, |
| 7541 | int iCol, |
| 7542 | const void *pVal, |
| 7543 | int nVal |
| 7544 | ){ |
| 7545 | sqlite3_int64 nByte = 1 + sessionVarintLen(nVal) + (i64)nVal; |
| 7546 | int rc = SQLITE_OK; |
| 7547 | SessionBuffer *pBuf = 0; |
| 7548 | |
| 7549 | if( SQLITE_OK!=(rc = checkChangeParams(pGrp, bNew, iCol, nByte, &pBuf)) ){ |
| 7550 | return rc; |
| 7551 | } |
| 7552 | |
| 7553 | pBuf->aBuf[0] = SQLITE_BLOB; |
| 7554 | pBuf->nBuf = (1 + sessionVarintPut(&pBuf->aBuf[1], nVal)); |
| 7555 | memcpy(&pBuf->aBuf[pBuf->nBuf], pVal, nVal); |
| 7556 | pBuf->nBuf += nVal; |
| 7557 | |
| 7558 | return SQLITE_OK; |
| 7559 | } |
| 7560 | |
| 7561 | /* |
| 7562 | ** Finish any change currently being constructed by the changegroup object. |
| 7563 | */ |
| 7564 | int sqlite3changegroup_change_finish( |
| 7565 | sqlite3_changegroup *pGrp, |
| 7566 | int bDiscard, |
| 7567 | char **pzErr |
| 7568 | ){ |
| 7569 | int rc = SQLITE_OK; |
| 7570 | char *zErr = 0; |
| 7571 | if( pGrp->cd.pTab ){ |
| 7572 | SessionBuffer *aBuf = pGrp->cd.aBuf; |
| 7573 | int ii; |
| 7574 | |
| 7575 | if( bDiscard==0 ){ |
| 7576 | int nBuf = pGrp->cd.pTab->nCol; |
| 7577 | u8 eUndef = SQLITE_NULL; |
| 7578 | if( pGrp->cd.eOp==SQLITE_UPDATE ){ |
| 7579 | for(ii=0; ii<nBuf; ii++){ |
| 7580 | if( pGrp->cd.pTab->abPK[ii] ){ |
| 7581 | if( aBuf[ii].nBuf<=1 ){ |
| 7582 | zErr = sqlite3_mprintf( |
| 7583 | "invalid change: %s value in PK of old.* record", |
| 7584 | aBuf[ii].nBuf==1 ? "null" : "undefined" |
| 7585 | ); |
| 7586 | rc = SQLITE_ERROR; |
| 7587 | break; |
| 7588 | }else if( aBuf[ii + nBuf].nBuf>0 ){ |
| 7589 | zErr = sqlite3_mprintf( |
| 7590 | "invalid change: defined value in PK of new.* record" |
| 7591 | ); |
| 7592 | rc = SQLITE_ERROR; |
| 7593 | break; |
| 7594 | } |
| 7595 | }else |
| 7596 | if( pGrp->bPatch==0 && (aBuf[ii].nBuf>0)!=(aBuf[ii+nBuf].nBuf>0) ){ |
| 7597 | zErr = sqlite3_mprintf( |
| 7598 | "invalid change: column %d " |
| 7599 | "- old.* value is %sdefined but new.* is %sdefined", |
| 7600 | ii, aBuf[ii].nBuf ? "" : "un", aBuf[ii+nBuf].nBuf ? "" : "un" |
| 7601 | ); |
| 7602 | rc = SQLITE_ERROR; |
| 7603 | break; |
| 7604 | } |
| 7605 | } |
| 7606 | eUndef = 0x00; |
| 7607 | if( pGrp->bPatch==0 ) nBuf = nBuf * 2; |
| 7608 | }else{ |
| 7609 | for(ii=0; ii<nBuf; ii++){ |
| 7610 | int isPK = pGrp->cd.pTab->abPK[ii]; |
| 7611 | if( (pGrp->cd.eOp==SQLITE_INSERT || pGrp->bPatch==0 || isPK) |
| 7612 | && aBuf[ii].nBuf==0 |
| 7613 | ){ |
| 7614 | zErr = sqlite3_mprintf( |
| 7615 | "invalid change: column %d is undefined", ii |
| 7616 | ); |
| 7617 | rc = SQLITE_ERROR; |
| 7618 | break; |
| 7619 | } |
| 7620 | if( aBuf[ii].nBuf==1 && isPK ){ |
| 7621 | zErr = sqlite3_mprintf( |
| 7622 | "invalid change: null value in PK" |
| 7623 | ); |
| 7624 | rc = SQLITE_ERROR; |
| 7625 | break; |
| 7626 | } |
| 7627 | } |
| 7628 | } |
| 7629 | |
| 7630 | pGrp->cd.record.nBuf = 0; |
| 7631 | for(ii=0; ii<nBuf; ii++){ |
| 7632 | SessionBuffer *p = &pGrp->cd.aBuf[ii]; |
| 7633 | if( pGrp->bPatch ){ |
| 7634 | if( pGrp->cd.pTab->abPK[ii]==0 ){ |
| 7635 | if( pGrp->cd.eOp==SQLITE_UPDATE ){ |
| 7636 | p += pGrp->cd.pTab->nCol; |
| 7637 | }else if( pGrp->cd.eOp==SQLITE_DELETE ){ |
| 7638 | continue; |
| 7639 | } |
| 7640 | } |
| 7641 | } |
| 7642 | if( 0==sessionBufferGrow(&pGrp->cd.record, p->nBuf?p->nBuf:1, &rc) ){ |
| 7643 | if( p->nBuf ){ |
| 7644 | memcpy(&pGrp->cd.record.aBuf[pGrp->cd.record.nBuf],p->aBuf,p->nBuf); |
| 7645 | pGrp->cd.record.nBuf += p->nBuf; |
| 7646 | }else{ |
| 7647 | pGrp->cd.record.aBuf[pGrp->cd.record.nBuf++] = eUndef; |
| 7648 | } |
| 7649 | } |
| 7650 | } |
| 7651 | if( rc==SQLITE_OK ){ |
| 7652 | rc = sessionOneChangeToHash( |
| 7653 | pGrp, pGrp->cd.pTab, |
| 7654 | pGrp->cd.eOp, pGrp->cd.bIndirect, pGrp->cd.pTab->nCol, |
| 7655 | pGrp->cd.record.aBuf, pGrp->cd.record.nBuf, 0 |
| 7656 | ); |
| 7657 | } |
| 7658 | } |
| 7659 | |
| 7660 | /* Reset all aBuf[] entries to "undefined". */ |
| 7661 | { |
| 7662 | int nZero = pGrp->cd.pTab->nCol; |
| 7663 | if( pGrp->cd.eOp==SQLITE_UPDATE ) nZero += nZero; |
| 7664 | for(ii=0; ii<nZero; ii++){ |
| 7665 | pGrp->cd.aBuf[ii].nBuf = 0; |
| 7666 | } |
| 7667 | } |
| 7668 | pGrp->cd.pTab = 0; |
| 7669 | } |
| 7670 | |
| 7671 | if( pzErr ){ |
| 7672 | *pzErr = zErr; |
| 7673 | }else{ |
| 7674 | sqlite3_free(zErr); |
| 7675 | } |
| 7676 | return rc; |
| 7677 | } |
| 7678 | |
| 7679 | #endif /* SQLITE_ENABLE_SESSION && SQLITE_ENABLE_PREUPDATE_HOOK */ |