OLD | NEW |
(Empty) | |
| 1 /* |
| 2 ** 2014 August 30 |
| 3 ** |
| 4 ** The author disclaims copyright to this source code. In place of |
| 5 ** a legal notice, here is a blessing: |
| 6 ** |
| 7 ** May you do good and not evil. |
| 8 ** May you find forgiveness for yourself and forgive others. |
| 9 ** May you share freely, never taking more than you give. |
| 10 ** |
| 11 ************************************************************************* |
| 12 ** |
| 13 ** |
| 14 ** OVERVIEW |
| 15 ** |
| 16 ** The RBU extension requires that the RBU update be packaged as an |
| 17 ** SQLite database. The tables it expects to find are described in |
| 18 ** sqlite3rbu.h. Essentially, for each table xyz in the target database |
| 19 ** that the user wishes to write to, a corresponding data_xyz table is |
| 20 ** created in the RBU database and populated with one row for each row to |
| 21 ** update, insert or delete from the target table. |
| 22 ** |
| 23 ** The update proceeds in three stages: |
| 24 ** |
| 25 ** 1) The database is updated. The modified database pages are written |
| 26 ** to a *-oal file. A *-oal file is just like a *-wal file, except |
| 27 ** that it is named "<database>-oal" instead of "<database>-wal". |
| 28 ** Because regular SQLite clients do not look for file named |
| 29 ** "<database>-oal", they go on using the original database in |
| 30 ** rollback mode while the *-oal file is being generated. |
| 31 ** |
| 32 ** During this stage RBU does not update the database by writing |
| 33 ** directly to the target tables. Instead it creates "imposter" |
| 34 ** tables using the SQLITE_TESTCTRL_IMPOSTER interface that it uses |
| 35 ** to update each b-tree individually. All updates required by each |
| 36 ** b-tree are completed before moving on to the next, and all |
| 37 ** updates are done in sorted key order. |
| 38 ** |
| 39 ** 2) The "<database>-oal" file is moved to the equivalent "<database>-wal" |
| 40 ** location using a call to rename(2). Before doing this the RBU |
| 41 ** module takes an EXCLUSIVE lock on the database file, ensuring |
| 42 ** that there are no other active readers. |
| 43 ** |
| 44 ** Once the EXCLUSIVE lock is released, any other database readers |
| 45 ** detect the new *-wal file and read the database in wal mode. At |
| 46 ** this point they see the new version of the database - including |
| 47 ** the updates made as part of the RBU update. |
| 48 ** |
| 49 ** 3) The new *-wal file is checkpointed. This proceeds in the same way |
| 50 ** as a regular database checkpoint, except that a single frame is |
| 51 ** checkpointed each time sqlite3rbu_step() is called. If the RBU |
| 52 ** handle is closed before the entire *-wal file is checkpointed, |
| 53 ** the checkpoint progress is saved in the RBU database and the |
| 54 ** checkpoint can be resumed by another RBU client at some point in |
| 55 ** the future. |
| 56 ** |
| 57 ** POTENTIAL PROBLEMS |
| 58 ** |
| 59 ** The rename() call might not be portable. And RBU is not currently |
| 60 ** syncing the directory after renaming the file. |
| 61 ** |
| 62 ** When state is saved, any commit to the *-oal file and the commit to |
| 63 ** the RBU update database are not atomic. So if the power fails at the |
| 64 ** wrong moment they might get out of sync. As the main database will be |
| 65 ** committed before the RBU update database this will likely either just |
| 66 ** pass unnoticed, or result in SQLITE_CONSTRAINT errors (due to UNIQUE |
| 67 ** constraint violations). |
| 68 ** |
| 69 ** If some client does modify the target database mid RBU update, or some |
| 70 ** other error occurs, the RBU extension will keep throwing errors. It's |
| 71 ** not really clear how to get out of this state. The system could just |
| 72 ** by delete the RBU update database and *-oal file and have the device |
| 73 ** download the update again and start over. |
| 74 ** |
| 75 ** At present, for an UPDATE, both the new.* and old.* records are |
| 76 ** collected in the rbu_xyz table. And for both UPDATEs and DELETEs all |
| 77 ** fields are collected. This means we're probably writing a lot more |
| 78 ** data to disk when saving the state of an ongoing update to the RBU |
| 79 ** update database than is strictly necessary. |
| 80 ** |
| 81 */ |
| 82 |
| 83 #include <assert.h> |
| 84 #include <string.h> |
| 85 #include <stdio.h> |
| 86 |
| 87 #include "sqlite3.h" |
| 88 |
| 89 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU) |
| 90 #include "sqlite3rbu.h" |
| 91 |
| 92 #if defined(_WIN32_WCE) |
| 93 #include "windows.h" |
| 94 #endif |
| 95 |
| 96 /* Maximum number of prepared UPDATE statements held by this module */ |
| 97 #define SQLITE_RBU_UPDATE_CACHESIZE 16 |
| 98 |
| 99 /* |
| 100 ** Swap two objects of type TYPE. |
| 101 */ |
| 102 #if !defined(SQLITE_AMALGAMATION) |
| 103 # define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;} |
| 104 #endif |
| 105 |
| 106 /* |
| 107 ** The rbu_state table is used to save the state of a partially applied |
| 108 ** update so that it can be resumed later. The table consists of integer |
| 109 ** keys mapped to values as follows: |
| 110 ** |
| 111 ** RBU_STATE_STAGE: |
| 112 ** May be set to integer values 1, 2, 4 or 5. As follows: |
| 113 ** 1: the *-rbu file is currently under construction. |
| 114 ** 2: the *-rbu file has been constructed, but not yet moved |
| 115 ** to the *-wal path. |
| 116 ** 4: the checkpoint is underway. |
| 117 ** 5: the rbu update has been checkpointed. |
| 118 ** |
| 119 ** RBU_STATE_TBL: |
| 120 ** Only valid if STAGE==1. The target database name of the table |
| 121 ** currently being written. |
| 122 ** |
| 123 ** RBU_STATE_IDX: |
| 124 ** Only valid if STAGE==1. The target database name of the index |
| 125 ** currently being written, or NULL if the main table is currently being |
| 126 ** updated. |
| 127 ** |
| 128 ** RBU_STATE_ROW: |
| 129 ** Only valid if STAGE==1. Number of rows already processed for the current |
| 130 ** table/index. |
| 131 ** |
| 132 ** RBU_STATE_PROGRESS: |
| 133 ** Trbul number of sqlite3rbu_step() calls made so far as part of this |
| 134 ** rbu update. |
| 135 ** |
| 136 ** RBU_STATE_CKPT: |
| 137 ** Valid if STAGE==4. The 64-bit checksum associated with the wal-index |
| 138 ** header created by recovering the *-wal file. This is used to detect |
| 139 ** cases when another client appends frames to the *-wal file in the |
| 140 ** middle of an incremental checkpoint (an incremental checkpoint cannot |
| 141 ** be continued if this happens). |
| 142 ** |
| 143 ** RBU_STATE_COOKIE: |
| 144 ** Valid if STAGE==1. The current change-counter cookie value in the |
| 145 ** target db file. |
| 146 ** |
| 147 ** RBU_STATE_OALSZ: |
| 148 ** Valid if STAGE==1. The size in bytes of the *-oal file. |
| 149 */ |
| 150 #define RBU_STATE_STAGE 1 |
| 151 #define RBU_STATE_TBL 2 |
| 152 #define RBU_STATE_IDX 3 |
| 153 #define RBU_STATE_ROW 4 |
| 154 #define RBU_STATE_PROGRESS 5 |
| 155 #define RBU_STATE_CKPT 6 |
| 156 #define RBU_STATE_COOKIE 7 |
| 157 #define RBU_STATE_OALSZ 8 |
| 158 #define RBU_STATE_PHASEONESTEP 9 |
| 159 |
| 160 #define RBU_STAGE_OAL 1 |
| 161 #define RBU_STAGE_MOVE 2 |
| 162 #define RBU_STAGE_CAPTURE 3 |
| 163 #define RBU_STAGE_CKPT 4 |
| 164 #define RBU_STAGE_DONE 5 |
| 165 |
| 166 |
| 167 #define RBU_CREATE_STATE \ |
| 168 "CREATE TABLE IF NOT EXISTS %s.rbu_state(k INTEGER PRIMARY KEY, v)" |
| 169 |
| 170 typedef struct RbuFrame RbuFrame; |
| 171 typedef struct RbuObjIter RbuObjIter; |
| 172 typedef struct RbuState RbuState; |
| 173 typedef struct rbu_vfs rbu_vfs; |
| 174 typedef struct rbu_file rbu_file; |
| 175 typedef struct RbuUpdateStmt RbuUpdateStmt; |
| 176 |
| 177 #if !defined(SQLITE_AMALGAMATION) |
| 178 typedef unsigned int u32; |
| 179 typedef unsigned short u16; |
| 180 typedef unsigned char u8; |
| 181 typedef sqlite3_int64 i64; |
| 182 #endif |
| 183 |
| 184 /* |
| 185 ** These values must match the values defined in wal.c for the equivalent |
| 186 ** locks. These are not magic numbers as they are part of the SQLite file |
| 187 ** format. |
| 188 */ |
| 189 #define WAL_LOCK_WRITE 0 |
| 190 #define WAL_LOCK_CKPT 1 |
| 191 #define WAL_LOCK_READ0 3 |
| 192 |
| 193 #define SQLITE_FCNTL_RBUCNT 5149216 |
| 194 |
| 195 /* |
| 196 ** A structure to store values read from the rbu_state table in memory. |
| 197 */ |
| 198 struct RbuState { |
| 199 int eStage; |
| 200 char *zTbl; |
| 201 char *zIdx; |
| 202 i64 iWalCksum; |
| 203 int nRow; |
| 204 i64 nProgress; |
| 205 u32 iCookie; |
| 206 i64 iOalSz; |
| 207 i64 nPhaseOneStep; |
| 208 }; |
| 209 |
| 210 struct RbuUpdateStmt { |
| 211 char *zMask; /* Copy of update mask used with pUpdate */ |
| 212 sqlite3_stmt *pUpdate; /* Last update statement (or NULL) */ |
| 213 RbuUpdateStmt *pNext; |
| 214 }; |
| 215 |
| 216 /* |
| 217 ** An iterator of this type is used to iterate through all objects in |
| 218 ** the target database that require updating. For each such table, the |
| 219 ** iterator visits, in order: |
| 220 ** |
| 221 ** * the table itself, |
| 222 ** * each index of the table (zero or more points to visit), and |
| 223 ** * a special "cleanup table" state. |
| 224 ** |
| 225 ** abIndexed: |
| 226 ** If the table has no indexes on it, abIndexed is set to NULL. Otherwise, |
| 227 ** it points to an array of flags nTblCol elements in size. The flag is |
| 228 ** set for each column that is either a part of the PK or a part of an |
| 229 ** index. Or clear otherwise. |
| 230 ** |
| 231 */ |
| 232 struct RbuObjIter { |
| 233 sqlite3_stmt *pTblIter; /* Iterate through tables */ |
| 234 sqlite3_stmt *pIdxIter; /* Index iterator */ |
| 235 int nTblCol; /* Size of azTblCol[] array */ |
| 236 char **azTblCol; /* Array of unquoted target column names */ |
| 237 char **azTblType; /* Array of target column types */ |
| 238 int *aiSrcOrder; /* src table col -> target table col */ |
| 239 u8 *abTblPk; /* Array of flags, set on target PK columns */ |
| 240 u8 *abNotNull; /* Array of flags, set on NOT NULL columns */ |
| 241 u8 *abIndexed; /* Array of flags, set on indexed & PK cols */ |
| 242 int eType; /* Table type - an RBU_PK_XXX value */ |
| 243 |
| 244 /* Output variables. zTbl==0 implies EOF. */ |
| 245 int bCleanup; /* True in "cleanup" state */ |
| 246 const char *zTbl; /* Name of target db table */ |
| 247 const char *zDataTbl; /* Name of rbu db table (or null) */ |
| 248 const char *zIdx; /* Name of target db index (or null) */ |
| 249 int iTnum; /* Root page of current object */ |
| 250 int iPkTnum; /* If eType==EXTERNAL, root of PK index */ |
| 251 int bUnique; /* Current index is unique */ |
| 252 int nIndex; /* Number of aux. indexes on table zTbl */ |
| 253 |
| 254 /* Statements created by rbuObjIterPrepareAll() */ |
| 255 int nCol; /* Number of columns in current object */ |
| 256 sqlite3_stmt *pSelect; /* Source data */ |
| 257 sqlite3_stmt *pInsert; /* Statement for INSERT operations */ |
| 258 sqlite3_stmt *pDelete; /* Statement for DELETE ops */ |
| 259 sqlite3_stmt *pTmpInsert; /* Insert into rbu_tmp_$zDataTbl */ |
| 260 |
| 261 /* Last UPDATE used (for PK b-tree updates only), or NULL. */ |
| 262 RbuUpdateStmt *pRbuUpdate; |
| 263 }; |
| 264 |
| 265 /* |
| 266 ** Values for RbuObjIter.eType |
| 267 ** |
| 268 ** 0: Table does not exist (error) |
| 269 ** 1: Table has an implicit rowid. |
| 270 ** 2: Table has an explicit IPK column. |
| 271 ** 3: Table has an external PK index. |
| 272 ** 4: Table is WITHOUT ROWID. |
| 273 ** 5: Table is a virtual table. |
| 274 */ |
| 275 #define RBU_PK_NOTABLE 0 |
| 276 #define RBU_PK_NONE 1 |
| 277 #define RBU_PK_IPK 2 |
| 278 #define RBU_PK_EXTERNAL 3 |
| 279 #define RBU_PK_WITHOUT_ROWID 4 |
| 280 #define RBU_PK_VTAB 5 |
| 281 |
| 282 |
| 283 /* |
| 284 ** Within the RBU_STAGE_OAL stage, each call to sqlite3rbu_step() performs |
| 285 ** one of the following operations. |
| 286 */ |
| 287 #define RBU_INSERT 1 /* Insert on a main table b-tree */ |
| 288 #define RBU_DELETE 2 /* Delete a row from a main table b-tree */ |
| 289 #define RBU_REPLACE 3 /* Delete and then insert a row */ |
| 290 #define RBU_IDX_DELETE 4 /* Delete a row from an aux. index b-tree */ |
| 291 #define RBU_IDX_INSERT 5 /* Insert on an aux. index b-tree */ |
| 292 |
| 293 #define RBU_UPDATE 6 /* Update a row in a main table b-tree */ |
| 294 |
| 295 /* |
| 296 ** A single step of an incremental checkpoint - frame iWalFrame of the wal |
| 297 ** file should be copied to page iDbPage of the database file. |
| 298 */ |
| 299 struct RbuFrame { |
| 300 u32 iDbPage; |
| 301 u32 iWalFrame; |
| 302 }; |
| 303 |
| 304 /* |
| 305 ** RBU handle. |
| 306 ** |
| 307 ** nPhaseOneStep: |
| 308 ** If the RBU database contains an rbu_count table, this value is set to |
| 309 ** a running estimate of the number of b-tree operations required to |
| 310 ** finish populating the *-oal file. This allows the sqlite3_bp_progress() |
| 311 ** API to calculate the permyriadage progress of populating the *-oal file |
| 312 ** using the formula: |
| 313 ** |
| 314 ** permyriadage = (10000 * nProgress) / nPhaseOneStep |
| 315 ** |
| 316 ** nPhaseOneStep is initialized to the sum of: |
| 317 ** |
| 318 ** nRow * (nIndex + 1) |
| 319 ** |
| 320 ** for all source tables in the RBU database, where nRow is the number |
| 321 ** of rows in the source table and nIndex the number of indexes on the |
| 322 ** corresponding target database table. |
| 323 ** |
| 324 ** This estimate is accurate if the RBU update consists entirely of |
| 325 ** INSERT operations. However, it is inaccurate if: |
| 326 ** |
| 327 ** * the RBU update contains any UPDATE operations. If the PK specified |
| 328 ** for an UPDATE operation does not exist in the target table, then |
| 329 ** no b-tree operations are required on index b-trees. Or if the |
| 330 ** specified PK does exist, then (nIndex*2) such operations are |
| 331 ** required (one delete and one insert on each index b-tree). |
| 332 ** |
| 333 ** * the RBU update contains any DELETE operations for which the specified |
| 334 ** PK does not exist. In this case no operations are required on index |
| 335 ** b-trees. |
| 336 ** |
| 337 ** * the RBU update contains REPLACE operations. These are similar to |
| 338 ** UPDATE operations. |
| 339 ** |
| 340 ** nPhaseOneStep is updated to account for the conditions above during the |
| 341 ** first pass of each source table. The updated nPhaseOneStep value is |
| 342 ** stored in the rbu_state table if the RBU update is suspended. |
| 343 */ |
| 344 struct sqlite3rbu { |
| 345 int eStage; /* Value of RBU_STATE_STAGE field */ |
| 346 sqlite3 *dbMain; /* target database handle */ |
| 347 sqlite3 *dbRbu; /* rbu database handle */ |
| 348 char *zTarget; /* Path to target db */ |
| 349 char *zRbu; /* Path to rbu db */ |
| 350 char *zState; /* Path to state db (or NULL if zRbu) */ |
| 351 char zStateDb[5]; /* Db name for state ("stat" or "main") */ |
| 352 int rc; /* Value returned by last rbu_step() call */ |
| 353 char *zErrmsg; /* Error message if rc!=SQLITE_OK */ |
| 354 int nStep; /* Rows processed for current object */ |
| 355 int nProgress; /* Rows processed for all objects */ |
| 356 RbuObjIter objiter; /* Iterator for skipping through tbl/idx */ |
| 357 const char *zVfsName; /* Name of automatically created rbu vfs */ |
| 358 rbu_file *pTargetFd; /* File handle open on target db */ |
| 359 i64 iOalSz; |
| 360 i64 nPhaseOneStep; |
| 361 |
| 362 /* The following state variables are used as part of the incremental |
| 363 ** checkpoint stage (eStage==RBU_STAGE_CKPT). See comments surrounding |
| 364 ** function rbuSetupCheckpoint() for details. */ |
| 365 u32 iMaxFrame; /* Largest iWalFrame value in aFrame[] */ |
| 366 u32 mLock; |
| 367 int nFrame; /* Entries in aFrame[] array */ |
| 368 int nFrameAlloc; /* Allocated size of aFrame[] array */ |
| 369 RbuFrame *aFrame; |
| 370 int pgsz; |
| 371 u8 *aBuf; |
| 372 i64 iWalCksum; |
| 373 |
| 374 /* Used in RBU vacuum mode only */ |
| 375 int nRbu; /* Number of RBU VFS in the stack */ |
| 376 rbu_file *pRbuFd; /* Fd for main db of dbRbu */ |
| 377 }; |
| 378 |
| 379 /* |
| 380 ** An rbu VFS is implemented using an instance of this structure. |
| 381 */ |
| 382 struct rbu_vfs { |
| 383 sqlite3_vfs base; /* rbu VFS shim methods */ |
| 384 sqlite3_vfs *pRealVfs; /* Underlying VFS */ |
| 385 sqlite3_mutex *mutex; /* Mutex to protect pMain */ |
| 386 rbu_file *pMain; /* Linked list of main db files */ |
| 387 }; |
| 388 |
| 389 /* |
| 390 ** Each file opened by an rbu VFS is represented by an instance of |
| 391 ** the following structure. |
| 392 */ |
| 393 struct rbu_file { |
| 394 sqlite3_file base; /* sqlite3_file methods */ |
| 395 sqlite3_file *pReal; /* Underlying file handle */ |
| 396 rbu_vfs *pRbuVfs; /* Pointer to the rbu_vfs object */ |
| 397 sqlite3rbu *pRbu; /* Pointer to rbu object (rbu target only) */ |
| 398 |
| 399 int openFlags; /* Flags this file was opened with */ |
| 400 u32 iCookie; /* Cookie value for main db files */ |
| 401 u8 iWriteVer; /* "write-version" value for main db files */ |
| 402 u8 bNolock; /* True to fail EXCLUSIVE locks */ |
| 403 |
| 404 int nShm; /* Number of entries in apShm[] array */ |
| 405 char **apShm; /* Array of mmap'd *-shm regions */ |
| 406 char *zDel; /* Delete this when closing file */ |
| 407 |
| 408 const char *zWal; /* Wal filename for this main db file */ |
| 409 rbu_file *pWalFd; /* Wal file descriptor for this main db */ |
| 410 rbu_file *pMainNext; /* Next MAIN_DB file */ |
| 411 }; |
| 412 |
| 413 /* |
| 414 ** True for an RBU vacuum handle, or false otherwise. |
| 415 */ |
| 416 #define rbuIsVacuum(p) ((p)->zTarget==0) |
| 417 |
| 418 |
| 419 /************************************************************************* |
| 420 ** The following three functions, found below: |
| 421 ** |
| 422 ** rbuDeltaGetInt() |
| 423 ** rbuDeltaChecksum() |
| 424 ** rbuDeltaApply() |
| 425 ** |
| 426 ** are lifted from the fossil source code (http://fossil-scm.org). They |
| 427 ** are used to implement the scalar SQL function rbu_fossil_delta(). |
| 428 */ |
| 429 |
| 430 /* |
| 431 ** Read bytes from *pz and convert them into a positive integer. When |
| 432 ** finished, leave *pz pointing to the first character past the end of |
| 433 ** the integer. The *pLen parameter holds the length of the string |
| 434 ** in *pz and is decremented once for each character in the integer. |
| 435 */ |
| 436 static unsigned int rbuDeltaGetInt(const char **pz, int *pLen){ |
| 437 static const signed char zValue[] = { |
| 438 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, |
| 439 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, |
| 440 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, |
| 441 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, |
| 442 -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, |
| 443 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, 36, |
| 444 -1, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, |
| 445 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, -1, -1, -1, 63, -1, |
| 446 }; |
| 447 unsigned int v = 0; |
| 448 int c; |
| 449 unsigned char *z = (unsigned char*)*pz; |
| 450 unsigned char *zStart = z; |
| 451 while( (c = zValue[0x7f&*(z++)])>=0 ){ |
| 452 v = (v<<6) + c; |
| 453 } |
| 454 z--; |
| 455 *pLen -= z - zStart; |
| 456 *pz = (char*)z; |
| 457 return v; |
| 458 } |
| 459 |
| 460 /* |
| 461 ** Compute a 32-bit checksum on the N-byte buffer. Return the result. |
| 462 */ |
| 463 static unsigned int rbuDeltaChecksum(const char *zIn, size_t N){ |
| 464 const unsigned char *z = (const unsigned char *)zIn; |
| 465 unsigned sum0 = 0; |
| 466 unsigned sum1 = 0; |
| 467 unsigned sum2 = 0; |
| 468 unsigned sum3 = 0; |
| 469 while(N >= 16){ |
| 470 sum0 += ((unsigned)z[0] + z[4] + z[8] + z[12]); |
| 471 sum1 += ((unsigned)z[1] + z[5] + z[9] + z[13]); |
| 472 sum2 += ((unsigned)z[2] + z[6] + z[10]+ z[14]); |
| 473 sum3 += ((unsigned)z[3] + z[7] + z[11]+ z[15]); |
| 474 z += 16; |
| 475 N -= 16; |
| 476 } |
| 477 while(N >= 4){ |
| 478 sum0 += z[0]; |
| 479 sum1 += z[1]; |
| 480 sum2 += z[2]; |
| 481 sum3 += z[3]; |
| 482 z += 4; |
| 483 N -= 4; |
| 484 } |
| 485 sum3 += (sum2 << 8) + (sum1 << 16) + (sum0 << 24); |
| 486 switch(N){ |
| 487 case 3: sum3 += (z[2] << 8); |
| 488 case 2: sum3 += (z[1] << 16); |
| 489 case 1: sum3 += (z[0] << 24); |
| 490 default: ; |
| 491 } |
| 492 return sum3; |
| 493 } |
| 494 |
| 495 /* |
| 496 ** Apply a delta. |
| 497 ** |
| 498 ** The output buffer should be big enough to hold the whole output |
| 499 ** file and a NUL terminator at the end. The delta_output_size() |
| 500 ** routine will determine this size for you. |
| 501 ** |
| 502 ** The delta string should be null-terminated. But the delta string |
| 503 ** may contain embedded NUL characters (if the input and output are |
| 504 ** binary files) so we also have to pass in the length of the delta in |
| 505 ** the lenDelta parameter. |
| 506 ** |
| 507 ** This function returns the size of the output file in bytes (excluding |
| 508 ** the final NUL terminator character). Except, if the delta string is |
| 509 ** malformed or intended for use with a source file other than zSrc, |
| 510 ** then this routine returns -1. |
| 511 ** |
| 512 ** Refer to the delta_create() documentation above for a description |
| 513 ** of the delta file format. |
| 514 */ |
| 515 static int rbuDeltaApply( |
| 516 const char *zSrc, /* The source or pattern file */ |
| 517 int lenSrc, /* Length of the source file */ |
| 518 const char *zDelta, /* Delta to apply to the pattern */ |
| 519 int lenDelta, /* Length of the delta */ |
| 520 char *zOut /* Write the output into this preallocated buffer */ |
| 521 ){ |
| 522 unsigned int limit; |
| 523 unsigned int total = 0; |
| 524 #ifndef FOSSIL_OMIT_DELTA_CKSUM_TEST |
| 525 char *zOrigOut = zOut; |
| 526 #endif |
| 527 |
| 528 limit = rbuDeltaGetInt(&zDelta, &lenDelta); |
| 529 if( *zDelta!='\n' ){ |
| 530 /* ERROR: size integer not terminated by "\n" */ |
| 531 return -1; |
| 532 } |
| 533 zDelta++; lenDelta--; |
| 534 while( *zDelta && lenDelta>0 ){ |
| 535 unsigned int cnt, ofst; |
| 536 cnt = rbuDeltaGetInt(&zDelta, &lenDelta); |
| 537 switch( zDelta[0] ){ |
| 538 case '@': { |
| 539 zDelta++; lenDelta--; |
| 540 ofst = rbuDeltaGetInt(&zDelta, &lenDelta); |
| 541 if( lenDelta>0 && zDelta[0]!=',' ){ |
| 542 /* ERROR: copy command not terminated by ',' */ |
| 543 return -1; |
| 544 } |
| 545 zDelta++; lenDelta--; |
| 546 total += cnt; |
| 547 if( total>limit ){ |
| 548 /* ERROR: copy exceeds output file size */ |
| 549 return -1; |
| 550 } |
| 551 if( (int)(ofst+cnt) > lenSrc ){ |
| 552 /* ERROR: copy extends past end of input */ |
| 553 return -1; |
| 554 } |
| 555 memcpy(zOut, &zSrc[ofst], cnt); |
| 556 zOut += cnt; |
| 557 break; |
| 558 } |
| 559 case ':': { |
| 560 zDelta++; lenDelta--; |
| 561 total += cnt; |
| 562 if( total>limit ){ |
| 563 /* ERROR: insert command gives an output larger than predicted */ |
| 564 return -1; |
| 565 } |
| 566 if( (int)cnt>lenDelta ){ |
| 567 /* ERROR: insert count exceeds size of delta */ |
| 568 return -1; |
| 569 } |
| 570 memcpy(zOut, zDelta, cnt); |
| 571 zOut += cnt; |
| 572 zDelta += cnt; |
| 573 lenDelta -= cnt; |
| 574 break; |
| 575 } |
| 576 case ';': { |
| 577 zDelta++; lenDelta--; |
| 578 zOut[0] = 0; |
| 579 #ifndef FOSSIL_OMIT_DELTA_CKSUM_TEST |
| 580 if( cnt!=rbuDeltaChecksum(zOrigOut, total) ){ |
| 581 /* ERROR: bad checksum */ |
| 582 return -1; |
| 583 } |
| 584 #endif |
| 585 if( total!=limit ){ |
| 586 /* ERROR: generated size does not match predicted size */ |
| 587 return -1; |
| 588 } |
| 589 return total; |
| 590 } |
| 591 default: { |
| 592 /* ERROR: unknown delta operator */ |
| 593 return -1; |
| 594 } |
| 595 } |
| 596 } |
| 597 /* ERROR: unterminated delta */ |
| 598 return -1; |
| 599 } |
| 600 |
| 601 static int rbuDeltaOutputSize(const char *zDelta, int lenDelta){ |
| 602 int size; |
| 603 size = rbuDeltaGetInt(&zDelta, &lenDelta); |
| 604 if( *zDelta!='\n' ){ |
| 605 /* ERROR: size integer not terminated by "\n" */ |
| 606 return -1; |
| 607 } |
| 608 return size; |
| 609 } |
| 610 |
| 611 /* |
| 612 ** End of code taken from fossil. |
| 613 *************************************************************************/ |
| 614 |
| 615 /* |
| 616 ** Implementation of SQL scalar function rbu_fossil_delta(). |
| 617 ** |
| 618 ** This function applies a fossil delta patch to a blob. Exactly two |
| 619 ** arguments must be passed to this function. The first is the blob to |
| 620 ** patch and the second the patch to apply. If no error occurs, this |
| 621 ** function returns the patched blob. |
| 622 */ |
| 623 static void rbuFossilDeltaFunc( |
| 624 sqlite3_context *context, |
| 625 int argc, |
| 626 sqlite3_value **argv |
| 627 ){ |
| 628 const char *aDelta; |
| 629 int nDelta; |
| 630 const char *aOrig; |
| 631 int nOrig; |
| 632 |
| 633 int nOut; |
| 634 int nOut2; |
| 635 char *aOut; |
| 636 |
| 637 assert( argc==2 ); |
| 638 |
| 639 nOrig = sqlite3_value_bytes(argv[0]); |
| 640 aOrig = (const char*)sqlite3_value_blob(argv[0]); |
| 641 nDelta = sqlite3_value_bytes(argv[1]); |
| 642 aDelta = (const char*)sqlite3_value_blob(argv[1]); |
| 643 |
| 644 /* Figure out the size of the output */ |
| 645 nOut = rbuDeltaOutputSize(aDelta, nDelta); |
| 646 if( nOut<0 ){ |
| 647 sqlite3_result_error(context, "corrupt fossil delta", -1); |
| 648 return; |
| 649 } |
| 650 |
| 651 aOut = sqlite3_malloc(nOut+1); |
| 652 if( aOut==0 ){ |
| 653 sqlite3_result_error_nomem(context); |
| 654 }else{ |
| 655 nOut2 = rbuDeltaApply(aOrig, nOrig, aDelta, nDelta, aOut); |
| 656 if( nOut2!=nOut ){ |
| 657 sqlite3_result_error(context, "corrupt fossil delta", -1); |
| 658 }else{ |
| 659 sqlite3_result_blob(context, aOut, nOut, sqlite3_free); |
| 660 } |
| 661 } |
| 662 } |
| 663 |
| 664 |
| 665 /* |
| 666 ** Prepare the SQL statement in buffer zSql against database handle db. |
| 667 ** If successful, set *ppStmt to point to the new statement and return |
| 668 ** SQLITE_OK. |
| 669 ** |
| 670 ** Otherwise, if an error does occur, set *ppStmt to NULL and return |
| 671 ** an SQLite error code. Additionally, set output variable *pzErrmsg to |
| 672 ** point to a buffer containing an error message. It is the responsibility |
| 673 ** of the caller to (eventually) free this buffer using sqlite3_free(). |
| 674 */ |
| 675 static int prepareAndCollectError( |
| 676 sqlite3 *db, |
| 677 sqlite3_stmt **ppStmt, |
| 678 char **pzErrmsg, |
| 679 const char *zSql |
| 680 ){ |
| 681 int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0); |
| 682 if( rc!=SQLITE_OK ){ |
| 683 *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db)); |
| 684 *ppStmt = 0; |
| 685 } |
| 686 return rc; |
| 687 } |
| 688 |
| 689 /* |
| 690 ** Reset the SQL statement passed as the first argument. Return a copy |
| 691 ** of the value returned by sqlite3_reset(). |
| 692 ** |
| 693 ** If an error has occurred, then set *pzErrmsg to point to a buffer |
| 694 ** containing an error message. It is the responsibility of the caller |
| 695 ** to eventually free this buffer using sqlite3_free(). |
| 696 */ |
| 697 static int resetAndCollectError(sqlite3_stmt *pStmt, char **pzErrmsg){ |
| 698 int rc = sqlite3_reset(pStmt); |
| 699 if( rc!=SQLITE_OK ){ |
| 700 *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(sqlite3_db_handle(pStmt))); |
| 701 } |
| 702 return rc; |
| 703 } |
| 704 |
| 705 /* |
| 706 ** Unless it is NULL, argument zSql points to a buffer allocated using |
| 707 ** sqlite3_malloc containing an SQL statement. This function prepares the SQL |
| 708 ** statement against database db and frees the buffer. If statement |
| 709 ** compilation is successful, *ppStmt is set to point to the new statement |
| 710 ** handle and SQLITE_OK is returned. |
| 711 ** |
| 712 ** Otherwise, if an error occurs, *ppStmt is set to NULL and an error code |
| 713 ** returned. In this case, *pzErrmsg may also be set to point to an error |
| 714 ** message. It is the responsibility of the caller to free this error message |
| 715 ** buffer using sqlite3_free(). |
| 716 ** |
| 717 ** If argument zSql is NULL, this function assumes that an OOM has occurred. |
| 718 ** In this case SQLITE_NOMEM is returned and *ppStmt set to NULL. |
| 719 */ |
| 720 static int prepareFreeAndCollectError( |
| 721 sqlite3 *db, |
| 722 sqlite3_stmt **ppStmt, |
| 723 char **pzErrmsg, |
| 724 char *zSql |
| 725 ){ |
| 726 int rc; |
| 727 assert( *pzErrmsg==0 ); |
| 728 if( zSql==0 ){ |
| 729 rc = SQLITE_NOMEM; |
| 730 *ppStmt = 0; |
| 731 }else{ |
| 732 rc = prepareAndCollectError(db, ppStmt, pzErrmsg, zSql); |
| 733 sqlite3_free(zSql); |
| 734 } |
| 735 return rc; |
| 736 } |
| 737 |
| 738 /* |
| 739 ** Free the RbuObjIter.azTblCol[] and RbuObjIter.abTblPk[] arrays allocated |
| 740 ** by an earlier call to rbuObjIterCacheTableInfo(). |
| 741 */ |
| 742 static void rbuObjIterFreeCols(RbuObjIter *pIter){ |
| 743 int i; |
| 744 for(i=0; i<pIter->nTblCol; i++){ |
| 745 sqlite3_free(pIter->azTblCol[i]); |
| 746 sqlite3_free(pIter->azTblType[i]); |
| 747 } |
| 748 sqlite3_free(pIter->azTblCol); |
| 749 pIter->azTblCol = 0; |
| 750 pIter->azTblType = 0; |
| 751 pIter->aiSrcOrder = 0; |
| 752 pIter->abTblPk = 0; |
| 753 pIter->abNotNull = 0; |
| 754 pIter->nTblCol = 0; |
| 755 pIter->eType = 0; /* Invalid value */ |
| 756 } |
| 757 |
| 758 /* |
| 759 ** Finalize all statements and free all allocations that are specific to |
| 760 ** the current object (table/index pair). |
| 761 */ |
| 762 static void rbuObjIterClearStatements(RbuObjIter *pIter){ |
| 763 RbuUpdateStmt *pUp; |
| 764 |
| 765 sqlite3_finalize(pIter->pSelect); |
| 766 sqlite3_finalize(pIter->pInsert); |
| 767 sqlite3_finalize(pIter->pDelete); |
| 768 sqlite3_finalize(pIter->pTmpInsert); |
| 769 pUp = pIter->pRbuUpdate; |
| 770 while( pUp ){ |
| 771 RbuUpdateStmt *pTmp = pUp->pNext; |
| 772 sqlite3_finalize(pUp->pUpdate); |
| 773 sqlite3_free(pUp); |
| 774 pUp = pTmp; |
| 775 } |
| 776 |
| 777 pIter->pSelect = 0; |
| 778 pIter->pInsert = 0; |
| 779 pIter->pDelete = 0; |
| 780 pIter->pRbuUpdate = 0; |
| 781 pIter->pTmpInsert = 0; |
| 782 pIter->nCol = 0; |
| 783 } |
| 784 |
| 785 /* |
| 786 ** Clean up any resources allocated as part of the iterator object passed |
| 787 ** as the only argument. |
| 788 */ |
| 789 static void rbuObjIterFinalize(RbuObjIter *pIter){ |
| 790 rbuObjIterClearStatements(pIter); |
| 791 sqlite3_finalize(pIter->pTblIter); |
| 792 sqlite3_finalize(pIter->pIdxIter); |
| 793 rbuObjIterFreeCols(pIter); |
| 794 memset(pIter, 0, sizeof(RbuObjIter)); |
| 795 } |
| 796 |
| 797 /* |
| 798 ** Advance the iterator to the next position. |
| 799 ** |
| 800 ** If no error occurs, SQLITE_OK is returned and the iterator is left |
| 801 ** pointing to the next entry. Otherwise, an error code and message is |
| 802 ** left in the RBU handle passed as the first argument. A copy of the |
| 803 ** error code is returned. |
| 804 */ |
| 805 static int rbuObjIterNext(sqlite3rbu *p, RbuObjIter *pIter){ |
| 806 int rc = p->rc; |
| 807 if( rc==SQLITE_OK ){ |
| 808 |
| 809 /* Free any SQLite statements used while processing the previous object */ |
| 810 rbuObjIterClearStatements(pIter); |
| 811 if( pIter->zIdx==0 ){ |
| 812 rc = sqlite3_exec(p->dbMain, |
| 813 "DROP TRIGGER IF EXISTS temp.rbu_insert_tr;" |
| 814 "DROP TRIGGER IF EXISTS temp.rbu_update1_tr;" |
| 815 "DROP TRIGGER IF EXISTS temp.rbu_update2_tr;" |
| 816 "DROP TRIGGER IF EXISTS temp.rbu_delete_tr;" |
| 817 , 0, 0, &p->zErrmsg |
| 818 ); |
| 819 } |
| 820 |
| 821 if( rc==SQLITE_OK ){ |
| 822 if( pIter->bCleanup ){ |
| 823 rbuObjIterFreeCols(pIter); |
| 824 pIter->bCleanup = 0; |
| 825 rc = sqlite3_step(pIter->pTblIter); |
| 826 if( rc!=SQLITE_ROW ){ |
| 827 rc = resetAndCollectError(pIter->pTblIter, &p->zErrmsg); |
| 828 pIter->zTbl = 0; |
| 829 }else{ |
| 830 pIter->zTbl = (const char*)sqlite3_column_text(pIter->pTblIter, 0); |
| 831 pIter->zDataTbl = (const char*)sqlite3_column_text(pIter->pTblIter,1); |
| 832 rc = (pIter->zDataTbl && pIter->zTbl) ? SQLITE_OK : SQLITE_NOMEM; |
| 833 } |
| 834 }else{ |
| 835 if( pIter->zIdx==0 ){ |
| 836 sqlite3_stmt *pIdx = pIter->pIdxIter; |
| 837 rc = sqlite3_bind_text(pIdx, 1, pIter->zTbl, -1, SQLITE_STATIC); |
| 838 } |
| 839 if( rc==SQLITE_OK ){ |
| 840 rc = sqlite3_step(pIter->pIdxIter); |
| 841 if( rc!=SQLITE_ROW ){ |
| 842 rc = resetAndCollectError(pIter->pIdxIter, &p->zErrmsg); |
| 843 pIter->bCleanup = 1; |
| 844 pIter->zIdx = 0; |
| 845 }else{ |
| 846 pIter->zIdx = (const char*)sqlite3_column_text(pIter->pIdxIter, 0); |
| 847 pIter->iTnum = sqlite3_column_int(pIter->pIdxIter, 1); |
| 848 pIter->bUnique = sqlite3_column_int(pIter->pIdxIter, 2); |
| 849 rc = pIter->zIdx ? SQLITE_OK : SQLITE_NOMEM; |
| 850 } |
| 851 } |
| 852 } |
| 853 } |
| 854 } |
| 855 |
| 856 if( rc!=SQLITE_OK ){ |
| 857 rbuObjIterFinalize(pIter); |
| 858 p->rc = rc; |
| 859 } |
| 860 return rc; |
| 861 } |
| 862 |
| 863 |
| 864 /* |
| 865 ** The implementation of the rbu_target_name() SQL function. This function |
| 866 ** accepts one or two arguments. The first argument is the name of a table - |
| 867 ** the name of a table in the RBU database. The second, if it is present, is 1 |
| 868 ** for a view or 0 for a table. |
| 869 ** |
| 870 ** For a non-vacuum RBU handle, if the table name matches the pattern: |
| 871 ** |
| 872 ** data[0-9]_<name> |
| 873 ** |
| 874 ** where <name> is any sequence of 1 or more characters, <name> is returned. |
| 875 ** Otherwise, if the only argument does not match the above pattern, an SQL |
| 876 ** NULL is returned. |
| 877 ** |
| 878 ** "data_t1" -> "t1" |
| 879 ** "data0123_t2" -> "t2" |
| 880 ** "dataAB_t3" -> NULL |
| 881 ** |
| 882 ** For an rbu vacuum handle, a copy of the first argument is returned if |
| 883 ** the second argument is either missing or 0 (not a view). |
| 884 */ |
| 885 static void rbuTargetNameFunc( |
| 886 sqlite3_context *pCtx, |
| 887 int argc, |
| 888 sqlite3_value **argv |
| 889 ){ |
| 890 sqlite3rbu *p = sqlite3_user_data(pCtx); |
| 891 const char *zIn; |
| 892 assert( argc==1 || argc==2 ); |
| 893 |
| 894 zIn = (const char*)sqlite3_value_text(argv[0]); |
| 895 if( zIn ){ |
| 896 if( rbuIsVacuum(p) ){ |
| 897 if( argc==1 || 0==sqlite3_value_int(argv[1]) ){ |
| 898 sqlite3_result_text(pCtx, zIn, -1, SQLITE_STATIC); |
| 899 } |
| 900 }else{ |
| 901 if( strlen(zIn)>4 && memcmp("data", zIn, 4)==0 ){ |
| 902 int i; |
| 903 for(i=4; zIn[i]>='0' && zIn[i]<='9'; i++); |
| 904 if( zIn[i]=='_' && zIn[i+1] ){ |
| 905 sqlite3_result_text(pCtx, &zIn[i+1], -1, SQLITE_STATIC); |
| 906 } |
| 907 } |
| 908 } |
| 909 } |
| 910 } |
| 911 |
| 912 /* |
| 913 ** Initialize the iterator structure passed as the second argument. |
| 914 ** |
| 915 ** If no error occurs, SQLITE_OK is returned and the iterator is left |
| 916 ** pointing to the first entry. Otherwise, an error code and message is |
| 917 ** left in the RBU handle passed as the first argument. A copy of the |
| 918 ** error code is returned. |
| 919 */ |
| 920 static int rbuObjIterFirst(sqlite3rbu *p, RbuObjIter *pIter){ |
| 921 int rc; |
| 922 memset(pIter, 0, sizeof(RbuObjIter)); |
| 923 |
| 924 rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pTblIter, &p->zErrmsg, |
| 925 sqlite3_mprintf( |
| 926 "SELECT rbu_target_name(name, type='view') AS target, name " |
| 927 "FROM sqlite_master " |
| 928 "WHERE type IN ('table', 'view') AND target IS NOT NULL " |
| 929 " %s " |
| 930 "ORDER BY name" |
| 931 , rbuIsVacuum(p) ? "AND rootpage!=0 AND rootpage IS NOT NULL" : "")); |
| 932 |
| 933 if( rc==SQLITE_OK ){ |
| 934 rc = prepareAndCollectError(p->dbMain, &pIter->pIdxIter, &p->zErrmsg, |
| 935 "SELECT name, rootpage, sql IS NULL OR substr(8, 6)=='UNIQUE' " |
| 936 " FROM main.sqlite_master " |
| 937 " WHERE type='index' AND tbl_name = ?" |
| 938 ); |
| 939 } |
| 940 |
| 941 pIter->bCleanup = 1; |
| 942 p->rc = rc; |
| 943 return rbuObjIterNext(p, pIter); |
| 944 } |
| 945 |
| 946 /* |
| 947 ** This is a wrapper around "sqlite3_mprintf(zFmt, ...)". If an OOM occurs, |
| 948 ** an error code is stored in the RBU handle passed as the first argument. |
| 949 ** |
| 950 ** If an error has already occurred (p->rc is already set to something other |
| 951 ** than SQLITE_OK), then this function returns NULL without modifying the |
| 952 ** stored error code. In this case it still calls sqlite3_free() on any |
| 953 ** printf() parameters associated with %z conversions. |
| 954 */ |
| 955 static char *rbuMPrintf(sqlite3rbu *p, const char *zFmt, ...){ |
| 956 char *zSql = 0; |
| 957 va_list ap; |
| 958 va_start(ap, zFmt); |
| 959 zSql = sqlite3_vmprintf(zFmt, ap); |
| 960 if( p->rc==SQLITE_OK ){ |
| 961 if( zSql==0 ) p->rc = SQLITE_NOMEM; |
| 962 }else{ |
| 963 sqlite3_free(zSql); |
| 964 zSql = 0; |
| 965 } |
| 966 va_end(ap); |
| 967 return zSql; |
| 968 } |
| 969 |
| 970 /* |
| 971 ** Argument zFmt is a sqlite3_mprintf() style format string. The trailing |
| 972 ** arguments are the usual subsitution values. This function performs |
| 973 ** the printf() style substitutions and executes the result as an SQL |
| 974 ** statement on the RBU handles database. |
| 975 ** |
| 976 ** If an error occurs, an error code and error message is stored in the |
| 977 ** RBU handle. If an error has already occurred when this function is |
| 978 ** called, it is a no-op. |
| 979 */ |
| 980 static int rbuMPrintfExec(sqlite3rbu *p, sqlite3 *db, const char *zFmt, ...){ |
| 981 va_list ap; |
| 982 char *zSql; |
| 983 va_start(ap, zFmt); |
| 984 zSql = sqlite3_vmprintf(zFmt, ap); |
| 985 if( p->rc==SQLITE_OK ){ |
| 986 if( zSql==0 ){ |
| 987 p->rc = SQLITE_NOMEM; |
| 988 }else{ |
| 989 p->rc = sqlite3_exec(db, zSql, 0, 0, &p->zErrmsg); |
| 990 } |
| 991 } |
| 992 sqlite3_free(zSql); |
| 993 va_end(ap); |
| 994 return p->rc; |
| 995 } |
| 996 |
| 997 /* |
| 998 ** Attempt to allocate and return a pointer to a zeroed block of nByte |
| 999 ** bytes. |
| 1000 ** |
| 1001 ** If an error (i.e. an OOM condition) occurs, return NULL and leave an |
| 1002 ** error code in the rbu handle passed as the first argument. Or, if an |
| 1003 ** error has already occurred when this function is called, return NULL |
| 1004 ** immediately without attempting the allocation or modifying the stored |
| 1005 ** error code. |
| 1006 */ |
| 1007 static void *rbuMalloc(sqlite3rbu *p, int nByte){ |
| 1008 void *pRet = 0; |
| 1009 if( p->rc==SQLITE_OK ){ |
| 1010 assert( nByte>0 ); |
| 1011 pRet = sqlite3_malloc64(nByte); |
| 1012 if( pRet==0 ){ |
| 1013 p->rc = SQLITE_NOMEM; |
| 1014 }else{ |
| 1015 memset(pRet, 0, nByte); |
| 1016 } |
| 1017 } |
| 1018 return pRet; |
| 1019 } |
| 1020 |
| 1021 |
| 1022 /* |
| 1023 ** Allocate and zero the pIter->azTblCol[] and abTblPk[] arrays so that |
| 1024 ** there is room for at least nCol elements. If an OOM occurs, store an |
| 1025 ** error code in the RBU handle passed as the first argument. |
| 1026 */ |
| 1027 static void rbuAllocateIterArrays(sqlite3rbu *p, RbuObjIter *pIter, int nCol){ |
| 1028 int nByte = (2*sizeof(char*) + sizeof(int) + 3*sizeof(u8)) * nCol; |
| 1029 char **azNew; |
| 1030 |
| 1031 azNew = (char**)rbuMalloc(p, nByte); |
| 1032 if( azNew ){ |
| 1033 pIter->azTblCol = azNew; |
| 1034 pIter->azTblType = &azNew[nCol]; |
| 1035 pIter->aiSrcOrder = (int*)&pIter->azTblType[nCol]; |
| 1036 pIter->abTblPk = (u8*)&pIter->aiSrcOrder[nCol]; |
| 1037 pIter->abNotNull = (u8*)&pIter->abTblPk[nCol]; |
| 1038 pIter->abIndexed = (u8*)&pIter->abNotNull[nCol]; |
| 1039 } |
| 1040 } |
| 1041 |
| 1042 /* |
| 1043 ** The first argument must be a nul-terminated string. This function |
| 1044 ** returns a copy of the string in memory obtained from sqlite3_malloc(). |
| 1045 ** It is the responsibility of the caller to eventually free this memory |
| 1046 ** using sqlite3_free(). |
| 1047 ** |
| 1048 ** If an OOM condition is encountered when attempting to allocate memory, |
| 1049 ** output variable (*pRc) is set to SQLITE_NOMEM before returning. Otherwise, |
| 1050 ** if the allocation succeeds, (*pRc) is left unchanged. |
| 1051 */ |
| 1052 static char *rbuStrndup(const char *zStr, int *pRc){ |
| 1053 char *zRet = 0; |
| 1054 |
| 1055 assert( *pRc==SQLITE_OK ); |
| 1056 if( zStr ){ |
| 1057 size_t nCopy = strlen(zStr) + 1; |
| 1058 zRet = (char*)sqlite3_malloc64(nCopy); |
| 1059 if( zRet ){ |
| 1060 memcpy(zRet, zStr, nCopy); |
| 1061 }else{ |
| 1062 *pRc = SQLITE_NOMEM; |
| 1063 } |
| 1064 } |
| 1065 |
| 1066 return zRet; |
| 1067 } |
| 1068 |
| 1069 /* |
| 1070 ** Finalize the statement passed as the second argument. |
| 1071 ** |
| 1072 ** If the sqlite3_finalize() call indicates that an error occurs, and the |
| 1073 ** rbu handle error code is not already set, set the error code and error |
| 1074 ** message accordingly. |
| 1075 */ |
| 1076 static void rbuFinalize(sqlite3rbu *p, sqlite3_stmt *pStmt){ |
| 1077 sqlite3 *db = sqlite3_db_handle(pStmt); |
| 1078 int rc = sqlite3_finalize(pStmt); |
| 1079 if( p->rc==SQLITE_OK && rc!=SQLITE_OK ){ |
| 1080 p->rc = rc; |
| 1081 p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db)); |
| 1082 } |
| 1083 } |
| 1084 |
| 1085 /* Determine the type of a table. |
| 1086 ** |
| 1087 ** peType is of type (int*), a pointer to an output parameter of type |
| 1088 ** (int). This call sets the output parameter as follows, depending |
| 1089 ** on the type of the table specified by parameters dbName and zTbl. |
| 1090 ** |
| 1091 ** RBU_PK_NOTABLE: No such table. |
| 1092 ** RBU_PK_NONE: Table has an implicit rowid. |
| 1093 ** RBU_PK_IPK: Table has an explicit IPK column. |
| 1094 ** RBU_PK_EXTERNAL: Table has an external PK index. |
| 1095 ** RBU_PK_WITHOUT_ROWID: Table is WITHOUT ROWID. |
| 1096 ** RBU_PK_VTAB: Table is a virtual table. |
| 1097 ** |
| 1098 ** Argument *piPk is also of type (int*), and also points to an output |
| 1099 ** parameter. Unless the table has an external primary key index |
| 1100 ** (i.e. unless *peType is set to 3), then *piPk is set to zero. Or, |
| 1101 ** if the table does have an external primary key index, then *piPk |
| 1102 ** is set to the root page number of the primary key index before |
| 1103 ** returning. |
| 1104 ** |
| 1105 ** ALGORITHM: |
| 1106 ** |
| 1107 ** if( no entry exists in sqlite_master ){ |
| 1108 ** return RBU_PK_NOTABLE |
| 1109 ** }else if( sql for the entry starts with "CREATE VIRTUAL" ){ |
| 1110 ** return RBU_PK_VTAB |
| 1111 ** }else if( "PRAGMA index_list()" for the table contains a "pk" index ){ |
| 1112 ** if( the index that is the pk exists in sqlite_master ){ |
| 1113 ** *piPK = rootpage of that index. |
| 1114 ** return RBU_PK_EXTERNAL |
| 1115 ** }else{ |
| 1116 ** return RBU_PK_WITHOUT_ROWID |
| 1117 ** } |
| 1118 ** }else if( "PRAGMA table_info()" lists one or more "pk" columns ){ |
| 1119 ** return RBU_PK_IPK |
| 1120 ** }else{ |
| 1121 ** return RBU_PK_NONE |
| 1122 ** } |
| 1123 */ |
| 1124 static void rbuTableType( |
| 1125 sqlite3rbu *p, |
| 1126 const char *zTab, |
| 1127 int *peType, |
| 1128 int *piTnum, |
| 1129 int *piPk |
| 1130 ){ |
| 1131 /* |
| 1132 ** 0) SELECT count(*) FROM sqlite_master where name=%Q AND IsVirtual(%Q) |
| 1133 ** 1) PRAGMA index_list = ? |
| 1134 ** 2) SELECT count(*) FROM sqlite_master where name=%Q |
| 1135 ** 3) PRAGMA table_info = ? |
| 1136 */ |
| 1137 sqlite3_stmt *aStmt[4] = {0, 0, 0, 0}; |
| 1138 |
| 1139 *peType = RBU_PK_NOTABLE; |
| 1140 *piPk = 0; |
| 1141 |
| 1142 assert( p->rc==SQLITE_OK ); |
| 1143 p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[0], &p->zErrmsg, |
| 1144 sqlite3_mprintf( |
| 1145 "SELECT (sql LIKE 'create virtual%%'), rootpage" |
| 1146 " FROM sqlite_master" |
| 1147 " WHERE name=%Q", zTab |
| 1148 )); |
| 1149 if( p->rc!=SQLITE_OK || sqlite3_step(aStmt[0])!=SQLITE_ROW ){ |
| 1150 /* Either an error, or no such table. */ |
| 1151 goto rbuTableType_end; |
| 1152 } |
| 1153 if( sqlite3_column_int(aStmt[0], 0) ){ |
| 1154 *peType = RBU_PK_VTAB; /* virtual table */ |
| 1155 goto rbuTableType_end; |
| 1156 } |
| 1157 *piTnum = sqlite3_column_int(aStmt[0], 1); |
| 1158 |
| 1159 p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[1], &p->zErrmsg, |
| 1160 sqlite3_mprintf("PRAGMA index_list=%Q",zTab) |
| 1161 ); |
| 1162 if( p->rc ) goto rbuTableType_end; |
| 1163 while( sqlite3_step(aStmt[1])==SQLITE_ROW ){ |
| 1164 const u8 *zOrig = sqlite3_column_text(aStmt[1], 3); |
| 1165 const u8 *zIdx = sqlite3_column_text(aStmt[1], 1); |
| 1166 if( zOrig && zIdx && zOrig[0]=='p' ){ |
| 1167 p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[2], &p->zErrmsg, |
| 1168 sqlite3_mprintf( |
| 1169 "SELECT rootpage FROM sqlite_master WHERE name = %Q", zIdx |
| 1170 )); |
| 1171 if( p->rc==SQLITE_OK ){ |
| 1172 if( sqlite3_step(aStmt[2])==SQLITE_ROW ){ |
| 1173 *piPk = sqlite3_column_int(aStmt[2], 0); |
| 1174 *peType = RBU_PK_EXTERNAL; |
| 1175 }else{ |
| 1176 *peType = RBU_PK_WITHOUT_ROWID; |
| 1177 } |
| 1178 } |
| 1179 goto rbuTableType_end; |
| 1180 } |
| 1181 } |
| 1182 |
| 1183 p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[3], &p->zErrmsg, |
| 1184 sqlite3_mprintf("PRAGMA table_info=%Q",zTab) |
| 1185 ); |
| 1186 if( p->rc==SQLITE_OK ){ |
| 1187 while( sqlite3_step(aStmt[3])==SQLITE_ROW ){ |
| 1188 if( sqlite3_column_int(aStmt[3],5)>0 ){ |
| 1189 *peType = RBU_PK_IPK; /* explicit IPK column */ |
| 1190 goto rbuTableType_end; |
| 1191 } |
| 1192 } |
| 1193 *peType = RBU_PK_NONE; |
| 1194 } |
| 1195 |
| 1196 rbuTableType_end: { |
| 1197 unsigned int i; |
| 1198 for(i=0; i<sizeof(aStmt)/sizeof(aStmt[0]); i++){ |
| 1199 rbuFinalize(p, aStmt[i]); |
| 1200 } |
| 1201 } |
| 1202 } |
| 1203 |
| 1204 /* |
| 1205 ** This is a helper function for rbuObjIterCacheTableInfo(). It populates |
| 1206 ** the pIter->abIndexed[] array. |
| 1207 */ |
| 1208 static void rbuObjIterCacheIndexedCols(sqlite3rbu *p, RbuObjIter *pIter){ |
| 1209 sqlite3_stmt *pList = 0; |
| 1210 int bIndex = 0; |
| 1211 |
| 1212 if( p->rc==SQLITE_OK ){ |
| 1213 memcpy(pIter->abIndexed, pIter->abTblPk, sizeof(u8)*pIter->nTblCol); |
| 1214 p->rc = prepareFreeAndCollectError(p->dbMain, &pList, &p->zErrmsg, |
| 1215 sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl) |
| 1216 ); |
| 1217 } |
| 1218 |
| 1219 pIter->nIndex = 0; |
| 1220 while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pList) ){ |
| 1221 const char *zIdx = (const char*)sqlite3_column_text(pList, 1); |
| 1222 sqlite3_stmt *pXInfo = 0; |
| 1223 if( zIdx==0 ) break; |
| 1224 p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg, |
| 1225 sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx) |
| 1226 ); |
| 1227 while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){ |
| 1228 int iCid = sqlite3_column_int(pXInfo, 1); |
| 1229 if( iCid>=0 ) pIter->abIndexed[iCid] = 1; |
| 1230 } |
| 1231 rbuFinalize(p, pXInfo); |
| 1232 bIndex = 1; |
| 1233 pIter->nIndex++; |
| 1234 } |
| 1235 |
| 1236 if( pIter->eType==RBU_PK_WITHOUT_ROWID ){ |
| 1237 /* "PRAGMA index_list" includes the main PK b-tree */ |
| 1238 pIter->nIndex--; |
| 1239 } |
| 1240 |
| 1241 rbuFinalize(p, pList); |
| 1242 if( bIndex==0 ) pIter->abIndexed = 0; |
| 1243 } |
| 1244 |
| 1245 |
| 1246 /* |
| 1247 ** If they are not already populated, populate the pIter->azTblCol[], |
| 1248 ** pIter->abTblPk[], pIter->nTblCol and pIter->bRowid variables according to |
| 1249 ** the table (not index) that the iterator currently points to. |
| 1250 ** |
| 1251 ** Return SQLITE_OK if successful, or an SQLite error code otherwise. If |
| 1252 ** an error does occur, an error code and error message are also left in |
| 1253 ** the RBU handle. |
| 1254 */ |
| 1255 static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){ |
| 1256 if( pIter->azTblCol==0 ){ |
| 1257 sqlite3_stmt *pStmt = 0; |
| 1258 int nCol = 0; |
| 1259 int i; /* for() loop iterator variable */ |
| 1260 int bRbuRowid = 0; /* If input table has column "rbu_rowid" */ |
| 1261 int iOrder = 0; |
| 1262 int iTnum = 0; |
| 1263 |
| 1264 /* Figure out the type of table this step will deal with. */ |
| 1265 assert( pIter->eType==0 ); |
| 1266 rbuTableType(p, pIter->zTbl, &pIter->eType, &iTnum, &pIter->iPkTnum); |
| 1267 if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_NOTABLE ){ |
| 1268 p->rc = SQLITE_ERROR; |
| 1269 p->zErrmsg = sqlite3_mprintf("no such table: %s", pIter->zTbl); |
| 1270 } |
| 1271 if( p->rc ) return p->rc; |
| 1272 if( pIter->zIdx==0 ) pIter->iTnum = iTnum; |
| 1273 |
| 1274 assert( pIter->eType==RBU_PK_NONE || pIter->eType==RBU_PK_IPK |
| 1275 || pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_WITHOUT_ROWID |
| 1276 || pIter->eType==RBU_PK_VTAB |
| 1277 ); |
| 1278 |
| 1279 /* Populate the azTblCol[] and nTblCol variables based on the columns |
| 1280 ** of the input table. Ignore any input table columns that begin with |
| 1281 ** "rbu_". */ |
| 1282 p->rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg, |
| 1283 sqlite3_mprintf("SELECT * FROM '%q'", pIter->zDataTbl) |
| 1284 ); |
| 1285 if( p->rc==SQLITE_OK ){ |
| 1286 nCol = sqlite3_column_count(pStmt); |
| 1287 rbuAllocateIterArrays(p, pIter, nCol); |
| 1288 } |
| 1289 for(i=0; p->rc==SQLITE_OK && i<nCol; i++){ |
| 1290 const char *zName = (const char*)sqlite3_column_name(pStmt, i); |
| 1291 if( sqlite3_strnicmp("rbu_", zName, 4) ){ |
| 1292 char *zCopy = rbuStrndup(zName, &p->rc); |
| 1293 pIter->aiSrcOrder[pIter->nTblCol] = pIter->nTblCol; |
| 1294 pIter->azTblCol[pIter->nTblCol++] = zCopy; |
| 1295 } |
| 1296 else if( 0==sqlite3_stricmp("rbu_rowid", zName) ){ |
| 1297 bRbuRowid = 1; |
| 1298 } |
| 1299 } |
| 1300 sqlite3_finalize(pStmt); |
| 1301 pStmt = 0; |
| 1302 |
| 1303 if( p->rc==SQLITE_OK |
| 1304 && rbuIsVacuum(p)==0 |
| 1305 && bRbuRowid!=(pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE) |
| 1306 ){ |
| 1307 p->rc = SQLITE_ERROR; |
| 1308 p->zErrmsg = sqlite3_mprintf( |
| 1309 "table %q %s rbu_rowid column", pIter->zDataTbl, |
| 1310 (bRbuRowid ? "may not have" : "requires") |
| 1311 ); |
| 1312 } |
| 1313 |
| 1314 /* Check that all non-HIDDEN columns in the destination table are also |
| 1315 ** present in the input table. Populate the abTblPk[], azTblType[] and |
| 1316 ** aiTblOrder[] arrays at the same time. */ |
| 1317 if( p->rc==SQLITE_OK ){ |
| 1318 p->rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &p->zErrmsg, |
| 1319 sqlite3_mprintf("PRAGMA table_info(%Q)", pIter->zTbl) |
| 1320 ); |
| 1321 } |
| 1322 while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ |
| 1323 const char *zName = (const char*)sqlite3_column_text(pStmt, 1); |
| 1324 if( zName==0 ) break; /* An OOM - finalize() below returns S_NOMEM */ |
| 1325 for(i=iOrder; i<pIter->nTblCol; i++){ |
| 1326 if( 0==strcmp(zName, pIter->azTblCol[i]) ) break; |
| 1327 } |
| 1328 if( i==pIter->nTblCol ){ |
| 1329 p->rc = SQLITE_ERROR; |
| 1330 p->zErrmsg = sqlite3_mprintf("column missing from %q: %s", |
| 1331 pIter->zDataTbl, zName |
| 1332 ); |
| 1333 }else{ |
| 1334 int iPk = sqlite3_column_int(pStmt, 5); |
| 1335 int bNotNull = sqlite3_column_int(pStmt, 3); |
| 1336 const char *zType = (const char*)sqlite3_column_text(pStmt, 2); |
| 1337 |
| 1338 if( i!=iOrder ){ |
| 1339 SWAP(int, pIter->aiSrcOrder[i], pIter->aiSrcOrder[iOrder]); |
| 1340 SWAP(char*, pIter->azTblCol[i], pIter->azTblCol[iOrder]); |
| 1341 } |
| 1342 |
| 1343 pIter->azTblType[iOrder] = rbuStrndup(zType, &p->rc); |
| 1344 pIter->abTblPk[iOrder] = (iPk!=0); |
| 1345 pIter->abNotNull[iOrder] = (u8)bNotNull || (iPk!=0); |
| 1346 iOrder++; |
| 1347 } |
| 1348 } |
| 1349 |
| 1350 rbuFinalize(p, pStmt); |
| 1351 rbuObjIterCacheIndexedCols(p, pIter); |
| 1352 assert( pIter->eType!=RBU_PK_VTAB || pIter->abIndexed==0 ); |
| 1353 assert( pIter->eType!=RBU_PK_VTAB || pIter->nIndex==0 ); |
| 1354 } |
| 1355 |
| 1356 return p->rc; |
| 1357 } |
| 1358 |
| 1359 /* |
| 1360 ** This function constructs and returns a pointer to a nul-terminated |
| 1361 ** string containing some SQL clause or list based on one or more of the |
| 1362 ** column names currently stored in the pIter->azTblCol[] array. |
| 1363 */ |
| 1364 static char *rbuObjIterGetCollist( |
| 1365 sqlite3rbu *p, /* RBU object */ |
| 1366 RbuObjIter *pIter /* Object iterator for column names */ |
| 1367 ){ |
| 1368 char *zList = 0; |
| 1369 const char *zSep = ""; |
| 1370 int i; |
| 1371 for(i=0; i<pIter->nTblCol; i++){ |
| 1372 const char *z = pIter->azTblCol[i]; |
| 1373 zList = rbuMPrintf(p, "%z%s\"%w\"", zList, zSep, z); |
| 1374 zSep = ", "; |
| 1375 } |
| 1376 return zList; |
| 1377 } |
| 1378 |
| 1379 /* |
| 1380 ** This function is used to create a SELECT list (the list of SQL |
| 1381 ** expressions that follows a SELECT keyword) for a SELECT statement |
| 1382 ** used to read from an data_xxx or rbu_tmp_xxx table while updating the |
| 1383 ** index object currently indicated by the iterator object passed as the |
| 1384 ** second argument. A "PRAGMA index_xinfo = <idxname>" statement is used |
| 1385 ** to obtain the required information. |
| 1386 ** |
| 1387 ** If the index is of the following form: |
| 1388 ** |
| 1389 ** CREATE INDEX i1 ON t1(c, b COLLATE nocase); |
| 1390 ** |
| 1391 ** and "t1" is a table with an explicit INTEGER PRIMARY KEY column |
| 1392 ** "ipk", the returned string is: |
| 1393 ** |
| 1394 ** "`c` COLLATE 'BINARY', `b` COLLATE 'NOCASE', `ipk` COLLATE 'BINARY'" |
| 1395 ** |
| 1396 ** As well as the returned string, three other malloc'd strings are |
| 1397 ** returned via output parameters. As follows: |
| 1398 ** |
| 1399 ** pzImposterCols: ... |
| 1400 ** pzImposterPk: ... |
| 1401 ** pzWhere: ... |
| 1402 */ |
| 1403 static char *rbuObjIterGetIndexCols( |
| 1404 sqlite3rbu *p, /* RBU object */ |
| 1405 RbuObjIter *pIter, /* Object iterator for column names */ |
| 1406 char **pzImposterCols, /* OUT: Columns for imposter table */ |
| 1407 char **pzImposterPk, /* OUT: Imposter PK clause */ |
| 1408 char **pzWhere, /* OUT: WHERE clause */ |
| 1409 int *pnBind /* OUT: Trbul number of columns */ |
| 1410 ){ |
| 1411 int rc = p->rc; /* Error code */ |
| 1412 int rc2; /* sqlite3_finalize() return code */ |
| 1413 char *zRet = 0; /* String to return */ |
| 1414 char *zImpCols = 0; /* String to return via *pzImposterCols */ |
| 1415 char *zImpPK = 0; /* String to return via *pzImposterPK */ |
| 1416 char *zWhere = 0; /* String to return via *pzWhere */ |
| 1417 int nBind = 0; /* Value to return via *pnBind */ |
| 1418 const char *zCom = ""; /* Set to ", " later on */ |
| 1419 const char *zAnd = ""; /* Set to " AND " later on */ |
| 1420 sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = ? */ |
| 1421 |
| 1422 if( rc==SQLITE_OK ){ |
| 1423 assert( p->zErrmsg==0 ); |
| 1424 rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg, |
| 1425 sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter->zIdx) |
| 1426 ); |
| 1427 } |
| 1428 |
| 1429 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){ |
| 1430 int iCid = sqlite3_column_int(pXInfo, 1); |
| 1431 int bDesc = sqlite3_column_int(pXInfo, 3); |
| 1432 const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4); |
| 1433 const char *zCol; |
| 1434 const char *zType; |
| 1435 |
| 1436 if( iCid<0 ){ |
| 1437 /* An integer primary key. If the table has an explicit IPK, use |
| 1438 ** its name. Otherwise, use "rbu_rowid". */ |
| 1439 if( pIter->eType==RBU_PK_IPK ){ |
| 1440 int i; |
| 1441 for(i=0; pIter->abTblPk[i]==0; i++); |
| 1442 assert( i<pIter->nTblCol ); |
| 1443 zCol = pIter->azTblCol[i]; |
| 1444 }else if( rbuIsVacuum(p) ){ |
| 1445 zCol = "_rowid_"; |
| 1446 }else{ |
| 1447 zCol = "rbu_rowid"; |
| 1448 } |
| 1449 zType = "INTEGER"; |
| 1450 }else{ |
| 1451 zCol = pIter->azTblCol[iCid]; |
| 1452 zType = pIter->azTblType[iCid]; |
| 1453 } |
| 1454 |
| 1455 zRet = sqlite3_mprintf("%z%s\"%w\" COLLATE %Q", zRet, zCom, zCol, zCollate); |
| 1456 if( pIter->bUnique==0 || sqlite3_column_int(pXInfo, 5) ){ |
| 1457 const char *zOrder = (bDesc ? " DESC" : ""); |
| 1458 zImpPK = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\"%s", |
| 1459 zImpPK, zCom, nBind, zCol, zOrder |
| 1460 ); |
| 1461 } |
| 1462 zImpCols = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\" %s COLLATE %Q", |
| 1463 zImpCols, zCom, nBind, zCol, zType, zCollate |
| 1464 ); |
| 1465 zWhere = sqlite3_mprintf( |
| 1466 "%z%s\"rbu_imp_%d%w\" IS ?", zWhere, zAnd, nBind, zCol |
| 1467 ); |
| 1468 if( zRet==0 || zImpPK==0 || zImpCols==0 || zWhere==0 ) rc = SQLITE_NOMEM; |
| 1469 zCom = ", "; |
| 1470 zAnd = " AND "; |
| 1471 nBind++; |
| 1472 } |
| 1473 |
| 1474 rc2 = sqlite3_finalize(pXInfo); |
| 1475 if( rc==SQLITE_OK ) rc = rc2; |
| 1476 |
| 1477 if( rc!=SQLITE_OK ){ |
| 1478 sqlite3_free(zRet); |
| 1479 sqlite3_free(zImpCols); |
| 1480 sqlite3_free(zImpPK); |
| 1481 sqlite3_free(zWhere); |
| 1482 zRet = 0; |
| 1483 zImpCols = 0; |
| 1484 zImpPK = 0; |
| 1485 zWhere = 0; |
| 1486 p->rc = rc; |
| 1487 } |
| 1488 |
| 1489 *pzImposterCols = zImpCols; |
| 1490 *pzImposterPk = zImpPK; |
| 1491 *pzWhere = zWhere; |
| 1492 *pnBind = nBind; |
| 1493 return zRet; |
| 1494 } |
| 1495 |
| 1496 /* |
| 1497 ** Assuming the current table columns are "a", "b" and "c", and the zObj |
| 1498 ** paramter is passed "old", return a string of the form: |
| 1499 ** |
| 1500 ** "old.a, old.b, old.b" |
| 1501 ** |
| 1502 ** With the column names escaped. |
| 1503 ** |
| 1504 ** For tables with implicit rowids - RBU_PK_EXTERNAL and RBU_PK_NONE, append |
| 1505 ** the text ", old._rowid_" to the returned value. |
| 1506 */ |
| 1507 static char *rbuObjIterGetOldlist( |
| 1508 sqlite3rbu *p, |
| 1509 RbuObjIter *pIter, |
| 1510 const char *zObj |
| 1511 ){ |
| 1512 char *zList = 0; |
| 1513 if( p->rc==SQLITE_OK && pIter->abIndexed ){ |
| 1514 const char *zS = ""; |
| 1515 int i; |
| 1516 for(i=0; i<pIter->nTblCol; i++){ |
| 1517 if( pIter->abIndexed[i] ){ |
| 1518 const char *zCol = pIter->azTblCol[i]; |
| 1519 zList = sqlite3_mprintf("%z%s%s.\"%w\"", zList, zS, zObj, zCol); |
| 1520 }else{ |
| 1521 zList = sqlite3_mprintf("%z%sNULL", zList, zS); |
| 1522 } |
| 1523 zS = ", "; |
| 1524 if( zList==0 ){ |
| 1525 p->rc = SQLITE_NOMEM; |
| 1526 break; |
| 1527 } |
| 1528 } |
| 1529 |
| 1530 /* For a table with implicit rowids, append "old._rowid_" to the list. */ |
| 1531 if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){ |
| 1532 zList = rbuMPrintf(p, "%z, %s._rowid_", zList, zObj); |
| 1533 } |
| 1534 } |
| 1535 return zList; |
| 1536 } |
| 1537 |
| 1538 /* |
| 1539 ** Return an expression that can be used in a WHERE clause to match the |
| 1540 ** primary key of the current table. For example, if the table is: |
| 1541 ** |
| 1542 ** CREATE TABLE t1(a, b, c, PRIMARY KEY(b, c)); |
| 1543 ** |
| 1544 ** Return the string: |
| 1545 ** |
| 1546 ** "b = ?1 AND c = ?2" |
| 1547 */ |
| 1548 static char *rbuObjIterGetWhere( |
| 1549 sqlite3rbu *p, |
| 1550 RbuObjIter *pIter |
| 1551 ){ |
| 1552 char *zList = 0; |
| 1553 if( pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE ){ |
| 1554 zList = rbuMPrintf(p, "_rowid_ = ?%d", pIter->nTblCol+1); |
| 1555 }else if( pIter->eType==RBU_PK_EXTERNAL ){ |
| 1556 const char *zSep = ""; |
| 1557 int i; |
| 1558 for(i=0; i<pIter->nTblCol; i++){ |
| 1559 if( pIter->abTblPk[i] ){ |
| 1560 zList = rbuMPrintf(p, "%z%sc%d=?%d", zList, zSep, i, i+1); |
| 1561 zSep = " AND "; |
| 1562 } |
| 1563 } |
| 1564 zList = rbuMPrintf(p, |
| 1565 "_rowid_ = (SELECT id FROM rbu_imposter2 WHERE %z)", zList |
| 1566 ); |
| 1567 |
| 1568 }else{ |
| 1569 const char *zSep = ""; |
| 1570 int i; |
| 1571 for(i=0; i<pIter->nTblCol; i++){ |
| 1572 if( pIter->abTblPk[i] ){ |
| 1573 const char *zCol = pIter->azTblCol[i]; |
| 1574 zList = rbuMPrintf(p, "%z%s\"%w\"=?%d", zList, zSep, zCol, i+1); |
| 1575 zSep = " AND "; |
| 1576 } |
| 1577 } |
| 1578 } |
| 1579 return zList; |
| 1580 } |
| 1581 |
| 1582 /* |
| 1583 ** The SELECT statement iterating through the keys for the current object |
| 1584 ** (p->objiter.pSelect) currently points to a valid row. However, there |
| 1585 ** is something wrong with the rbu_control value in the rbu_control value |
| 1586 ** stored in the (p->nCol+1)'th column. Set the error code and error message |
| 1587 ** of the RBU handle to something reflecting this. |
| 1588 */ |
| 1589 static void rbuBadControlError(sqlite3rbu *p){ |
| 1590 p->rc = SQLITE_ERROR; |
| 1591 p->zErrmsg = sqlite3_mprintf("invalid rbu_control value"); |
| 1592 } |
| 1593 |
| 1594 |
| 1595 /* |
| 1596 ** Return a nul-terminated string containing the comma separated list of |
| 1597 ** assignments that should be included following the "SET" keyword of |
| 1598 ** an UPDATE statement used to update the table object that the iterator |
| 1599 ** passed as the second argument currently points to if the rbu_control |
| 1600 ** column of the data_xxx table entry is set to zMask. |
| 1601 ** |
| 1602 ** The memory for the returned string is obtained from sqlite3_malloc(). |
| 1603 ** It is the responsibility of the caller to eventually free it using |
| 1604 ** sqlite3_free(). |
| 1605 ** |
| 1606 ** If an OOM error is encountered when allocating space for the new |
| 1607 ** string, an error code is left in the rbu handle passed as the first |
| 1608 ** argument and NULL is returned. Or, if an error has already occurred |
| 1609 ** when this function is called, NULL is returned immediately, without |
| 1610 ** attempting the allocation or modifying the stored error code. |
| 1611 */ |
| 1612 static char *rbuObjIterGetSetlist( |
| 1613 sqlite3rbu *p, |
| 1614 RbuObjIter *pIter, |
| 1615 const char *zMask |
| 1616 ){ |
| 1617 char *zList = 0; |
| 1618 if( p->rc==SQLITE_OK ){ |
| 1619 int i; |
| 1620 |
| 1621 if( (int)strlen(zMask)!=pIter->nTblCol ){ |
| 1622 rbuBadControlError(p); |
| 1623 }else{ |
| 1624 const char *zSep = ""; |
| 1625 for(i=0; i<pIter->nTblCol; i++){ |
| 1626 char c = zMask[pIter->aiSrcOrder[i]]; |
| 1627 if( c=='x' ){ |
| 1628 zList = rbuMPrintf(p, "%z%s\"%w\"=?%d", |
| 1629 zList, zSep, pIter->azTblCol[i], i+1 |
| 1630 ); |
| 1631 zSep = ", "; |
| 1632 } |
| 1633 else if( c=='d' ){ |
| 1634 zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_delta(\"%w\", ?%d)", |
| 1635 zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1 |
| 1636 ); |
| 1637 zSep = ", "; |
| 1638 } |
| 1639 else if( c=='f' ){ |
| 1640 zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_fossil_delta(\"%w\", ?%d)", |
| 1641 zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1 |
| 1642 ); |
| 1643 zSep = ", "; |
| 1644 } |
| 1645 } |
| 1646 } |
| 1647 } |
| 1648 return zList; |
| 1649 } |
| 1650 |
| 1651 /* |
| 1652 ** Return a nul-terminated string consisting of nByte comma separated |
| 1653 ** "?" expressions. For example, if nByte is 3, return a pointer to |
| 1654 ** a buffer containing the string "?,?,?". |
| 1655 ** |
| 1656 ** The memory for the returned string is obtained from sqlite3_malloc(). |
| 1657 ** It is the responsibility of the caller to eventually free it using |
| 1658 ** sqlite3_free(). |
| 1659 ** |
| 1660 ** If an OOM error is encountered when allocating space for the new |
| 1661 ** string, an error code is left in the rbu handle passed as the first |
| 1662 ** argument and NULL is returned. Or, if an error has already occurred |
| 1663 ** when this function is called, NULL is returned immediately, without |
| 1664 ** attempting the allocation or modifying the stored error code. |
| 1665 */ |
| 1666 static char *rbuObjIterGetBindlist(sqlite3rbu *p, int nBind){ |
| 1667 char *zRet = 0; |
| 1668 int nByte = nBind*2 + 1; |
| 1669 |
| 1670 zRet = (char*)rbuMalloc(p, nByte); |
| 1671 if( zRet ){ |
| 1672 int i; |
| 1673 for(i=0; i<nBind; i++){ |
| 1674 zRet[i*2] = '?'; |
| 1675 zRet[i*2+1] = (i+1==nBind) ? '\0' : ','; |
| 1676 } |
| 1677 } |
| 1678 return zRet; |
| 1679 } |
| 1680 |
| 1681 /* |
| 1682 ** The iterator currently points to a table (not index) of type |
| 1683 ** RBU_PK_WITHOUT_ROWID. This function creates the PRIMARY KEY |
| 1684 ** declaration for the corresponding imposter table. For example, |
| 1685 ** if the iterator points to a table created as: |
| 1686 ** |
| 1687 ** CREATE TABLE t1(a, b, c, PRIMARY KEY(b, a DESC)) WITHOUT ROWID |
| 1688 ** |
| 1689 ** this function returns: |
| 1690 ** |
| 1691 ** PRIMARY KEY("b", "a" DESC) |
| 1692 */ |
| 1693 static char *rbuWithoutRowidPK(sqlite3rbu *p, RbuObjIter *pIter){ |
| 1694 char *z = 0; |
| 1695 assert( pIter->zIdx==0 ); |
| 1696 if( p->rc==SQLITE_OK ){ |
| 1697 const char *zSep = "PRIMARY KEY("; |
| 1698 sqlite3_stmt *pXList = 0; /* PRAGMA index_list = (pIter->zTbl) */ |
| 1699 sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = <pk-index> */ |
| 1700 |
| 1701 p->rc = prepareFreeAndCollectError(p->dbMain, &pXList, &p->zErrmsg, |
| 1702 sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl) |
| 1703 ); |
| 1704 while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXList) ){ |
| 1705 const char *zOrig = (const char*)sqlite3_column_text(pXList,3); |
| 1706 if( zOrig && strcmp(zOrig, "pk")==0 ){ |
| 1707 const char *zIdx = (const char*)sqlite3_column_text(pXList,1); |
| 1708 if( zIdx ){ |
| 1709 p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg, |
| 1710 sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx) |
| 1711 ); |
| 1712 } |
| 1713 break; |
| 1714 } |
| 1715 } |
| 1716 rbuFinalize(p, pXList); |
| 1717 |
| 1718 while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){ |
| 1719 if( sqlite3_column_int(pXInfo, 5) ){ |
| 1720 /* int iCid = sqlite3_column_int(pXInfo, 0); */ |
| 1721 const char *zCol = (const char*)sqlite3_column_text(pXInfo, 2); |
| 1722 const char *zDesc = sqlite3_column_int(pXInfo, 3) ? " DESC" : ""; |
| 1723 z = rbuMPrintf(p, "%z%s\"%w\"%s", z, zSep, zCol, zDesc); |
| 1724 zSep = ", "; |
| 1725 } |
| 1726 } |
| 1727 z = rbuMPrintf(p, "%z)", z); |
| 1728 rbuFinalize(p, pXInfo); |
| 1729 } |
| 1730 return z; |
| 1731 } |
| 1732 |
| 1733 /* |
| 1734 ** This function creates the second imposter table used when writing to |
| 1735 ** a table b-tree where the table has an external primary key. If the |
| 1736 ** iterator passed as the second argument does not currently point to |
| 1737 ** a table (not index) with an external primary key, this function is a |
| 1738 ** no-op. |
| 1739 ** |
| 1740 ** Assuming the iterator does point to a table with an external PK, this |
| 1741 ** function creates a WITHOUT ROWID imposter table named "rbu_imposter2" |
| 1742 ** used to access that PK index. For example, if the target table is |
| 1743 ** declared as follows: |
| 1744 ** |
| 1745 ** CREATE TABLE t1(a, b TEXT, c REAL, PRIMARY KEY(b, c)); |
| 1746 ** |
| 1747 ** then the imposter table schema is: |
| 1748 ** |
| 1749 ** CREATE TABLE rbu_imposter2(c1 TEXT, c2 REAL, id INTEGER) WITHOUT ROWID; |
| 1750 ** |
| 1751 */ |
| 1752 static void rbuCreateImposterTable2(sqlite3rbu *p, RbuObjIter *pIter){ |
| 1753 if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_EXTERNAL ){ |
| 1754 int tnum = pIter->iPkTnum; /* Root page of PK index */ |
| 1755 sqlite3_stmt *pQuery = 0; /* SELECT name ... WHERE rootpage = $tnum */ |
| 1756 const char *zIdx = 0; /* Name of PK index */ |
| 1757 sqlite3_stmt *pXInfo = 0; /* PRAGMA main.index_xinfo = $zIdx */ |
| 1758 const char *zComma = ""; |
| 1759 char *zCols = 0; /* Used to build up list of table cols */ |
| 1760 char *zPk = 0; /* Used to build up table PK declaration */ |
| 1761 |
| 1762 /* Figure out the name of the primary key index for the current table. |
| 1763 ** This is needed for the argument to "PRAGMA index_xinfo". Set |
| 1764 ** zIdx to point to a nul-terminated string containing this name. */ |
| 1765 p->rc = prepareAndCollectError(p->dbMain, &pQuery, &p->zErrmsg, |
| 1766 "SELECT name FROM sqlite_master WHERE rootpage = ?" |
| 1767 ); |
| 1768 if( p->rc==SQLITE_OK ){ |
| 1769 sqlite3_bind_int(pQuery, 1, tnum); |
| 1770 if( SQLITE_ROW==sqlite3_step(pQuery) ){ |
| 1771 zIdx = (const char*)sqlite3_column_text(pQuery, 0); |
| 1772 } |
| 1773 } |
| 1774 if( zIdx ){ |
| 1775 p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg, |
| 1776 sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx) |
| 1777 ); |
| 1778 } |
| 1779 rbuFinalize(p, pQuery); |
| 1780 |
| 1781 while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){ |
| 1782 int bKey = sqlite3_column_int(pXInfo, 5); |
| 1783 if( bKey ){ |
| 1784 int iCid = sqlite3_column_int(pXInfo, 1); |
| 1785 int bDesc = sqlite3_column_int(pXInfo, 3); |
| 1786 const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4); |
| 1787 zCols = rbuMPrintf(p, "%z%sc%d %s COLLATE %s", zCols, zComma, |
| 1788 iCid, pIter->azTblType[iCid], zCollate |
| 1789 ); |
| 1790 zPk = rbuMPrintf(p, "%z%sc%d%s", zPk, zComma, iCid, bDesc?" DESC":""); |
| 1791 zComma = ", "; |
| 1792 } |
| 1793 } |
| 1794 zCols = rbuMPrintf(p, "%z, id INTEGER", zCols); |
| 1795 rbuFinalize(p, pXInfo); |
| 1796 |
| 1797 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum); |
| 1798 rbuMPrintfExec(p, p->dbMain, |
| 1799 "CREATE TABLE rbu_imposter2(%z, PRIMARY KEY(%z)) WITHOUT ROWID", |
| 1800 zCols, zPk |
| 1801 ); |
| 1802 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0); |
| 1803 } |
| 1804 } |
| 1805 |
| 1806 /* |
| 1807 ** If an error has already occurred when this function is called, it |
| 1808 ** immediately returns zero (without doing any work). Or, if an error |
| 1809 ** occurs during the execution of this function, it sets the error code |
| 1810 ** in the sqlite3rbu object indicated by the first argument and returns |
| 1811 ** zero. |
| 1812 ** |
| 1813 ** The iterator passed as the second argument is guaranteed to point to |
| 1814 ** a table (not an index) when this function is called. This function |
| 1815 ** attempts to create any imposter table required to write to the main |
| 1816 ** table b-tree of the table before returning. Non-zero is returned if |
| 1817 ** an imposter table are created, or zero otherwise. |
| 1818 ** |
| 1819 ** An imposter table is required in all cases except RBU_PK_VTAB. Only |
| 1820 ** virtual tables are written to directly. The imposter table has the |
| 1821 ** same schema as the actual target table (less any UNIQUE constraints). |
| 1822 ** More precisely, the "same schema" means the same columns, types, |
| 1823 ** collation sequences. For tables that do not have an external PRIMARY |
| 1824 ** KEY, it also means the same PRIMARY KEY declaration. |
| 1825 */ |
| 1826 static void rbuCreateImposterTable(sqlite3rbu *p, RbuObjIter *pIter){ |
| 1827 if( p->rc==SQLITE_OK && pIter->eType!=RBU_PK_VTAB ){ |
| 1828 int tnum = pIter->iTnum; |
| 1829 const char *zComma = ""; |
| 1830 char *zSql = 0; |
| 1831 int iCol; |
| 1832 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1); |
| 1833 |
| 1834 for(iCol=0; p->rc==SQLITE_OK && iCol<pIter->nTblCol; iCol++){ |
| 1835 const char *zPk = ""; |
| 1836 const char *zCol = pIter->azTblCol[iCol]; |
| 1837 const char *zColl = 0; |
| 1838 |
| 1839 p->rc = sqlite3_table_column_metadata( |
| 1840 p->dbMain, "main", pIter->zTbl, zCol, 0, &zColl, 0, 0, 0 |
| 1841 ); |
| 1842 |
| 1843 if( pIter->eType==RBU_PK_IPK && pIter->abTblPk[iCol] ){ |
| 1844 /* If the target table column is an "INTEGER PRIMARY KEY", add |
| 1845 ** "PRIMARY KEY" to the imposter table column declaration. */ |
| 1846 zPk = "PRIMARY KEY "; |
| 1847 } |
| 1848 zSql = rbuMPrintf(p, "%z%s\"%w\" %s %sCOLLATE %s%s", |
| 1849 zSql, zComma, zCol, pIter->azTblType[iCol], zPk, zColl, |
| 1850 (pIter->abNotNull[iCol] ? " NOT NULL" : "") |
| 1851 ); |
| 1852 zComma = ", "; |
| 1853 } |
| 1854 |
| 1855 if( pIter->eType==RBU_PK_WITHOUT_ROWID ){ |
| 1856 char *zPk = rbuWithoutRowidPK(p, pIter); |
| 1857 if( zPk ){ |
| 1858 zSql = rbuMPrintf(p, "%z, %z", zSql, zPk); |
| 1859 } |
| 1860 } |
| 1861 |
| 1862 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum); |
| 1863 rbuMPrintfExec(p, p->dbMain, "CREATE TABLE \"rbu_imp_%w\"(%z)%s", |
| 1864 pIter->zTbl, zSql, |
| 1865 (pIter->eType==RBU_PK_WITHOUT_ROWID ? " WITHOUT ROWID" : "") |
| 1866 ); |
| 1867 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0); |
| 1868 } |
| 1869 } |
| 1870 |
| 1871 /* |
| 1872 ** Prepare a statement used to insert rows into the "rbu_tmp_xxx" table. |
| 1873 ** Specifically a statement of the form: |
| 1874 ** |
| 1875 ** INSERT INTO rbu_tmp_xxx VALUES(?, ?, ? ...); |
| 1876 ** |
| 1877 ** The number of bound variables is equal to the number of columns in |
| 1878 ** the target table, plus one (for the rbu_control column), plus one more |
| 1879 ** (for the rbu_rowid column) if the target table is an implicit IPK or |
| 1880 ** virtual table. |
| 1881 */ |
| 1882 static void rbuObjIterPrepareTmpInsert( |
| 1883 sqlite3rbu *p, |
| 1884 RbuObjIter *pIter, |
| 1885 const char *zCollist, |
| 1886 const char *zRbuRowid |
| 1887 ){ |
| 1888 int bRbuRowid = (pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE); |
| 1889 char *zBind = rbuObjIterGetBindlist(p, pIter->nTblCol + 1 + bRbuRowid); |
| 1890 if( zBind ){ |
| 1891 assert( pIter->pTmpInsert==0 ); |
| 1892 p->rc = prepareFreeAndCollectError( |
| 1893 p->dbRbu, &pIter->pTmpInsert, &p->zErrmsg, sqlite3_mprintf( |
| 1894 "INSERT INTO %s.'rbu_tmp_%q'(rbu_control,%s%s) VALUES(%z)", |
| 1895 p->zStateDb, pIter->zDataTbl, zCollist, zRbuRowid, zBind |
| 1896 )); |
| 1897 } |
| 1898 } |
| 1899 |
| 1900 static void rbuTmpInsertFunc( |
| 1901 sqlite3_context *pCtx, |
| 1902 int nVal, |
| 1903 sqlite3_value **apVal |
| 1904 ){ |
| 1905 sqlite3rbu *p = sqlite3_user_data(pCtx); |
| 1906 int rc = SQLITE_OK; |
| 1907 int i; |
| 1908 |
| 1909 assert( sqlite3_value_int(apVal[0])!=0 |
| 1910 || p->objiter.eType==RBU_PK_EXTERNAL |
| 1911 || p->objiter.eType==RBU_PK_NONE |
| 1912 ); |
| 1913 if( sqlite3_value_int(apVal[0])!=0 ){ |
| 1914 p->nPhaseOneStep += p->objiter.nIndex; |
| 1915 } |
| 1916 |
| 1917 for(i=0; rc==SQLITE_OK && i<nVal; i++){ |
| 1918 rc = sqlite3_bind_value(p->objiter.pTmpInsert, i+1, apVal[i]); |
| 1919 } |
| 1920 if( rc==SQLITE_OK ){ |
| 1921 sqlite3_step(p->objiter.pTmpInsert); |
| 1922 rc = sqlite3_reset(p->objiter.pTmpInsert); |
| 1923 } |
| 1924 |
| 1925 if( rc!=SQLITE_OK ){ |
| 1926 sqlite3_result_error_code(pCtx, rc); |
| 1927 } |
| 1928 } |
| 1929 |
| 1930 /* |
| 1931 ** Ensure that the SQLite statement handles required to update the |
| 1932 ** target database object currently indicated by the iterator passed |
| 1933 ** as the second argument are available. |
| 1934 */ |
| 1935 static int rbuObjIterPrepareAll( |
| 1936 sqlite3rbu *p, |
| 1937 RbuObjIter *pIter, |
| 1938 int nOffset /* Add "LIMIT -1 OFFSET $nOffset" to SELECT */ |
| 1939 ){ |
| 1940 assert( pIter->bCleanup==0 ); |
| 1941 if( pIter->pSelect==0 && rbuObjIterCacheTableInfo(p, pIter)==SQLITE_OK ){ |
| 1942 const int tnum = pIter->iTnum; |
| 1943 char *zCollist = 0; /* List of indexed columns */ |
| 1944 char **pz = &p->zErrmsg; |
| 1945 const char *zIdx = pIter->zIdx; |
| 1946 char *zLimit = 0; |
| 1947 |
| 1948 if( nOffset ){ |
| 1949 zLimit = sqlite3_mprintf(" LIMIT -1 OFFSET %d", nOffset); |
| 1950 if( !zLimit ) p->rc = SQLITE_NOMEM; |
| 1951 } |
| 1952 |
| 1953 if( zIdx ){ |
| 1954 const char *zTbl = pIter->zTbl; |
| 1955 char *zImposterCols = 0; /* Columns for imposter table */ |
| 1956 char *zImposterPK = 0; /* Primary key declaration for imposter */ |
| 1957 char *zWhere = 0; /* WHERE clause on PK columns */ |
| 1958 char *zBind = 0; |
| 1959 int nBind = 0; |
| 1960 |
| 1961 assert( pIter->eType!=RBU_PK_VTAB ); |
| 1962 zCollist = rbuObjIterGetIndexCols( |
| 1963 p, pIter, &zImposterCols, &zImposterPK, &zWhere, &nBind |
| 1964 ); |
| 1965 zBind = rbuObjIterGetBindlist(p, nBind); |
| 1966 |
| 1967 /* Create the imposter table used to write to this index. */ |
| 1968 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1); |
| 1969 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1,tnum); |
| 1970 rbuMPrintfExec(p, p->dbMain, |
| 1971 "CREATE TABLE \"rbu_imp_%w\"( %s, PRIMARY KEY( %s ) ) WITHOUT ROWID", |
| 1972 zTbl, zImposterCols, zImposterPK |
| 1973 ); |
| 1974 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0); |
| 1975 |
| 1976 /* Create the statement to insert index entries */ |
| 1977 pIter->nCol = nBind; |
| 1978 if( p->rc==SQLITE_OK ){ |
| 1979 p->rc = prepareFreeAndCollectError( |
| 1980 p->dbMain, &pIter->pInsert, &p->zErrmsg, |
| 1981 sqlite3_mprintf("INSERT INTO \"rbu_imp_%w\" VALUES(%s)", zTbl, zBind) |
| 1982 ); |
| 1983 } |
| 1984 |
| 1985 /* And to delete index entries */ |
| 1986 if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){ |
| 1987 p->rc = prepareFreeAndCollectError( |
| 1988 p->dbMain, &pIter->pDelete, &p->zErrmsg, |
| 1989 sqlite3_mprintf("DELETE FROM \"rbu_imp_%w\" WHERE %s", zTbl, zWhere) |
| 1990 ); |
| 1991 } |
| 1992 |
| 1993 /* Create the SELECT statement to read keys in sorted order */ |
| 1994 if( p->rc==SQLITE_OK ){ |
| 1995 char *zSql; |
| 1996 if( rbuIsVacuum(p) ){ |
| 1997 zSql = sqlite3_mprintf( |
| 1998 "SELECT %s, 0 AS rbu_control FROM '%q' ORDER BY %s%s", |
| 1999 zCollist, |
| 2000 pIter->zDataTbl, |
| 2001 zCollist, zLimit |
| 2002 ); |
| 2003 }else |
| 2004 |
| 2005 if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){ |
| 2006 zSql = sqlite3_mprintf( |
| 2007 "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' ORDER BY %s%s", |
| 2008 zCollist, p->zStateDb, pIter->zDataTbl, |
| 2009 zCollist, zLimit |
| 2010 ); |
| 2011 }else{ |
| 2012 zSql = sqlite3_mprintf( |
| 2013 "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' " |
| 2014 "UNION ALL " |
| 2015 "SELECT %s, rbu_control FROM '%q' " |
| 2016 "WHERE typeof(rbu_control)='integer' AND rbu_control!=1 " |
| 2017 "ORDER BY %s%s", |
| 2018 zCollist, p->zStateDb, pIter->zDataTbl, |
| 2019 zCollist, pIter->zDataTbl, |
| 2020 zCollist, zLimit |
| 2021 ); |
| 2022 } |
| 2023 p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz, zSql); |
| 2024 } |
| 2025 |
| 2026 sqlite3_free(zImposterCols); |
| 2027 sqlite3_free(zImposterPK); |
| 2028 sqlite3_free(zWhere); |
| 2029 sqlite3_free(zBind); |
| 2030 }else{ |
| 2031 int bRbuRowid = (pIter->eType==RBU_PK_VTAB) |
| 2032 ||(pIter->eType==RBU_PK_NONE) |
| 2033 ||(pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p)); |
| 2034 const char *zTbl = pIter->zTbl; /* Table this step applies to */ |
| 2035 const char *zWrite; /* Imposter table name */ |
| 2036 |
| 2037 char *zBindings = rbuObjIterGetBindlist(p, pIter->nTblCol + bRbuRowid); |
| 2038 char *zWhere = rbuObjIterGetWhere(p, pIter); |
| 2039 char *zOldlist = rbuObjIterGetOldlist(p, pIter, "old"); |
| 2040 char *zNewlist = rbuObjIterGetOldlist(p, pIter, "new"); |
| 2041 |
| 2042 zCollist = rbuObjIterGetCollist(p, pIter); |
| 2043 pIter->nCol = pIter->nTblCol; |
| 2044 |
| 2045 /* Create the imposter table or tables (if required). */ |
| 2046 rbuCreateImposterTable(p, pIter); |
| 2047 rbuCreateImposterTable2(p, pIter); |
| 2048 zWrite = (pIter->eType==RBU_PK_VTAB ? "" : "rbu_imp_"); |
| 2049 |
| 2050 /* Create the INSERT statement to write to the target PK b-tree */ |
| 2051 if( p->rc==SQLITE_OK ){ |
| 2052 p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pInsert, pz, |
| 2053 sqlite3_mprintf( |
| 2054 "INSERT INTO \"%s%w\"(%s%s) VALUES(%s)", |
| 2055 zWrite, zTbl, zCollist, (bRbuRowid ? ", _rowid_" : ""), zBindings |
| 2056 ) |
| 2057 ); |
| 2058 } |
| 2059 |
| 2060 /* Create the DELETE statement to write to the target PK b-tree. |
| 2061 ** Because it only performs INSERT operations, this is not required for |
| 2062 ** an rbu vacuum handle. */ |
| 2063 if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){ |
| 2064 p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pDelete, pz, |
| 2065 sqlite3_mprintf( |
| 2066 "DELETE FROM \"%s%w\" WHERE %s", zWrite, zTbl, zWhere |
| 2067 ) |
| 2068 ); |
| 2069 } |
| 2070 |
| 2071 if( rbuIsVacuum(p)==0 && pIter->abIndexed ){ |
| 2072 const char *zRbuRowid = ""; |
| 2073 if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){ |
| 2074 zRbuRowid = ", rbu_rowid"; |
| 2075 } |
| 2076 |
| 2077 /* Create the rbu_tmp_xxx table and the triggers to populate it. */ |
| 2078 rbuMPrintfExec(p, p->dbRbu, |
| 2079 "CREATE TABLE IF NOT EXISTS %s.'rbu_tmp_%q' AS " |
| 2080 "SELECT *%s FROM '%q' WHERE 0;" |
| 2081 , p->zStateDb, pIter->zDataTbl |
| 2082 , (pIter->eType==RBU_PK_EXTERNAL ? ", 0 AS rbu_rowid" : "") |
| 2083 , pIter->zDataTbl |
| 2084 ); |
| 2085 |
| 2086 rbuMPrintfExec(p, p->dbMain, |
| 2087 "CREATE TEMP TRIGGER rbu_delete_tr BEFORE DELETE ON \"%s%w\" " |
| 2088 "BEGIN " |
| 2089 " SELECT rbu_tmp_insert(3, %s);" |
| 2090 "END;" |
| 2091 |
| 2092 "CREATE TEMP TRIGGER rbu_update1_tr BEFORE UPDATE ON \"%s%w\" " |
| 2093 "BEGIN " |
| 2094 " SELECT rbu_tmp_insert(3, %s);" |
| 2095 "END;" |
| 2096 |
| 2097 "CREATE TEMP TRIGGER rbu_update2_tr AFTER UPDATE ON \"%s%w\" " |
| 2098 "BEGIN " |
| 2099 " SELECT rbu_tmp_insert(4, %s);" |
| 2100 "END;", |
| 2101 zWrite, zTbl, zOldlist, |
| 2102 zWrite, zTbl, zOldlist, |
| 2103 zWrite, zTbl, zNewlist |
| 2104 ); |
| 2105 |
| 2106 if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){ |
| 2107 rbuMPrintfExec(p, p->dbMain, |
| 2108 "CREATE TEMP TRIGGER rbu_insert_tr AFTER INSERT ON \"%s%w\" " |
| 2109 "BEGIN " |
| 2110 " SELECT rbu_tmp_insert(0, %s);" |
| 2111 "END;", |
| 2112 zWrite, zTbl, zNewlist |
| 2113 ); |
| 2114 } |
| 2115 |
| 2116 rbuObjIterPrepareTmpInsert(p, pIter, zCollist, zRbuRowid); |
| 2117 } |
| 2118 |
| 2119 /* Create the SELECT statement to read keys from data_xxx */ |
| 2120 if( p->rc==SQLITE_OK ){ |
| 2121 const char *zRbuRowid = ""; |
| 2122 if( bRbuRowid ){ |
| 2123 zRbuRowid = rbuIsVacuum(p) ? ",_rowid_ " : ",rbu_rowid"; |
| 2124 } |
| 2125 p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz, |
| 2126 sqlite3_mprintf( |
| 2127 "SELECT %s,%s rbu_control%s FROM '%q'%s", |
| 2128 zCollist, |
| 2129 (rbuIsVacuum(p) ? "0 AS " : ""), |
| 2130 zRbuRowid, |
| 2131 pIter->zDataTbl, zLimit |
| 2132 ) |
| 2133 ); |
| 2134 } |
| 2135 |
| 2136 sqlite3_free(zWhere); |
| 2137 sqlite3_free(zOldlist); |
| 2138 sqlite3_free(zNewlist); |
| 2139 sqlite3_free(zBindings); |
| 2140 } |
| 2141 sqlite3_free(zCollist); |
| 2142 sqlite3_free(zLimit); |
| 2143 } |
| 2144 |
| 2145 return p->rc; |
| 2146 } |
| 2147 |
| 2148 /* |
| 2149 ** Set output variable *ppStmt to point to an UPDATE statement that may |
| 2150 ** be used to update the imposter table for the main table b-tree of the |
| 2151 ** table object that pIter currently points to, assuming that the |
| 2152 ** rbu_control column of the data_xyz table contains zMask. |
| 2153 ** |
| 2154 ** If the zMask string does not specify any columns to update, then this |
| 2155 ** is not an error. Output variable *ppStmt is set to NULL in this case. |
| 2156 */ |
| 2157 static int rbuGetUpdateStmt( |
| 2158 sqlite3rbu *p, /* RBU handle */ |
| 2159 RbuObjIter *pIter, /* Object iterator */ |
| 2160 const char *zMask, /* rbu_control value ('x.x.') */ |
| 2161 sqlite3_stmt **ppStmt /* OUT: UPDATE statement handle */ |
| 2162 ){ |
| 2163 RbuUpdateStmt **pp; |
| 2164 RbuUpdateStmt *pUp = 0; |
| 2165 int nUp = 0; |
| 2166 |
| 2167 /* In case an error occurs */ |
| 2168 *ppStmt = 0; |
| 2169 |
| 2170 /* Search for an existing statement. If one is found, shift it to the front |
| 2171 ** of the LRU queue and return immediately. Otherwise, leave nUp pointing |
| 2172 ** to the number of statements currently in the cache and pUp to the |
| 2173 ** last object in the list. */ |
| 2174 for(pp=&pIter->pRbuUpdate; *pp; pp=&((*pp)->pNext)){ |
| 2175 pUp = *pp; |
| 2176 if( strcmp(pUp->zMask, zMask)==0 ){ |
| 2177 *pp = pUp->pNext; |
| 2178 pUp->pNext = pIter->pRbuUpdate; |
| 2179 pIter->pRbuUpdate = pUp; |
| 2180 *ppStmt = pUp->pUpdate; |
| 2181 return SQLITE_OK; |
| 2182 } |
| 2183 nUp++; |
| 2184 } |
| 2185 assert( pUp==0 || pUp->pNext==0 ); |
| 2186 |
| 2187 if( nUp>=SQLITE_RBU_UPDATE_CACHESIZE ){ |
| 2188 for(pp=&pIter->pRbuUpdate; *pp!=pUp; pp=&((*pp)->pNext)); |
| 2189 *pp = 0; |
| 2190 sqlite3_finalize(pUp->pUpdate); |
| 2191 pUp->pUpdate = 0; |
| 2192 }else{ |
| 2193 pUp = (RbuUpdateStmt*)rbuMalloc(p, sizeof(RbuUpdateStmt)+pIter->nTblCol+1); |
| 2194 } |
| 2195 |
| 2196 if( pUp ){ |
| 2197 char *zWhere = rbuObjIterGetWhere(p, pIter); |
| 2198 char *zSet = rbuObjIterGetSetlist(p, pIter, zMask); |
| 2199 char *zUpdate = 0; |
| 2200 |
| 2201 pUp->zMask = (char*)&pUp[1]; |
| 2202 memcpy(pUp->zMask, zMask, pIter->nTblCol); |
| 2203 pUp->pNext = pIter->pRbuUpdate; |
| 2204 pIter->pRbuUpdate = pUp; |
| 2205 |
| 2206 if( zSet ){ |
| 2207 const char *zPrefix = ""; |
| 2208 |
| 2209 if( pIter->eType!=RBU_PK_VTAB ) zPrefix = "rbu_imp_"; |
| 2210 zUpdate = sqlite3_mprintf("UPDATE \"%s%w\" SET %s WHERE %s", |
| 2211 zPrefix, pIter->zTbl, zSet, zWhere |
| 2212 ); |
| 2213 p->rc = prepareFreeAndCollectError( |
| 2214 p->dbMain, &pUp->pUpdate, &p->zErrmsg, zUpdate |
| 2215 ); |
| 2216 *ppStmt = pUp->pUpdate; |
| 2217 } |
| 2218 sqlite3_free(zWhere); |
| 2219 sqlite3_free(zSet); |
| 2220 } |
| 2221 |
| 2222 return p->rc; |
| 2223 } |
| 2224 |
| 2225 static sqlite3 *rbuOpenDbhandle( |
| 2226 sqlite3rbu *p, |
| 2227 const char *zName, |
| 2228 int bUseVfs |
| 2229 ){ |
| 2230 sqlite3 *db = 0; |
| 2231 if( p->rc==SQLITE_OK ){ |
| 2232 const int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_URI; |
| 2233 p->rc = sqlite3_open_v2(zName, &db, flags, bUseVfs ? p->zVfsName : 0); |
| 2234 if( p->rc ){ |
| 2235 p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db)); |
| 2236 sqlite3_close(db); |
| 2237 db = 0; |
| 2238 } |
| 2239 } |
| 2240 return db; |
| 2241 } |
| 2242 |
| 2243 /* |
| 2244 ** Free an RbuState object allocated by rbuLoadState(). |
| 2245 */ |
| 2246 static void rbuFreeState(RbuState *p){ |
| 2247 if( p ){ |
| 2248 sqlite3_free(p->zTbl); |
| 2249 sqlite3_free(p->zIdx); |
| 2250 sqlite3_free(p); |
| 2251 } |
| 2252 } |
| 2253 |
| 2254 /* |
| 2255 ** Allocate an RbuState object and load the contents of the rbu_state |
| 2256 ** table into it. Return a pointer to the new object. It is the |
| 2257 ** responsibility of the caller to eventually free the object using |
| 2258 ** sqlite3_free(). |
| 2259 ** |
| 2260 ** If an error occurs, leave an error code and message in the rbu handle |
| 2261 ** and return NULL. |
| 2262 */ |
| 2263 static RbuState *rbuLoadState(sqlite3rbu *p){ |
| 2264 RbuState *pRet = 0; |
| 2265 sqlite3_stmt *pStmt = 0; |
| 2266 int rc; |
| 2267 int rc2; |
| 2268 |
| 2269 pRet = (RbuState*)rbuMalloc(p, sizeof(RbuState)); |
| 2270 if( pRet==0 ) return 0; |
| 2271 |
| 2272 rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg, |
| 2273 sqlite3_mprintf("SELECT k, v FROM %s.rbu_state", p->zStateDb) |
| 2274 ); |
| 2275 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ |
| 2276 switch( sqlite3_column_int(pStmt, 0) ){ |
| 2277 case RBU_STATE_STAGE: |
| 2278 pRet->eStage = sqlite3_column_int(pStmt, 1); |
| 2279 if( pRet->eStage!=RBU_STAGE_OAL |
| 2280 && pRet->eStage!=RBU_STAGE_MOVE |
| 2281 && pRet->eStage!=RBU_STAGE_CKPT |
| 2282 ){ |
| 2283 p->rc = SQLITE_CORRUPT; |
| 2284 } |
| 2285 break; |
| 2286 |
| 2287 case RBU_STATE_TBL: |
| 2288 pRet->zTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc); |
| 2289 break; |
| 2290 |
| 2291 case RBU_STATE_IDX: |
| 2292 pRet->zIdx = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc); |
| 2293 break; |
| 2294 |
| 2295 case RBU_STATE_ROW: |
| 2296 pRet->nRow = sqlite3_column_int(pStmt, 1); |
| 2297 break; |
| 2298 |
| 2299 case RBU_STATE_PROGRESS: |
| 2300 pRet->nProgress = sqlite3_column_int64(pStmt, 1); |
| 2301 break; |
| 2302 |
| 2303 case RBU_STATE_CKPT: |
| 2304 pRet->iWalCksum = sqlite3_column_int64(pStmt, 1); |
| 2305 break; |
| 2306 |
| 2307 case RBU_STATE_COOKIE: |
| 2308 pRet->iCookie = (u32)sqlite3_column_int64(pStmt, 1); |
| 2309 break; |
| 2310 |
| 2311 case RBU_STATE_OALSZ: |
| 2312 pRet->iOalSz = (u32)sqlite3_column_int64(pStmt, 1); |
| 2313 break; |
| 2314 |
| 2315 case RBU_STATE_PHASEONESTEP: |
| 2316 pRet->nPhaseOneStep = sqlite3_column_int64(pStmt, 1); |
| 2317 break; |
| 2318 |
| 2319 default: |
| 2320 rc = SQLITE_CORRUPT; |
| 2321 break; |
| 2322 } |
| 2323 } |
| 2324 rc2 = sqlite3_finalize(pStmt); |
| 2325 if( rc==SQLITE_OK ) rc = rc2; |
| 2326 |
| 2327 p->rc = rc; |
| 2328 return pRet; |
| 2329 } |
| 2330 |
| 2331 |
| 2332 /* |
| 2333 ** Open the database handle and attach the RBU database as "rbu". If an |
| 2334 ** error occurs, leave an error code and message in the RBU handle. |
| 2335 */ |
| 2336 static void rbuOpenDatabase(sqlite3rbu *p, int *pbRetry){ |
| 2337 assert( p->rc || (p->dbMain==0 && p->dbRbu==0) ); |
| 2338 assert( p->rc || rbuIsVacuum(p) || p->zTarget!=0 ); |
| 2339 |
| 2340 /* Open the RBU database */ |
| 2341 p->dbRbu = rbuOpenDbhandle(p, p->zRbu, 1); |
| 2342 |
| 2343 if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){ |
| 2344 sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p); |
| 2345 if( p->zState==0 ){ |
| 2346 const char *zFile = sqlite3_db_filename(p->dbRbu, "main"); |
| 2347 p->zState = rbuMPrintf(p, "file://%s-vacuum?modeof=%s", zFile, zFile); |
| 2348 } |
| 2349 } |
| 2350 |
| 2351 /* If using separate RBU and state databases, attach the state database to |
| 2352 ** the RBU db handle now. */ |
| 2353 if( p->zState ){ |
| 2354 rbuMPrintfExec(p, p->dbRbu, "ATTACH %Q AS stat", p->zState); |
| 2355 memcpy(p->zStateDb, "stat", 4); |
| 2356 }else{ |
| 2357 memcpy(p->zStateDb, "main", 4); |
| 2358 } |
| 2359 |
| 2360 #if 0 |
| 2361 if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){ |
| 2362 p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, 0); |
| 2363 } |
| 2364 #endif |
| 2365 |
| 2366 /* If it has not already been created, create the rbu_state table */ |
| 2367 rbuMPrintfExec(p, p->dbRbu, RBU_CREATE_STATE, p->zStateDb); |
| 2368 |
| 2369 #if 0 |
| 2370 if( rbuIsVacuum(p) ){ |
| 2371 if( p->rc==SQLITE_OK ){ |
| 2372 int rc2; |
| 2373 int bOk = 0; |
| 2374 sqlite3_stmt *pCnt = 0; |
| 2375 p->rc = prepareAndCollectError(p->dbRbu, &pCnt, &p->zErrmsg, |
| 2376 "SELECT count(*) FROM stat.sqlite_master" |
| 2377 ); |
| 2378 if( p->rc==SQLITE_OK |
| 2379 && sqlite3_step(pCnt)==SQLITE_ROW |
| 2380 && 1==sqlite3_column_int(pCnt, 0) |
| 2381 ){ |
| 2382 bOk = 1; |
| 2383 } |
| 2384 rc2 = sqlite3_finalize(pCnt); |
| 2385 if( p->rc==SQLITE_OK ) p->rc = rc2; |
| 2386 |
| 2387 if( p->rc==SQLITE_OK && bOk==0 ){ |
| 2388 p->rc = SQLITE_ERROR; |
| 2389 p->zErrmsg = sqlite3_mprintf("invalid state database"); |
| 2390 } |
| 2391 |
| 2392 if( p->rc==SQLITE_OK ){ |
| 2393 p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0); |
| 2394 } |
| 2395 } |
| 2396 } |
| 2397 #endif |
| 2398 |
| 2399 if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){ |
| 2400 int bOpen = 0; |
| 2401 int rc; |
| 2402 p->nRbu = 0; |
| 2403 p->pRbuFd = 0; |
| 2404 rc = sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p); |
| 2405 if( rc!=SQLITE_NOTFOUND ) p->rc = rc; |
| 2406 if( p->eStage>=RBU_STAGE_MOVE ){ |
| 2407 bOpen = 1; |
| 2408 }else{ |
| 2409 RbuState *pState = rbuLoadState(p); |
| 2410 if( pState ){ |
| 2411 bOpen = (pState->eStage>=RBU_STAGE_MOVE); |
| 2412 rbuFreeState(pState); |
| 2413 } |
| 2414 } |
| 2415 if( bOpen ) p->dbMain = rbuOpenDbhandle(p, p->zRbu, p->nRbu<=1); |
| 2416 } |
| 2417 |
| 2418 p->eStage = 0; |
| 2419 if( p->rc==SQLITE_OK && p->dbMain==0 ){ |
| 2420 if( !rbuIsVacuum(p) ){ |
| 2421 p->dbMain = rbuOpenDbhandle(p, p->zTarget, 1); |
| 2422 }else if( p->pRbuFd->pWalFd ){ |
| 2423 if( pbRetry ){ |
| 2424 p->pRbuFd->bNolock = 0; |
| 2425 sqlite3_close(p->dbRbu); |
| 2426 sqlite3_close(p->dbMain); |
| 2427 p->dbMain = 0; |
| 2428 p->dbRbu = 0; |
| 2429 *pbRetry = 1; |
| 2430 return; |
| 2431 } |
| 2432 p->rc = SQLITE_ERROR; |
| 2433 p->zErrmsg = sqlite3_mprintf("cannot vacuum wal mode database"); |
| 2434 }else{ |
| 2435 char *zTarget; |
| 2436 char *zExtra = 0; |
| 2437 if( strlen(p->zRbu)>=5 && 0==memcmp("file:", p->zRbu, 5) ){ |
| 2438 zExtra = &p->zRbu[5]; |
| 2439 while( *zExtra ){ |
| 2440 if( *zExtra++=='?' ) break; |
| 2441 } |
| 2442 if( *zExtra=='\0' ) zExtra = 0; |
| 2443 } |
| 2444 |
| 2445 zTarget = sqlite3_mprintf("file:%s-vacuum?rbu_memory=1%s%s", |
| 2446 sqlite3_db_filename(p->dbRbu, "main"), |
| 2447 (zExtra==0 ? "" : "&"), (zExtra==0 ? "" : zExtra) |
| 2448 ); |
| 2449 |
| 2450 if( zTarget==0 ){ |
| 2451 p->rc = SQLITE_NOMEM; |
| 2452 return; |
| 2453 } |
| 2454 p->dbMain = rbuOpenDbhandle(p, zTarget, p->nRbu<=1); |
| 2455 sqlite3_free(zTarget); |
| 2456 } |
| 2457 } |
| 2458 |
| 2459 if( p->rc==SQLITE_OK ){ |
| 2460 p->rc = sqlite3_create_function(p->dbMain, |
| 2461 "rbu_tmp_insert", -1, SQLITE_UTF8, (void*)p, rbuTmpInsertFunc, 0, 0 |
| 2462 ); |
| 2463 } |
| 2464 |
| 2465 if( p->rc==SQLITE_OK ){ |
| 2466 p->rc = sqlite3_create_function(p->dbMain, |
| 2467 "rbu_fossil_delta", 2, SQLITE_UTF8, 0, rbuFossilDeltaFunc, 0, 0 |
| 2468 ); |
| 2469 } |
| 2470 |
| 2471 if( p->rc==SQLITE_OK ){ |
| 2472 p->rc = sqlite3_create_function(p->dbRbu, |
| 2473 "rbu_target_name", -1, SQLITE_UTF8, (void*)p, rbuTargetNameFunc, 0, 0 |
| 2474 ); |
| 2475 } |
| 2476 |
| 2477 if( p->rc==SQLITE_OK ){ |
| 2478 p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p); |
| 2479 } |
| 2480 rbuMPrintfExec(p, p->dbMain, "SELECT * FROM sqlite_master"); |
| 2481 |
| 2482 /* Mark the database file just opened as an RBU target database. If |
| 2483 ** this call returns SQLITE_NOTFOUND, then the RBU vfs is not in use. |
| 2484 ** This is an error. */ |
| 2485 if( p->rc==SQLITE_OK ){ |
| 2486 p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p); |
| 2487 } |
| 2488 |
| 2489 if( p->rc==SQLITE_NOTFOUND ){ |
| 2490 p->rc = SQLITE_ERROR; |
| 2491 p->zErrmsg = sqlite3_mprintf("rbu vfs not found"); |
| 2492 } |
| 2493 } |
| 2494 |
| 2495 /* |
| 2496 ** This routine is a copy of the sqlite3FileSuffix3() routine from the core. |
| 2497 ** It is a no-op unless SQLITE_ENABLE_8_3_NAMES is defined. |
| 2498 ** |
| 2499 ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database |
| 2500 ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and |
| 2501 ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than |
| 2502 ** three characters, then shorten the suffix on z[] to be the last three |
| 2503 ** characters of the original suffix. |
| 2504 ** |
| 2505 ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always |
| 2506 ** do the suffix shortening regardless of URI parameter. |
| 2507 ** |
| 2508 ** Examples: |
| 2509 ** |
| 2510 ** test.db-journal => test.nal |
| 2511 ** test.db-wal => test.wal |
| 2512 ** test.db-shm => test.shm |
| 2513 ** test.db-mj7f3319fa => test.9fa |
| 2514 */ |
| 2515 static void rbuFileSuffix3(const char *zBase, char *z){ |
| 2516 #ifdef SQLITE_ENABLE_8_3_NAMES |
| 2517 #if SQLITE_ENABLE_8_3_NAMES<2 |
| 2518 if( sqlite3_uri_boolean(zBase, "8_3_names", 0) ) |
| 2519 #endif |
| 2520 { |
| 2521 int i, sz; |
| 2522 sz = (int)strlen(z)&0xffffff; |
| 2523 for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){} |
| 2524 if( z[i]=='.' && sz>i+4 ) memmove(&z[i+1], &z[sz-3], 4); |
| 2525 } |
| 2526 #endif |
| 2527 } |
| 2528 |
| 2529 /* |
| 2530 ** Return the current wal-index header checksum for the target database |
| 2531 ** as a 64-bit integer. |
| 2532 ** |
| 2533 ** The checksum is store in the first page of xShmMap memory as an 8-byte |
| 2534 ** blob starting at byte offset 40. |
| 2535 */ |
| 2536 static i64 rbuShmChecksum(sqlite3rbu *p){ |
| 2537 i64 iRet = 0; |
| 2538 if( p->rc==SQLITE_OK ){ |
| 2539 sqlite3_file *pDb = p->pTargetFd->pReal; |
| 2540 u32 volatile *ptr; |
| 2541 p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, (void volatile**)&ptr); |
| 2542 if( p->rc==SQLITE_OK ){ |
| 2543 iRet = ((i64)ptr[10] << 32) + ptr[11]; |
| 2544 } |
| 2545 } |
| 2546 return iRet; |
| 2547 } |
| 2548 |
| 2549 /* |
| 2550 ** This function is called as part of initializing or reinitializing an |
| 2551 ** incremental checkpoint. |
| 2552 ** |
| 2553 ** It populates the sqlite3rbu.aFrame[] array with the set of |
| 2554 ** (wal frame -> db page) copy operations required to checkpoint the |
| 2555 ** current wal file, and obtains the set of shm locks required to safely |
| 2556 ** perform the copy operations directly on the file-system. |
| 2557 ** |
| 2558 ** If argument pState is not NULL, then the incremental checkpoint is |
| 2559 ** being resumed. In this case, if the checksum of the wal-index-header |
| 2560 ** following recovery is not the same as the checksum saved in the RbuState |
| 2561 ** object, then the rbu handle is set to DONE state. This occurs if some |
| 2562 ** other client appends a transaction to the wal file in the middle of |
| 2563 ** an incremental checkpoint. |
| 2564 */ |
| 2565 static void rbuSetupCheckpoint(sqlite3rbu *p, RbuState *pState){ |
| 2566 |
| 2567 /* If pState is NULL, then the wal file may not have been opened and |
| 2568 ** recovered. Running a read-statement here to ensure that doing so |
| 2569 ** does not interfere with the "capture" process below. */ |
| 2570 if( pState==0 ){ |
| 2571 p->eStage = 0; |
| 2572 if( p->rc==SQLITE_OK ){ |
| 2573 p->rc = sqlite3_exec(p->dbMain, "SELECT * FROM sqlite_master", 0, 0, 0); |
| 2574 } |
| 2575 } |
| 2576 |
| 2577 /* Assuming no error has occurred, run a "restart" checkpoint with the |
| 2578 ** sqlite3rbu.eStage variable set to CAPTURE. This turns on the following |
| 2579 ** special behaviour in the rbu VFS: |
| 2580 ** |
| 2581 ** * If the exclusive shm WRITER or READ0 lock cannot be obtained, |
| 2582 ** the checkpoint fails with SQLITE_BUSY (normally SQLite would |
| 2583 ** proceed with running a passive checkpoint instead of failing). |
| 2584 ** |
| 2585 ** * Attempts to read from the *-wal file or write to the database file |
| 2586 ** do not perform any IO. Instead, the frame/page combinations that |
| 2587 ** would be read/written are recorded in the sqlite3rbu.aFrame[] |
| 2588 ** array. |
| 2589 ** |
| 2590 ** * Calls to xShmLock(UNLOCK) to release the exclusive shm WRITER, |
| 2591 ** READ0 and CHECKPOINT locks taken as part of the checkpoint are |
| 2592 ** no-ops. These locks will not be released until the connection |
| 2593 ** is closed. |
| 2594 ** |
| 2595 ** * Attempting to xSync() the database file causes an SQLITE_INTERNAL |
| 2596 ** error. |
| 2597 ** |
| 2598 ** As a result, unless an error (i.e. OOM or SQLITE_BUSY) occurs, the |
| 2599 ** checkpoint below fails with SQLITE_INTERNAL, and leaves the aFrame[] |
| 2600 ** array populated with a set of (frame -> page) mappings. Because the |
| 2601 ** WRITER, CHECKPOINT and READ0 locks are still held, it is safe to copy |
| 2602 ** data from the wal file into the database file according to the |
| 2603 ** contents of aFrame[]. |
| 2604 */ |
| 2605 if( p->rc==SQLITE_OK ){ |
| 2606 int rc2; |
| 2607 p->eStage = RBU_STAGE_CAPTURE; |
| 2608 rc2 = sqlite3_exec(p->dbMain, "PRAGMA main.wal_checkpoint=restart", 0, 0,0); |
| 2609 if( rc2!=SQLITE_INTERNAL ) p->rc = rc2; |
| 2610 } |
| 2611 |
| 2612 if( p->rc==SQLITE_OK && p->nFrame>0 ){ |
| 2613 p->eStage = RBU_STAGE_CKPT; |
| 2614 p->nStep = (pState ? pState->nRow : 0); |
| 2615 p->aBuf = rbuMalloc(p, p->pgsz); |
| 2616 p->iWalCksum = rbuShmChecksum(p); |
| 2617 } |
| 2618 |
| 2619 if( p->rc==SQLITE_OK ){ |
| 2620 if( p->nFrame==0 || (pState && pState->iWalCksum!=p->iWalCksum) ){ |
| 2621 p->rc = SQLITE_DONE; |
| 2622 p->eStage = RBU_STAGE_DONE; |
| 2623 } |
| 2624 } |
| 2625 } |
| 2626 |
| 2627 /* |
| 2628 ** Called when iAmt bytes are read from offset iOff of the wal file while |
| 2629 ** the rbu object is in capture mode. Record the frame number of the frame |
| 2630 ** being read in the aFrame[] array. |
| 2631 */ |
| 2632 static int rbuCaptureWalRead(sqlite3rbu *pRbu, i64 iOff, int iAmt){ |
| 2633 const u32 mReq = (1<<WAL_LOCK_WRITE)|(1<<WAL_LOCK_CKPT)|(1<<WAL_LOCK_READ0); |
| 2634 u32 iFrame; |
| 2635 |
| 2636 if( pRbu->mLock!=mReq ){ |
| 2637 pRbu->rc = SQLITE_BUSY; |
| 2638 return SQLITE_INTERNAL; |
| 2639 } |
| 2640 |
| 2641 pRbu->pgsz = iAmt; |
| 2642 if( pRbu->nFrame==pRbu->nFrameAlloc ){ |
| 2643 int nNew = (pRbu->nFrameAlloc ? pRbu->nFrameAlloc : 64) * 2; |
| 2644 RbuFrame *aNew; |
| 2645 aNew = (RbuFrame*)sqlite3_realloc64(pRbu->aFrame, nNew * sizeof(RbuFrame)); |
| 2646 if( aNew==0 ) return SQLITE_NOMEM; |
| 2647 pRbu->aFrame = aNew; |
| 2648 pRbu->nFrameAlloc = nNew; |
| 2649 } |
| 2650 |
| 2651 iFrame = (u32)((iOff-32) / (i64)(iAmt+24)) + 1; |
| 2652 if( pRbu->iMaxFrame<iFrame ) pRbu->iMaxFrame = iFrame; |
| 2653 pRbu->aFrame[pRbu->nFrame].iWalFrame = iFrame; |
| 2654 pRbu->aFrame[pRbu->nFrame].iDbPage = 0; |
| 2655 pRbu->nFrame++; |
| 2656 return SQLITE_OK; |
| 2657 } |
| 2658 |
| 2659 /* |
| 2660 ** Called when a page of data is written to offset iOff of the database |
| 2661 ** file while the rbu handle is in capture mode. Record the page number |
| 2662 ** of the page being written in the aFrame[] array. |
| 2663 */ |
| 2664 static int rbuCaptureDbWrite(sqlite3rbu *pRbu, i64 iOff){ |
| 2665 pRbu->aFrame[pRbu->nFrame-1].iDbPage = (u32)(iOff / pRbu->pgsz) + 1; |
| 2666 return SQLITE_OK; |
| 2667 } |
| 2668 |
| 2669 /* |
| 2670 ** This is called as part of an incremental checkpoint operation. Copy |
| 2671 ** a single frame of data from the wal file into the database file, as |
| 2672 ** indicated by the RbuFrame object. |
| 2673 */ |
| 2674 static void rbuCheckpointFrame(sqlite3rbu *p, RbuFrame *pFrame){ |
| 2675 sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal; |
| 2676 sqlite3_file *pDb = p->pTargetFd->pReal; |
| 2677 i64 iOff; |
| 2678 |
| 2679 assert( p->rc==SQLITE_OK ); |
| 2680 iOff = (i64)(pFrame->iWalFrame-1) * (p->pgsz + 24) + 32 + 24; |
| 2681 p->rc = pWal->pMethods->xRead(pWal, p->aBuf, p->pgsz, iOff); |
| 2682 if( p->rc ) return; |
| 2683 |
| 2684 iOff = (i64)(pFrame->iDbPage-1) * p->pgsz; |
| 2685 p->rc = pDb->pMethods->xWrite(pDb, p->aBuf, p->pgsz, iOff); |
| 2686 } |
| 2687 |
| 2688 |
| 2689 /* |
| 2690 ** Take an EXCLUSIVE lock on the database file. |
| 2691 */ |
| 2692 static void rbuLockDatabase(sqlite3rbu *p){ |
| 2693 sqlite3_file *pReal = p->pTargetFd->pReal; |
| 2694 assert( p->rc==SQLITE_OK ); |
| 2695 p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_SHARED); |
| 2696 if( p->rc==SQLITE_OK ){ |
| 2697 p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_EXCLUSIVE); |
| 2698 } |
| 2699 } |
| 2700 |
| 2701 #if defined(_WIN32_WCE) |
| 2702 static LPWSTR rbuWinUtf8ToUnicode(const char *zFilename){ |
| 2703 int nChar; |
| 2704 LPWSTR zWideFilename; |
| 2705 |
| 2706 nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0); |
| 2707 if( nChar==0 ){ |
| 2708 return 0; |
| 2709 } |
| 2710 zWideFilename = sqlite3_malloc64( nChar*sizeof(zWideFilename[0]) ); |
| 2711 if( zWideFilename==0 ){ |
| 2712 return 0; |
| 2713 } |
| 2714 memset(zWideFilename, 0, nChar*sizeof(zWideFilename[0])); |
| 2715 nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, |
| 2716 nChar); |
| 2717 if( nChar==0 ){ |
| 2718 sqlite3_free(zWideFilename); |
| 2719 zWideFilename = 0; |
| 2720 } |
| 2721 return zWideFilename; |
| 2722 } |
| 2723 #endif |
| 2724 |
| 2725 /* |
| 2726 ** The RBU handle is currently in RBU_STAGE_OAL state, with a SHARED lock |
| 2727 ** on the database file. This proc moves the *-oal file to the *-wal path, |
| 2728 ** then reopens the database file (this time in vanilla, non-oal, WAL mode). |
| 2729 ** If an error occurs, leave an error code and error message in the rbu |
| 2730 ** handle. |
| 2731 */ |
| 2732 static void rbuMoveOalFile(sqlite3rbu *p){ |
| 2733 const char *zBase = sqlite3_db_filename(p->dbMain, "main"); |
| 2734 const char *zMove = zBase; |
| 2735 char *zOal; |
| 2736 char *zWal; |
| 2737 |
| 2738 if( rbuIsVacuum(p) ){ |
| 2739 zMove = sqlite3_db_filename(p->dbRbu, "main"); |
| 2740 } |
| 2741 zOal = sqlite3_mprintf("%s-oal", zMove); |
| 2742 zWal = sqlite3_mprintf("%s-wal", zMove); |
| 2743 |
| 2744 assert( p->eStage==RBU_STAGE_MOVE ); |
| 2745 assert( p->rc==SQLITE_OK && p->zErrmsg==0 ); |
| 2746 if( zWal==0 || zOal==0 ){ |
| 2747 p->rc = SQLITE_NOMEM; |
| 2748 }else{ |
| 2749 /* Move the *-oal file to *-wal. At this point connection p->db is |
| 2750 ** holding a SHARED lock on the target database file (because it is |
| 2751 ** in WAL mode). So no other connection may be writing the db. |
| 2752 ** |
| 2753 ** In order to ensure that there are no database readers, an EXCLUSIVE |
| 2754 ** lock is obtained here before the *-oal is moved to *-wal. |
| 2755 */ |
| 2756 rbuLockDatabase(p); |
| 2757 if( p->rc==SQLITE_OK ){ |
| 2758 rbuFileSuffix3(zBase, zWal); |
| 2759 rbuFileSuffix3(zBase, zOal); |
| 2760 |
| 2761 /* Re-open the databases. */ |
| 2762 rbuObjIterFinalize(&p->objiter); |
| 2763 sqlite3_close(p->dbRbu); |
| 2764 sqlite3_close(p->dbMain); |
| 2765 p->dbMain = 0; |
| 2766 p->dbRbu = 0; |
| 2767 |
| 2768 #if defined(_WIN32_WCE) |
| 2769 { |
| 2770 LPWSTR zWideOal; |
| 2771 LPWSTR zWideWal; |
| 2772 |
| 2773 zWideOal = rbuWinUtf8ToUnicode(zOal); |
| 2774 if( zWideOal ){ |
| 2775 zWideWal = rbuWinUtf8ToUnicode(zWal); |
| 2776 if( zWideWal ){ |
| 2777 if( MoveFileW(zWideOal, zWideWal) ){ |
| 2778 p->rc = SQLITE_OK; |
| 2779 }else{ |
| 2780 p->rc = SQLITE_IOERR; |
| 2781 } |
| 2782 sqlite3_free(zWideWal); |
| 2783 }else{ |
| 2784 p->rc = SQLITE_IOERR_NOMEM; |
| 2785 } |
| 2786 sqlite3_free(zWideOal); |
| 2787 }else{ |
| 2788 p->rc = SQLITE_IOERR_NOMEM; |
| 2789 } |
| 2790 } |
| 2791 #else |
| 2792 p->rc = rename(zOal, zWal) ? SQLITE_IOERR : SQLITE_OK; |
| 2793 #endif |
| 2794 |
| 2795 if( p->rc==SQLITE_OK ){ |
| 2796 rbuOpenDatabase(p, 0); |
| 2797 rbuSetupCheckpoint(p, 0); |
| 2798 } |
| 2799 } |
| 2800 } |
| 2801 |
| 2802 sqlite3_free(zWal); |
| 2803 sqlite3_free(zOal); |
| 2804 } |
| 2805 |
| 2806 /* |
| 2807 ** The SELECT statement iterating through the keys for the current object |
| 2808 ** (p->objiter.pSelect) currently points to a valid row. This function |
| 2809 ** determines the type of operation requested by this row and returns |
| 2810 ** one of the following values to indicate the result: |
| 2811 ** |
| 2812 ** * RBU_INSERT |
| 2813 ** * RBU_DELETE |
| 2814 ** * RBU_IDX_DELETE |
| 2815 ** * RBU_UPDATE |
| 2816 ** |
| 2817 ** If RBU_UPDATE is returned, then output variable *pzMask is set to |
| 2818 ** point to the text value indicating the columns to update. |
| 2819 ** |
| 2820 ** If the rbu_control field contains an invalid value, an error code and |
| 2821 ** message are left in the RBU handle and zero returned. |
| 2822 */ |
| 2823 static int rbuStepType(sqlite3rbu *p, const char **pzMask){ |
| 2824 int iCol = p->objiter.nCol; /* Index of rbu_control column */ |
| 2825 int res = 0; /* Return value */ |
| 2826 |
| 2827 switch( sqlite3_column_type(p->objiter.pSelect, iCol) ){ |
| 2828 case SQLITE_INTEGER: { |
| 2829 int iVal = sqlite3_column_int(p->objiter.pSelect, iCol); |
| 2830 switch( iVal ){ |
| 2831 case 0: res = RBU_INSERT; break; |
| 2832 case 1: res = RBU_DELETE; break; |
| 2833 case 2: res = RBU_REPLACE; break; |
| 2834 case 3: res = RBU_IDX_DELETE; break; |
| 2835 case 4: res = RBU_IDX_INSERT; break; |
| 2836 } |
| 2837 break; |
| 2838 } |
| 2839 |
| 2840 case SQLITE_TEXT: { |
| 2841 const unsigned char *z = sqlite3_column_text(p->objiter.pSelect, iCol); |
| 2842 if( z==0 ){ |
| 2843 p->rc = SQLITE_NOMEM; |
| 2844 }else{ |
| 2845 *pzMask = (const char*)z; |
| 2846 } |
| 2847 res = RBU_UPDATE; |
| 2848 |
| 2849 break; |
| 2850 } |
| 2851 |
| 2852 default: |
| 2853 break; |
| 2854 } |
| 2855 |
| 2856 if( res==0 ){ |
| 2857 rbuBadControlError(p); |
| 2858 } |
| 2859 return res; |
| 2860 } |
| 2861 |
| 2862 #ifdef SQLITE_DEBUG |
| 2863 /* |
| 2864 ** Assert that column iCol of statement pStmt is named zName. |
| 2865 */ |
| 2866 static void assertColumnName(sqlite3_stmt *pStmt, int iCol, const char *zName){ |
| 2867 const char *zCol = sqlite3_column_name(pStmt, iCol); |
| 2868 assert( 0==sqlite3_stricmp(zName, zCol) ); |
| 2869 } |
| 2870 #else |
| 2871 # define assertColumnName(x,y,z) |
| 2872 #endif |
| 2873 |
| 2874 /* |
| 2875 ** Argument eType must be one of RBU_INSERT, RBU_DELETE, RBU_IDX_INSERT or |
| 2876 ** RBU_IDX_DELETE. This function performs the work of a single |
| 2877 ** sqlite3rbu_step() call for the type of operation specified by eType. |
| 2878 */ |
| 2879 static void rbuStepOneOp(sqlite3rbu *p, int eType){ |
| 2880 RbuObjIter *pIter = &p->objiter; |
| 2881 sqlite3_value *pVal; |
| 2882 sqlite3_stmt *pWriter; |
| 2883 int i; |
| 2884 |
| 2885 assert( p->rc==SQLITE_OK ); |
| 2886 assert( eType!=RBU_DELETE || pIter->zIdx==0 ); |
| 2887 assert( eType==RBU_DELETE || eType==RBU_IDX_DELETE |
| 2888 || eType==RBU_INSERT || eType==RBU_IDX_INSERT |
| 2889 ); |
| 2890 |
| 2891 /* If this is a delete, decrement nPhaseOneStep by nIndex. If the DELETE |
| 2892 ** statement below does actually delete a row, nPhaseOneStep will be |
| 2893 ** incremented by the same amount when SQL function rbu_tmp_insert() |
| 2894 ** is invoked by the trigger. */ |
| 2895 if( eType==RBU_DELETE ){ |
| 2896 p->nPhaseOneStep -= p->objiter.nIndex; |
| 2897 } |
| 2898 |
| 2899 if( eType==RBU_IDX_DELETE || eType==RBU_DELETE ){ |
| 2900 pWriter = pIter->pDelete; |
| 2901 }else{ |
| 2902 pWriter = pIter->pInsert; |
| 2903 } |
| 2904 |
| 2905 for(i=0; i<pIter->nCol; i++){ |
| 2906 /* If this is an INSERT into a table b-tree and the table has an |
| 2907 ** explicit INTEGER PRIMARY KEY, check that this is not an attempt |
| 2908 ** to write a NULL into the IPK column. That is not permitted. */ |
| 2909 if( eType==RBU_INSERT |
| 2910 && pIter->zIdx==0 && pIter->eType==RBU_PK_IPK && pIter->abTblPk[i] |
| 2911 && sqlite3_column_type(pIter->pSelect, i)==SQLITE_NULL |
| 2912 ){ |
| 2913 p->rc = SQLITE_MISMATCH; |
| 2914 p->zErrmsg = sqlite3_mprintf("datatype mismatch"); |
| 2915 return; |
| 2916 } |
| 2917 |
| 2918 if( eType==RBU_DELETE && pIter->abTblPk[i]==0 ){ |
| 2919 continue; |
| 2920 } |
| 2921 |
| 2922 pVal = sqlite3_column_value(pIter->pSelect, i); |
| 2923 p->rc = sqlite3_bind_value(pWriter, i+1, pVal); |
| 2924 if( p->rc ) return; |
| 2925 } |
| 2926 if( pIter->zIdx==0 ){ |
| 2927 if( pIter->eType==RBU_PK_VTAB |
| 2928 || pIter->eType==RBU_PK_NONE |
| 2929 || (pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p)) |
| 2930 ){ |
| 2931 /* For a virtual table, or a table with no primary key, the |
| 2932 ** SELECT statement is: |
| 2933 ** |
| 2934 ** SELECT <cols>, rbu_control, rbu_rowid FROM .... |
| 2935 ** |
| 2936 ** Hence column_value(pIter->nCol+1). |
| 2937 */ |
| 2938 assertColumnName(pIter->pSelect, pIter->nCol+1, |
| 2939 rbuIsVacuum(p) ? "rowid" : "rbu_rowid" |
| 2940 ); |
| 2941 pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1); |
| 2942 p->rc = sqlite3_bind_value(pWriter, pIter->nCol+1, pVal); |
| 2943 } |
| 2944 } |
| 2945 if( p->rc==SQLITE_OK ){ |
| 2946 sqlite3_step(pWriter); |
| 2947 p->rc = resetAndCollectError(pWriter, &p->zErrmsg); |
| 2948 } |
| 2949 } |
| 2950 |
| 2951 /* |
| 2952 ** This function does the work for an sqlite3rbu_step() call. |
| 2953 ** |
| 2954 ** The object-iterator (p->objiter) currently points to a valid object, |
| 2955 ** and the input cursor (p->objiter.pSelect) currently points to a valid |
| 2956 ** input row. Perform whatever processing is required and return. |
| 2957 ** |
| 2958 ** If no error occurs, SQLITE_OK is returned. Otherwise, an error code |
| 2959 ** and message is left in the RBU handle and a copy of the error code |
| 2960 ** returned. |
| 2961 */ |
| 2962 static int rbuStep(sqlite3rbu *p){ |
| 2963 RbuObjIter *pIter = &p->objiter; |
| 2964 const char *zMask = 0; |
| 2965 int eType = rbuStepType(p, &zMask); |
| 2966 |
| 2967 if( eType ){ |
| 2968 assert( eType==RBU_INSERT || eType==RBU_DELETE |
| 2969 || eType==RBU_REPLACE || eType==RBU_IDX_DELETE |
| 2970 || eType==RBU_IDX_INSERT || eType==RBU_UPDATE |
| 2971 ); |
| 2972 assert( eType!=RBU_UPDATE || pIter->zIdx==0 ); |
| 2973 |
| 2974 if( pIter->zIdx==0 && (eType==RBU_IDX_DELETE || eType==RBU_IDX_INSERT) ){ |
| 2975 rbuBadControlError(p); |
| 2976 } |
| 2977 else if( eType==RBU_REPLACE ){ |
| 2978 if( pIter->zIdx==0 ){ |
| 2979 p->nPhaseOneStep += p->objiter.nIndex; |
| 2980 rbuStepOneOp(p, RBU_DELETE); |
| 2981 } |
| 2982 if( p->rc==SQLITE_OK ) rbuStepOneOp(p, RBU_INSERT); |
| 2983 } |
| 2984 else if( eType!=RBU_UPDATE ){ |
| 2985 rbuStepOneOp(p, eType); |
| 2986 } |
| 2987 else{ |
| 2988 sqlite3_value *pVal; |
| 2989 sqlite3_stmt *pUpdate = 0; |
| 2990 assert( eType==RBU_UPDATE ); |
| 2991 p->nPhaseOneStep -= p->objiter.nIndex; |
| 2992 rbuGetUpdateStmt(p, pIter, zMask, &pUpdate); |
| 2993 if( pUpdate ){ |
| 2994 int i; |
| 2995 for(i=0; p->rc==SQLITE_OK && i<pIter->nCol; i++){ |
| 2996 char c = zMask[pIter->aiSrcOrder[i]]; |
| 2997 pVal = sqlite3_column_value(pIter->pSelect, i); |
| 2998 if( pIter->abTblPk[i] || c!='.' ){ |
| 2999 p->rc = sqlite3_bind_value(pUpdate, i+1, pVal); |
| 3000 } |
| 3001 } |
| 3002 if( p->rc==SQLITE_OK |
| 3003 && (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE) |
| 3004 ){ |
| 3005 /* Bind the rbu_rowid value to column _rowid_ */ |
| 3006 assertColumnName(pIter->pSelect, pIter->nCol+1, "rbu_rowid"); |
| 3007 pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1); |
| 3008 p->rc = sqlite3_bind_value(pUpdate, pIter->nCol+1, pVal); |
| 3009 } |
| 3010 if( p->rc==SQLITE_OK ){ |
| 3011 sqlite3_step(pUpdate); |
| 3012 p->rc = resetAndCollectError(pUpdate, &p->zErrmsg); |
| 3013 } |
| 3014 } |
| 3015 } |
| 3016 } |
| 3017 return p->rc; |
| 3018 } |
| 3019 |
| 3020 /* |
| 3021 ** Increment the schema cookie of the main database opened by p->dbMain. |
| 3022 ** |
| 3023 ** Or, if this is an RBU vacuum, set the schema cookie of the main db |
| 3024 ** opened by p->dbMain to one more than the schema cookie of the main |
| 3025 ** db opened by p->dbRbu. |
| 3026 */ |
| 3027 static void rbuIncrSchemaCookie(sqlite3rbu *p){ |
| 3028 if( p->rc==SQLITE_OK ){ |
| 3029 sqlite3 *dbread = (rbuIsVacuum(p) ? p->dbRbu : p->dbMain); |
| 3030 int iCookie = 1000000; |
| 3031 sqlite3_stmt *pStmt; |
| 3032 |
| 3033 p->rc = prepareAndCollectError(dbread, &pStmt, &p->zErrmsg, |
| 3034 "PRAGMA schema_version" |
| 3035 ); |
| 3036 if( p->rc==SQLITE_OK ){ |
| 3037 /* Coverage: it may be that this sqlite3_step() cannot fail. There |
| 3038 ** is already a transaction open, so the prepared statement cannot |
| 3039 ** throw an SQLITE_SCHEMA exception. The only database page the |
| 3040 ** statement reads is page 1, which is guaranteed to be in the cache. |
| 3041 ** And no memory allocations are required. */ |
| 3042 if( SQLITE_ROW==sqlite3_step(pStmt) ){ |
| 3043 iCookie = sqlite3_column_int(pStmt, 0); |
| 3044 } |
| 3045 rbuFinalize(p, pStmt); |
| 3046 } |
| 3047 if( p->rc==SQLITE_OK ){ |
| 3048 rbuMPrintfExec(p, p->dbMain, "PRAGMA schema_version = %d", iCookie+1); |
| 3049 } |
| 3050 } |
| 3051 } |
| 3052 |
| 3053 /* |
| 3054 ** Update the contents of the rbu_state table within the rbu database. The |
| 3055 ** value stored in the RBU_STATE_STAGE column is eStage. All other values |
| 3056 ** are determined by inspecting the rbu handle passed as the first argument. |
| 3057 */ |
| 3058 static void rbuSaveState(sqlite3rbu *p, int eStage){ |
| 3059 if( p->rc==SQLITE_OK || p->rc==SQLITE_DONE ){ |
| 3060 sqlite3_stmt *pInsert = 0; |
| 3061 rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd); |
| 3062 int rc; |
| 3063 |
| 3064 assert( p->zErrmsg==0 ); |
| 3065 rc = prepareFreeAndCollectError(p->dbRbu, &pInsert, &p->zErrmsg, |
| 3066 sqlite3_mprintf( |
| 3067 "INSERT OR REPLACE INTO %s.rbu_state(k, v) VALUES " |
| 3068 "(%d, %d), " |
| 3069 "(%d, %Q), " |
| 3070 "(%d, %Q), " |
| 3071 "(%d, %d), " |
| 3072 "(%d, %d), " |
| 3073 "(%d, %lld), " |
| 3074 "(%d, %lld), " |
| 3075 "(%d, %lld), " |
| 3076 "(%d, %lld) ", |
| 3077 p->zStateDb, |
| 3078 RBU_STATE_STAGE, eStage, |
| 3079 RBU_STATE_TBL, p->objiter.zTbl, |
| 3080 RBU_STATE_IDX, p->objiter.zIdx, |
| 3081 RBU_STATE_ROW, p->nStep, |
| 3082 RBU_STATE_PROGRESS, p->nProgress, |
| 3083 RBU_STATE_CKPT, p->iWalCksum, |
| 3084 RBU_STATE_COOKIE, (i64)pFd->iCookie, |
| 3085 RBU_STATE_OALSZ, p->iOalSz, |
| 3086 RBU_STATE_PHASEONESTEP, p->nPhaseOneStep |
| 3087 ) |
| 3088 ); |
| 3089 assert( pInsert==0 || rc==SQLITE_OK ); |
| 3090 |
| 3091 if( rc==SQLITE_OK ){ |
| 3092 sqlite3_step(pInsert); |
| 3093 rc = sqlite3_finalize(pInsert); |
| 3094 } |
| 3095 if( rc!=SQLITE_OK ) p->rc = rc; |
| 3096 } |
| 3097 } |
| 3098 |
| 3099 |
| 3100 /* |
| 3101 ** The second argument passed to this function is the name of a PRAGMA |
| 3102 ** setting - "page_size", "auto_vacuum", "user_version" or "application_id". |
| 3103 ** This function executes the following on sqlite3rbu.dbRbu: |
| 3104 ** |
| 3105 ** "PRAGMA main.$zPragma" |
| 3106 ** |
| 3107 ** where $zPragma is the string passed as the second argument, then |
| 3108 ** on sqlite3rbu.dbMain: |
| 3109 ** |
| 3110 ** "PRAGMA main.$zPragma = $val" |
| 3111 ** |
| 3112 ** where $val is the value returned by the first PRAGMA invocation. |
| 3113 ** |
| 3114 ** In short, it copies the value of the specified PRAGMA setting from |
| 3115 ** dbRbu to dbMain. |
| 3116 */ |
| 3117 static void rbuCopyPragma(sqlite3rbu *p, const char *zPragma){ |
| 3118 if( p->rc==SQLITE_OK ){ |
| 3119 sqlite3_stmt *pPragma = 0; |
| 3120 p->rc = prepareFreeAndCollectError(p->dbRbu, &pPragma, &p->zErrmsg, |
| 3121 sqlite3_mprintf("PRAGMA main.%s", zPragma) |
| 3122 ); |
| 3123 if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPragma) ){ |
| 3124 p->rc = rbuMPrintfExec(p, p->dbMain, "PRAGMA main.%s = %d", |
| 3125 zPragma, sqlite3_column_int(pPragma, 0) |
| 3126 ); |
| 3127 } |
| 3128 rbuFinalize(p, pPragma); |
| 3129 } |
| 3130 } |
| 3131 |
| 3132 /* |
| 3133 ** The RBU handle passed as the only argument has just been opened and |
| 3134 ** the state database is empty. If this RBU handle was opened for an |
| 3135 ** RBU vacuum operation, create the schema in the target db. |
| 3136 */ |
| 3137 static void rbuCreateTargetSchema(sqlite3rbu *p){ |
| 3138 sqlite3_stmt *pSql = 0; |
| 3139 sqlite3_stmt *pInsert = 0; |
| 3140 |
| 3141 assert( rbuIsVacuum(p) ); |
| 3142 p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=1", 0,0, &p->zErrmsg); |
| 3143 if( p->rc==SQLITE_OK ){ |
| 3144 p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg, |
| 3145 "SELECT sql FROM sqlite_master WHERE sql!='' AND rootpage!=0" |
| 3146 " AND name!='sqlite_sequence' " |
| 3147 " ORDER BY type DESC" |
| 3148 ); |
| 3149 } |
| 3150 |
| 3151 while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){ |
| 3152 const char *zSql = (const char*)sqlite3_column_text(pSql, 0); |
| 3153 p->rc = sqlite3_exec(p->dbMain, zSql, 0, 0, &p->zErrmsg); |
| 3154 } |
| 3155 rbuFinalize(p, pSql); |
| 3156 if( p->rc!=SQLITE_OK ) return; |
| 3157 |
| 3158 if( p->rc==SQLITE_OK ){ |
| 3159 p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg, |
| 3160 "SELECT * FROM sqlite_master WHERE rootpage=0 OR rootpage IS NULL" |
| 3161 ); |
| 3162 } |
| 3163 |
| 3164 if( p->rc==SQLITE_OK ){ |
| 3165 p->rc = prepareAndCollectError(p->dbMain, &pInsert, &p->zErrmsg, |
| 3166 "INSERT INTO sqlite_master VALUES(?,?,?,?,?)" |
| 3167 ); |
| 3168 } |
| 3169 |
| 3170 while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){ |
| 3171 int i; |
| 3172 for(i=0; i<5; i++){ |
| 3173 sqlite3_bind_value(pInsert, i+1, sqlite3_column_value(pSql, i)); |
| 3174 } |
| 3175 sqlite3_step(pInsert); |
| 3176 p->rc = sqlite3_reset(pInsert); |
| 3177 } |
| 3178 if( p->rc==SQLITE_OK ){ |
| 3179 p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=0",0,0,&p->zErrmsg); |
| 3180 } |
| 3181 |
| 3182 rbuFinalize(p, pSql); |
| 3183 rbuFinalize(p, pInsert); |
| 3184 } |
| 3185 |
| 3186 /* |
| 3187 ** Step the RBU object. |
| 3188 */ |
| 3189 int sqlite3rbu_step(sqlite3rbu *p){ |
| 3190 if( p ){ |
| 3191 switch( p->eStage ){ |
| 3192 case RBU_STAGE_OAL: { |
| 3193 RbuObjIter *pIter = &p->objiter; |
| 3194 |
| 3195 /* If this is an RBU vacuum operation and the state table was empty |
| 3196 ** when this handle was opened, create the target database schema. */ |
| 3197 if( rbuIsVacuum(p) && p->nProgress==0 && p->rc==SQLITE_OK ){ |
| 3198 rbuCreateTargetSchema(p); |
| 3199 rbuCopyPragma(p, "user_version"); |
| 3200 rbuCopyPragma(p, "application_id"); |
| 3201 } |
| 3202 |
| 3203 while( p->rc==SQLITE_OK && pIter->zTbl ){ |
| 3204 |
| 3205 if( pIter->bCleanup ){ |
| 3206 /* Clean up the rbu_tmp_xxx table for the previous table. It |
| 3207 ** cannot be dropped as there are currently active SQL statements. |
| 3208 ** But the contents can be deleted. */ |
| 3209 if( rbuIsVacuum(p)==0 && pIter->abIndexed ){ |
| 3210 rbuMPrintfExec(p, p->dbRbu, |
| 3211 "DELETE FROM %s.'rbu_tmp_%q'", p->zStateDb, pIter->zDataTbl |
| 3212 ); |
| 3213 } |
| 3214 }else{ |
| 3215 rbuObjIterPrepareAll(p, pIter, 0); |
| 3216 |
| 3217 /* Advance to the next row to process. */ |
| 3218 if( p->rc==SQLITE_OK ){ |
| 3219 int rc = sqlite3_step(pIter->pSelect); |
| 3220 if( rc==SQLITE_ROW ){ |
| 3221 p->nProgress++; |
| 3222 p->nStep++; |
| 3223 return rbuStep(p); |
| 3224 } |
| 3225 p->rc = sqlite3_reset(pIter->pSelect); |
| 3226 p->nStep = 0; |
| 3227 } |
| 3228 } |
| 3229 |
| 3230 rbuObjIterNext(p, pIter); |
| 3231 } |
| 3232 |
| 3233 if( p->rc==SQLITE_OK ){ |
| 3234 assert( pIter->zTbl==0 ); |
| 3235 rbuSaveState(p, RBU_STAGE_MOVE); |
| 3236 rbuIncrSchemaCookie(p); |
| 3237 if( p->rc==SQLITE_OK ){ |
| 3238 p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg); |
| 3239 } |
| 3240 if( p->rc==SQLITE_OK ){ |
| 3241 p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg); |
| 3242 } |
| 3243 p->eStage = RBU_STAGE_MOVE; |
| 3244 } |
| 3245 break; |
| 3246 } |
| 3247 |
| 3248 case RBU_STAGE_MOVE: { |
| 3249 if( p->rc==SQLITE_OK ){ |
| 3250 rbuMoveOalFile(p); |
| 3251 p->nProgress++; |
| 3252 } |
| 3253 break; |
| 3254 } |
| 3255 |
| 3256 case RBU_STAGE_CKPT: { |
| 3257 if( p->rc==SQLITE_OK ){ |
| 3258 if( p->nStep>=p->nFrame ){ |
| 3259 sqlite3_file *pDb = p->pTargetFd->pReal; |
| 3260 |
| 3261 /* Sync the db file */ |
| 3262 p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL); |
| 3263 |
| 3264 /* Update nBackfill */ |
| 3265 if( p->rc==SQLITE_OK ){ |
| 3266 void volatile *ptr; |
| 3267 p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, &ptr); |
| 3268 if( p->rc==SQLITE_OK ){ |
| 3269 ((u32 volatile*)ptr)[24] = p->iMaxFrame; |
| 3270 } |
| 3271 } |
| 3272 |
| 3273 if( p->rc==SQLITE_OK ){ |
| 3274 p->eStage = RBU_STAGE_DONE; |
| 3275 p->rc = SQLITE_DONE; |
| 3276 } |
| 3277 }else{ |
| 3278 RbuFrame *pFrame = &p->aFrame[p->nStep]; |
| 3279 rbuCheckpointFrame(p, pFrame); |
| 3280 p->nStep++; |
| 3281 } |
| 3282 p->nProgress++; |
| 3283 } |
| 3284 break; |
| 3285 } |
| 3286 |
| 3287 default: |
| 3288 break; |
| 3289 } |
| 3290 return p->rc; |
| 3291 }else{ |
| 3292 return SQLITE_NOMEM; |
| 3293 } |
| 3294 } |
| 3295 |
| 3296 /* |
| 3297 ** Compare strings z1 and z2, returning 0 if they are identical, or non-zero |
| 3298 ** otherwise. Either or both argument may be NULL. Two NULL values are |
| 3299 ** considered equal, and NULL is considered distinct from all other values. |
| 3300 */ |
| 3301 static int rbuStrCompare(const char *z1, const char *z2){ |
| 3302 if( z1==0 && z2==0 ) return 0; |
| 3303 if( z1==0 || z2==0 ) return 1; |
| 3304 return (sqlite3_stricmp(z1, z2)!=0); |
| 3305 } |
| 3306 |
| 3307 /* |
| 3308 ** This function is called as part of sqlite3rbu_open() when initializing |
| 3309 ** an rbu handle in OAL stage. If the rbu update has not started (i.e. |
| 3310 ** the rbu_state table was empty) it is a no-op. Otherwise, it arranges |
| 3311 ** things so that the next call to sqlite3rbu_step() continues on from |
| 3312 ** where the previous rbu handle left off. |
| 3313 ** |
| 3314 ** If an error occurs, an error code and error message are left in the |
| 3315 ** rbu handle passed as the first argument. |
| 3316 */ |
| 3317 static void rbuSetupOal(sqlite3rbu *p, RbuState *pState){ |
| 3318 assert( p->rc==SQLITE_OK ); |
| 3319 if( pState->zTbl ){ |
| 3320 RbuObjIter *pIter = &p->objiter; |
| 3321 int rc = SQLITE_OK; |
| 3322 |
| 3323 while( rc==SQLITE_OK && pIter->zTbl && (pIter->bCleanup |
| 3324 || rbuStrCompare(pIter->zIdx, pState->zIdx) |
| 3325 || rbuStrCompare(pIter->zTbl, pState->zTbl) |
| 3326 )){ |
| 3327 rc = rbuObjIterNext(p, pIter); |
| 3328 } |
| 3329 |
| 3330 if( rc==SQLITE_OK && !pIter->zTbl ){ |
| 3331 rc = SQLITE_ERROR; |
| 3332 p->zErrmsg = sqlite3_mprintf("rbu_state mismatch error"); |
| 3333 } |
| 3334 |
| 3335 if( rc==SQLITE_OK ){ |
| 3336 p->nStep = pState->nRow; |
| 3337 rc = rbuObjIterPrepareAll(p, &p->objiter, p->nStep); |
| 3338 } |
| 3339 |
| 3340 p->rc = rc; |
| 3341 } |
| 3342 } |
| 3343 |
| 3344 /* |
| 3345 ** If there is a "*-oal" file in the file-system corresponding to the |
| 3346 ** target database in the file-system, delete it. If an error occurs, |
| 3347 ** leave an error code and error message in the rbu handle. |
| 3348 */ |
| 3349 static void rbuDeleteOalFile(sqlite3rbu *p){ |
| 3350 char *zOal = rbuMPrintf(p, "%s-oal", p->zTarget); |
| 3351 if( zOal ){ |
| 3352 sqlite3_vfs *pVfs = sqlite3_vfs_find(0); |
| 3353 assert( pVfs && p->rc==SQLITE_OK && p->zErrmsg==0 ); |
| 3354 pVfs->xDelete(pVfs, zOal, 0); |
| 3355 sqlite3_free(zOal); |
| 3356 } |
| 3357 } |
| 3358 |
| 3359 /* |
| 3360 ** Allocate a private rbu VFS for the rbu handle passed as the only |
| 3361 ** argument. This VFS will be used unless the call to sqlite3rbu_open() |
| 3362 ** specified a URI with a vfs=? option in place of a target database |
| 3363 ** file name. |
| 3364 */ |
| 3365 static void rbuCreateVfs(sqlite3rbu *p){ |
| 3366 int rnd; |
| 3367 char zRnd[64]; |
| 3368 |
| 3369 assert( p->rc==SQLITE_OK ); |
| 3370 sqlite3_randomness(sizeof(int), (void*)&rnd); |
| 3371 sqlite3_snprintf(sizeof(zRnd), zRnd, "rbu_vfs_%d", rnd); |
| 3372 p->rc = sqlite3rbu_create_vfs(zRnd, 0); |
| 3373 if( p->rc==SQLITE_OK ){ |
| 3374 sqlite3_vfs *pVfs = sqlite3_vfs_find(zRnd); |
| 3375 assert( pVfs ); |
| 3376 p->zVfsName = pVfs->zName; |
| 3377 } |
| 3378 } |
| 3379 |
| 3380 /* |
| 3381 ** Destroy the private VFS created for the rbu handle passed as the only |
| 3382 ** argument by an earlier call to rbuCreateVfs(). |
| 3383 */ |
| 3384 static void rbuDeleteVfs(sqlite3rbu *p){ |
| 3385 if( p->zVfsName ){ |
| 3386 sqlite3rbu_destroy_vfs(p->zVfsName); |
| 3387 p->zVfsName = 0; |
| 3388 } |
| 3389 } |
| 3390 |
| 3391 /* |
| 3392 ** This user-defined SQL function is invoked with a single argument - the |
| 3393 ** name of a table expected to appear in the target database. It returns |
| 3394 ** the number of auxilliary indexes on the table. |
| 3395 */ |
| 3396 static void rbuIndexCntFunc( |
| 3397 sqlite3_context *pCtx, |
| 3398 int nVal, |
| 3399 sqlite3_value **apVal |
| 3400 ){ |
| 3401 sqlite3rbu *p = (sqlite3rbu*)sqlite3_user_data(pCtx); |
| 3402 sqlite3_stmt *pStmt = 0; |
| 3403 char *zErrmsg = 0; |
| 3404 int rc; |
| 3405 |
| 3406 assert( nVal==1 ); |
| 3407 |
| 3408 rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &zErrmsg, |
| 3409 sqlite3_mprintf("SELECT count(*) FROM sqlite_master " |
| 3410 "WHERE type='index' AND tbl_name = %Q", sqlite3_value_text(apVal[0])) |
| 3411 ); |
| 3412 if( rc!=SQLITE_OK ){ |
| 3413 sqlite3_result_error(pCtx, zErrmsg, -1); |
| 3414 }else{ |
| 3415 int nIndex = 0; |
| 3416 if( SQLITE_ROW==sqlite3_step(pStmt) ){ |
| 3417 nIndex = sqlite3_column_int(pStmt, 0); |
| 3418 } |
| 3419 rc = sqlite3_finalize(pStmt); |
| 3420 if( rc==SQLITE_OK ){ |
| 3421 sqlite3_result_int(pCtx, nIndex); |
| 3422 }else{ |
| 3423 sqlite3_result_error(pCtx, sqlite3_errmsg(p->dbMain), -1); |
| 3424 } |
| 3425 } |
| 3426 |
| 3427 sqlite3_free(zErrmsg); |
| 3428 } |
| 3429 |
| 3430 /* |
| 3431 ** If the RBU database contains the rbu_count table, use it to initialize |
| 3432 ** the sqlite3rbu.nPhaseOneStep variable. The schema of the rbu_count table |
| 3433 ** is assumed to contain the same columns as: |
| 3434 ** |
| 3435 ** CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID; |
| 3436 ** |
| 3437 ** There should be one row in the table for each data_xxx table in the |
| 3438 ** database. The 'tbl' column should contain the name of a data_xxx table, |
| 3439 ** and the cnt column the number of rows it contains. |
| 3440 ** |
| 3441 ** sqlite3rbu.nPhaseOneStep is initialized to the sum of (1 + nIndex) * cnt |
| 3442 ** for all rows in the rbu_count table, where nIndex is the number of |
| 3443 ** indexes on the corresponding target database table. |
| 3444 */ |
| 3445 static void rbuInitPhaseOneSteps(sqlite3rbu *p){ |
| 3446 if( p->rc==SQLITE_OK ){ |
| 3447 sqlite3_stmt *pStmt = 0; |
| 3448 int bExists = 0; /* True if rbu_count exists */ |
| 3449 |
| 3450 p->nPhaseOneStep = -1; |
| 3451 |
| 3452 p->rc = sqlite3_create_function(p->dbRbu, |
| 3453 "rbu_index_cnt", 1, SQLITE_UTF8, (void*)p, rbuIndexCntFunc, 0, 0 |
| 3454 ); |
| 3455 |
| 3456 /* Check for the rbu_count table. If it does not exist, or if an error |
| 3457 ** occurs, nPhaseOneStep will be left set to -1. */ |
| 3458 if( p->rc==SQLITE_OK ){ |
| 3459 p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg, |
| 3460 "SELECT 1 FROM sqlite_master WHERE tbl_name = 'rbu_count'" |
| 3461 ); |
| 3462 } |
| 3463 if( p->rc==SQLITE_OK ){ |
| 3464 if( SQLITE_ROW==sqlite3_step(pStmt) ){ |
| 3465 bExists = 1; |
| 3466 } |
| 3467 p->rc = sqlite3_finalize(pStmt); |
| 3468 } |
| 3469 |
| 3470 if( p->rc==SQLITE_OK && bExists ){ |
| 3471 p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg, |
| 3472 "SELECT sum(cnt * (1 + rbu_index_cnt(rbu_target_name(tbl))))" |
| 3473 "FROM rbu_count" |
| 3474 ); |
| 3475 if( p->rc==SQLITE_OK ){ |
| 3476 if( SQLITE_ROW==sqlite3_step(pStmt) ){ |
| 3477 p->nPhaseOneStep = sqlite3_column_int64(pStmt, 0); |
| 3478 } |
| 3479 p->rc = sqlite3_finalize(pStmt); |
| 3480 } |
| 3481 } |
| 3482 } |
| 3483 } |
| 3484 |
| 3485 |
| 3486 static sqlite3rbu *openRbuHandle( |
| 3487 const char *zTarget, |
| 3488 const char *zRbu, |
| 3489 const char *zState |
| 3490 ){ |
| 3491 sqlite3rbu *p; |
| 3492 size_t nTarget = zTarget ? strlen(zTarget) : 0; |
| 3493 size_t nRbu = strlen(zRbu); |
| 3494 size_t nByte = sizeof(sqlite3rbu) + nTarget+1 + nRbu+1; |
| 3495 |
| 3496 p = (sqlite3rbu*)sqlite3_malloc64(nByte); |
| 3497 if( p ){ |
| 3498 RbuState *pState = 0; |
| 3499 |
| 3500 /* Create the custom VFS. */ |
| 3501 memset(p, 0, sizeof(sqlite3rbu)); |
| 3502 rbuCreateVfs(p); |
| 3503 |
| 3504 /* Open the target, RBU and state databases */ |
| 3505 if( p->rc==SQLITE_OK ){ |
| 3506 char *pCsr = (char*)&p[1]; |
| 3507 int bRetry = 0; |
| 3508 if( zTarget ){ |
| 3509 p->zTarget = pCsr; |
| 3510 memcpy(p->zTarget, zTarget, nTarget+1); |
| 3511 pCsr += nTarget+1; |
| 3512 } |
| 3513 p->zRbu = pCsr; |
| 3514 memcpy(p->zRbu, zRbu, nRbu+1); |
| 3515 pCsr += nRbu+1; |
| 3516 if( zState ){ |
| 3517 p->zState = rbuMPrintf(p, "%s", zState); |
| 3518 } |
| 3519 |
| 3520 /* If the first attempt to open the database file fails and the bRetry |
| 3521 ** flag it set, this means that the db was not opened because it seemed |
| 3522 ** to be a wal-mode db. But, this may have happened due to an earlier |
| 3523 ** RBU vacuum operation leaving an old wal file in the directory. |
| 3524 ** If this is the case, it will have been checkpointed and deleted |
| 3525 ** when the handle was closed and a second attempt to open the |
| 3526 ** database may succeed. */ |
| 3527 rbuOpenDatabase(p, &bRetry); |
| 3528 if( bRetry ){ |
| 3529 rbuOpenDatabase(p, 0); |
| 3530 } |
| 3531 } |
| 3532 |
| 3533 if( p->rc==SQLITE_OK ){ |
| 3534 pState = rbuLoadState(p); |
| 3535 assert( pState || p->rc!=SQLITE_OK ); |
| 3536 if( p->rc==SQLITE_OK ){ |
| 3537 |
| 3538 if( pState->eStage==0 ){ |
| 3539 rbuDeleteOalFile(p); |
| 3540 rbuInitPhaseOneSteps(p); |
| 3541 p->eStage = RBU_STAGE_OAL; |
| 3542 }else{ |
| 3543 p->eStage = pState->eStage; |
| 3544 p->nPhaseOneStep = pState->nPhaseOneStep; |
| 3545 } |
| 3546 p->nProgress = pState->nProgress; |
| 3547 p->iOalSz = pState->iOalSz; |
| 3548 } |
| 3549 } |
| 3550 assert( p->rc!=SQLITE_OK || p->eStage!=0 ); |
| 3551 |
| 3552 if( p->rc==SQLITE_OK && p->pTargetFd->pWalFd ){ |
| 3553 if( p->eStage==RBU_STAGE_OAL ){ |
| 3554 p->rc = SQLITE_ERROR; |
| 3555 p->zErrmsg = sqlite3_mprintf("cannot update wal mode database"); |
| 3556 }else if( p->eStage==RBU_STAGE_MOVE ){ |
| 3557 p->eStage = RBU_STAGE_CKPT; |
| 3558 p->nStep = 0; |
| 3559 } |
| 3560 } |
| 3561 |
| 3562 if( p->rc==SQLITE_OK |
| 3563 && (p->eStage==RBU_STAGE_OAL || p->eStage==RBU_STAGE_MOVE) |
| 3564 && pState->eStage!=0 |
| 3565 ){ |
| 3566 rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd); |
| 3567 if( pFd->iCookie!=pState->iCookie ){ |
| 3568 /* At this point (pTargetFd->iCookie) contains the value of the |
| 3569 ** change-counter cookie (the thing that gets incremented when a |
| 3570 ** transaction is committed in rollback mode) currently stored on |
| 3571 ** page 1 of the database file. */ |
| 3572 p->rc = SQLITE_BUSY; |
| 3573 p->zErrmsg = sqlite3_mprintf("database modified during rbu %s", |
| 3574 (rbuIsVacuum(p) ? "vacuum" : "update") |
| 3575 ); |
| 3576 } |
| 3577 } |
| 3578 |
| 3579 if( p->rc==SQLITE_OK ){ |
| 3580 if( p->eStage==RBU_STAGE_OAL ){ |
| 3581 sqlite3 *db = p->dbMain; |
| 3582 p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, &p->zErrmsg); |
| 3583 |
| 3584 /* Point the object iterator at the first object */ |
| 3585 if( p->rc==SQLITE_OK ){ |
| 3586 p->rc = rbuObjIterFirst(p, &p->objiter); |
| 3587 } |
| 3588 |
| 3589 /* If the RBU database contains no data_xxx tables, declare the RBU |
| 3590 ** update finished. */ |
| 3591 if( p->rc==SQLITE_OK && p->objiter.zTbl==0 ){ |
| 3592 p->rc = SQLITE_DONE; |
| 3593 p->eStage = RBU_STAGE_DONE; |
| 3594 }else{ |
| 3595 if( p->rc==SQLITE_OK && pState->eStage==0 && rbuIsVacuum(p) ){ |
| 3596 rbuCopyPragma(p, "page_size"); |
| 3597 rbuCopyPragma(p, "auto_vacuum"); |
| 3598 } |
| 3599 |
| 3600 /* Open transactions both databases. The *-oal file is opened or |
| 3601 ** created at this point. */ |
| 3602 if( p->rc==SQLITE_OK ){ |
| 3603 p->rc = sqlite3_exec(db, "BEGIN IMMEDIATE", 0, 0, &p->zErrmsg); |
| 3604 } |
| 3605 |
| 3606 /* Check if the main database is a zipvfs db. If it is, set the upper |
| 3607 ** level pager to use "journal_mode=off". This prevents it from |
| 3608 ** generating a large journal using a temp file. */ |
| 3609 if( p->rc==SQLITE_OK ){ |
| 3610 int frc = sqlite3_file_control(db, "main", SQLITE_FCNTL_ZIPVFS, 0); |
| 3611 if( frc==SQLITE_OK ){ |
| 3612 p->rc = sqlite3_exec( |
| 3613 db, "PRAGMA journal_mode=off",0,0,&p->zErrmsg); |
| 3614 } |
| 3615 } |
| 3616 |
| 3617 if( p->rc==SQLITE_OK ){ |
| 3618 rbuSetupOal(p, pState); |
| 3619 } |
| 3620 } |
| 3621 }else if( p->eStage==RBU_STAGE_MOVE ){ |
| 3622 /* no-op */ |
| 3623 }else if( p->eStage==RBU_STAGE_CKPT ){ |
| 3624 rbuSetupCheckpoint(p, pState); |
| 3625 }else if( p->eStage==RBU_STAGE_DONE ){ |
| 3626 p->rc = SQLITE_DONE; |
| 3627 }else{ |
| 3628 p->rc = SQLITE_CORRUPT; |
| 3629 } |
| 3630 } |
| 3631 |
| 3632 rbuFreeState(pState); |
| 3633 } |
| 3634 |
| 3635 return p; |
| 3636 } |
| 3637 |
| 3638 /* |
| 3639 ** Allocate and return an RBU handle with all fields zeroed except for the |
| 3640 ** error code, which is set to SQLITE_MISUSE. |
| 3641 */ |
| 3642 static sqlite3rbu *rbuMisuseError(void){ |
| 3643 sqlite3rbu *pRet; |
| 3644 pRet = sqlite3_malloc64(sizeof(sqlite3rbu)); |
| 3645 if( pRet ){ |
| 3646 memset(pRet, 0, sizeof(sqlite3rbu)); |
| 3647 pRet->rc = SQLITE_MISUSE; |
| 3648 } |
| 3649 return pRet; |
| 3650 } |
| 3651 |
| 3652 /* |
| 3653 ** Open and return a new RBU handle. |
| 3654 */ |
| 3655 sqlite3rbu *sqlite3rbu_open( |
| 3656 const char *zTarget, |
| 3657 const char *zRbu, |
| 3658 const char *zState |
| 3659 ){ |
| 3660 if( zTarget==0 || zRbu==0 ){ return rbuMisuseError(); } |
| 3661 /* TODO: Check that zTarget and zRbu are non-NULL */ |
| 3662 return openRbuHandle(zTarget, zRbu, zState); |
| 3663 } |
| 3664 |
| 3665 /* |
| 3666 ** Open a handle to begin or resume an RBU VACUUM operation. |
| 3667 */ |
| 3668 sqlite3rbu *sqlite3rbu_vacuum( |
| 3669 const char *zTarget, |
| 3670 const char *zState |
| 3671 ){ |
| 3672 if( zTarget==0 ){ return rbuMisuseError(); } |
| 3673 /* TODO: Check that both arguments are non-NULL */ |
| 3674 return openRbuHandle(0, zTarget, zState); |
| 3675 } |
| 3676 |
| 3677 /* |
| 3678 ** Return the database handle used by pRbu. |
| 3679 */ |
| 3680 sqlite3 *sqlite3rbu_db(sqlite3rbu *pRbu, int bRbu){ |
| 3681 sqlite3 *db = 0; |
| 3682 if( pRbu ){ |
| 3683 db = (bRbu ? pRbu->dbRbu : pRbu->dbMain); |
| 3684 } |
| 3685 return db; |
| 3686 } |
| 3687 |
| 3688 |
| 3689 /* |
| 3690 ** If the error code currently stored in the RBU handle is SQLITE_CONSTRAINT, |
| 3691 ** then edit any error message string so as to remove all occurrences of |
| 3692 ** the pattern "rbu_imp_[0-9]*". |
| 3693 */ |
| 3694 static void rbuEditErrmsg(sqlite3rbu *p){ |
| 3695 if( p->rc==SQLITE_CONSTRAINT && p->zErrmsg ){ |
| 3696 unsigned int i; |
| 3697 size_t nErrmsg = strlen(p->zErrmsg); |
| 3698 for(i=0; i<(nErrmsg-8); i++){ |
| 3699 if( memcmp(&p->zErrmsg[i], "rbu_imp_", 8)==0 ){ |
| 3700 int nDel = 8; |
| 3701 while( p->zErrmsg[i+nDel]>='0' && p->zErrmsg[i+nDel]<='9' ) nDel++; |
| 3702 memmove(&p->zErrmsg[i], &p->zErrmsg[i+nDel], nErrmsg + 1 - i - nDel); |
| 3703 nErrmsg -= nDel; |
| 3704 } |
| 3705 } |
| 3706 } |
| 3707 } |
| 3708 |
| 3709 /* |
| 3710 ** Close the RBU handle. |
| 3711 */ |
| 3712 int sqlite3rbu_close(sqlite3rbu *p, char **pzErrmsg){ |
| 3713 int rc; |
| 3714 if( p ){ |
| 3715 |
| 3716 /* Commit the transaction to the *-oal file. */ |
| 3717 if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){ |
| 3718 p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg); |
| 3719 } |
| 3720 |
| 3721 rbuSaveState(p, p->eStage); |
| 3722 |
| 3723 if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){ |
| 3724 p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg); |
| 3725 } |
| 3726 |
| 3727 /* Close any open statement handles. */ |
| 3728 rbuObjIterFinalize(&p->objiter); |
| 3729 |
| 3730 /* If this is an RBU vacuum handle and the vacuum has either finished |
| 3731 ** successfully or encountered an error, delete the contents of the |
| 3732 ** state table. This causes the next call to sqlite3rbu_vacuum() |
| 3733 ** specifying the current target and state databases to start a new |
| 3734 ** vacuum from scratch. */ |
| 3735 if( rbuIsVacuum(p) && p->rc!=SQLITE_OK && p->dbRbu ){ |
| 3736 int rc2 = sqlite3_exec(p->dbRbu, "DELETE FROM stat.rbu_state", 0, 0, 0); |
| 3737 if( p->rc==SQLITE_DONE && rc2!=SQLITE_OK ) p->rc = rc2; |
| 3738 } |
| 3739 |
| 3740 /* Close the open database handle and VFS object. */ |
| 3741 sqlite3_close(p->dbRbu); |
| 3742 sqlite3_close(p->dbMain); |
| 3743 rbuDeleteVfs(p); |
| 3744 sqlite3_free(p->aBuf); |
| 3745 sqlite3_free(p->aFrame); |
| 3746 |
| 3747 rbuEditErrmsg(p); |
| 3748 rc = p->rc; |
| 3749 *pzErrmsg = p->zErrmsg; |
| 3750 sqlite3_free(p->zState); |
| 3751 sqlite3_free(p); |
| 3752 }else{ |
| 3753 rc = SQLITE_NOMEM; |
| 3754 *pzErrmsg = 0; |
| 3755 } |
| 3756 return rc; |
| 3757 } |
| 3758 |
| 3759 /* |
| 3760 ** Return the total number of key-value operations (inserts, deletes or |
| 3761 ** updates) that have been performed on the target database since the |
| 3762 ** current RBU update was started. |
| 3763 */ |
| 3764 sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu){ |
| 3765 return pRbu->nProgress; |
| 3766 } |
| 3767 |
| 3768 /* |
| 3769 ** Return permyriadage progress indications for the two main stages of |
| 3770 ** an RBU update. |
| 3771 */ |
| 3772 void sqlite3rbu_bp_progress(sqlite3rbu *p, int *pnOne, int *pnTwo){ |
| 3773 const int MAX_PROGRESS = 10000; |
| 3774 switch( p->eStage ){ |
| 3775 case RBU_STAGE_OAL: |
| 3776 if( p->nPhaseOneStep>0 ){ |
| 3777 *pnOne = (int)(MAX_PROGRESS * (i64)p->nProgress/(i64)p->nPhaseOneStep); |
| 3778 }else{ |
| 3779 *pnOne = -1; |
| 3780 } |
| 3781 *pnTwo = 0; |
| 3782 break; |
| 3783 |
| 3784 case RBU_STAGE_MOVE: |
| 3785 *pnOne = MAX_PROGRESS; |
| 3786 *pnTwo = 0; |
| 3787 break; |
| 3788 |
| 3789 case RBU_STAGE_CKPT: |
| 3790 *pnOne = MAX_PROGRESS; |
| 3791 *pnTwo = (int)(MAX_PROGRESS * (i64)p->nStep / (i64)p->nFrame); |
| 3792 break; |
| 3793 |
| 3794 case RBU_STAGE_DONE: |
| 3795 *pnOne = MAX_PROGRESS; |
| 3796 *pnTwo = MAX_PROGRESS; |
| 3797 break; |
| 3798 |
| 3799 default: |
| 3800 assert( 0 ); |
| 3801 } |
| 3802 } |
| 3803 |
| 3804 /* |
| 3805 ** Return the current state of the RBU vacuum or update operation. |
| 3806 */ |
| 3807 int sqlite3rbu_state(sqlite3rbu *p){ |
| 3808 int aRes[] = { |
| 3809 0, SQLITE_RBU_STATE_OAL, SQLITE_RBU_STATE_MOVE, |
| 3810 0, SQLITE_RBU_STATE_CHECKPOINT, SQLITE_RBU_STATE_DONE |
| 3811 }; |
| 3812 |
| 3813 assert( RBU_STAGE_OAL==1 ); |
| 3814 assert( RBU_STAGE_MOVE==2 ); |
| 3815 assert( RBU_STAGE_CKPT==4 ); |
| 3816 assert( RBU_STAGE_DONE==5 ); |
| 3817 assert( aRes[RBU_STAGE_OAL]==SQLITE_RBU_STATE_OAL ); |
| 3818 assert( aRes[RBU_STAGE_MOVE]==SQLITE_RBU_STATE_MOVE ); |
| 3819 assert( aRes[RBU_STAGE_CKPT]==SQLITE_RBU_STATE_CHECKPOINT ); |
| 3820 assert( aRes[RBU_STAGE_DONE]==SQLITE_RBU_STATE_DONE ); |
| 3821 |
| 3822 if( p->rc!=SQLITE_OK && p->rc!=SQLITE_DONE ){ |
| 3823 return SQLITE_RBU_STATE_ERROR; |
| 3824 }else{ |
| 3825 assert( p->rc!=SQLITE_DONE || p->eStage==RBU_STAGE_DONE ); |
| 3826 assert( p->eStage==RBU_STAGE_OAL |
| 3827 || p->eStage==RBU_STAGE_MOVE |
| 3828 || p->eStage==RBU_STAGE_CKPT |
| 3829 || p->eStage==RBU_STAGE_DONE |
| 3830 ); |
| 3831 return aRes[p->eStage]; |
| 3832 } |
| 3833 } |
| 3834 |
| 3835 int sqlite3rbu_savestate(sqlite3rbu *p){ |
| 3836 int rc = p->rc; |
| 3837 if( rc==SQLITE_DONE ) return SQLITE_OK; |
| 3838 |
| 3839 assert( p->eStage>=RBU_STAGE_OAL && p->eStage<=RBU_STAGE_DONE ); |
| 3840 if( p->eStage==RBU_STAGE_OAL ){ |
| 3841 assert( rc!=SQLITE_DONE ); |
| 3842 if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, 0); |
| 3843 } |
| 3844 |
| 3845 p->rc = rc; |
| 3846 rbuSaveState(p, p->eStage); |
| 3847 rc = p->rc; |
| 3848 |
| 3849 if( p->eStage==RBU_STAGE_OAL ){ |
| 3850 assert( rc!=SQLITE_DONE ); |
| 3851 if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0); |
| 3852 if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "BEGIN IMMEDIATE", 0, 0, 0); |
| 3853 if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "BEGIN IMMEDIATE", 0, 0,0); |
| 3854 } |
| 3855 |
| 3856 p->rc = rc; |
| 3857 return rc; |
| 3858 } |
| 3859 |
| 3860 /************************************************************************** |
| 3861 ** Beginning of RBU VFS shim methods. The VFS shim modifies the behaviour |
| 3862 ** of a standard VFS in the following ways: |
| 3863 ** |
| 3864 ** 1. Whenever the first page of a main database file is read or |
| 3865 ** written, the value of the change-counter cookie is stored in |
| 3866 ** rbu_file.iCookie. Similarly, the value of the "write-version" |
| 3867 ** database header field is stored in rbu_file.iWriteVer. This ensures |
| 3868 ** that the values are always trustworthy within an open transaction. |
| 3869 ** |
| 3870 ** 2. Whenever an SQLITE_OPEN_WAL file is opened, the (rbu_file.pWalFd) |
| 3871 ** member variable of the associated database file descriptor is set |
| 3872 ** to point to the new file. A mutex protected linked list of all main |
| 3873 ** db fds opened using a particular RBU VFS is maintained at |
| 3874 ** rbu_vfs.pMain to facilitate this. |
| 3875 ** |
| 3876 ** 3. Using a new file-control "SQLITE_FCNTL_RBU", a main db rbu_file |
| 3877 ** object can be marked as the target database of an RBU update. This |
| 3878 ** turns on the following extra special behaviour: |
| 3879 ** |
| 3880 ** 3a. If xAccess() is called to check if there exists a *-wal file |
| 3881 ** associated with an RBU target database currently in RBU_STAGE_OAL |
| 3882 ** stage (preparing the *-oal file), the following special handling |
| 3883 ** applies: |
| 3884 ** |
| 3885 ** * if the *-wal file does exist, return SQLITE_CANTOPEN. An RBU |
| 3886 ** target database may not be in wal mode already. |
| 3887 ** |
| 3888 ** * if the *-wal file does not exist, set the output parameter to |
| 3889 ** non-zero (to tell SQLite that it does exist) anyway. |
| 3890 ** |
| 3891 ** Then, when xOpen() is called to open the *-wal file associated with |
| 3892 ** the RBU target in RBU_STAGE_OAL stage, instead of opening the *-wal |
| 3893 ** file, the rbu vfs opens the corresponding *-oal file instead. |
| 3894 ** |
| 3895 ** 3b. The *-shm pages returned by xShmMap() for a target db file in |
| 3896 ** RBU_STAGE_OAL mode are actually stored in heap memory. This is to |
| 3897 ** avoid creating a *-shm file on disk. Additionally, xShmLock() calls |
| 3898 ** are no-ops on target database files in RBU_STAGE_OAL mode. This is |
| 3899 ** because assert() statements in some VFS implementations fail if |
| 3900 ** xShmLock() is called before xShmMap(). |
| 3901 ** |
| 3902 ** 3c. If an EXCLUSIVE lock is attempted on a target database file in any |
| 3903 ** mode except RBU_STAGE_DONE (all work completed and checkpointed), it |
| 3904 ** fails with an SQLITE_BUSY error. This is to stop RBU connections |
| 3905 ** from automatically checkpointing a *-wal (or *-oal) file from within |
| 3906 ** sqlite3_close(). |
| 3907 ** |
| 3908 ** 3d. In RBU_STAGE_CAPTURE mode, all xRead() calls on the wal file, and |
| 3909 ** all xWrite() calls on the target database file perform no IO. |
| 3910 ** Instead the frame and page numbers that would be read and written |
| 3911 ** are recorded. Additionally, successful attempts to obtain exclusive |
| 3912 ** xShmLock() WRITER, CHECKPOINTER and READ0 locks on the target |
| 3913 ** database file are recorded. xShmLock() calls to unlock the same |
| 3914 ** locks are no-ops (so that once obtained, these locks are never |
| 3915 ** relinquished). Finally, calls to xSync() on the target database |
| 3916 ** file fail with SQLITE_INTERNAL errors. |
| 3917 */ |
| 3918 |
| 3919 static void rbuUnlockShm(rbu_file *p){ |
| 3920 if( p->pRbu ){ |
| 3921 int (*xShmLock)(sqlite3_file*,int,int,int) = p->pReal->pMethods->xShmLock; |
| 3922 int i; |
| 3923 for(i=0; i<SQLITE_SHM_NLOCK;i++){ |
| 3924 if( (1<<i) & p->pRbu->mLock ){ |
| 3925 xShmLock(p->pReal, i, 1, SQLITE_SHM_UNLOCK|SQLITE_SHM_EXCLUSIVE); |
| 3926 } |
| 3927 } |
| 3928 p->pRbu->mLock = 0; |
| 3929 } |
| 3930 } |
| 3931 |
| 3932 /* |
| 3933 ** Close an rbu file. |
| 3934 */ |
| 3935 static int rbuVfsClose(sqlite3_file *pFile){ |
| 3936 rbu_file *p = (rbu_file*)pFile; |
| 3937 int rc; |
| 3938 int i; |
| 3939 |
| 3940 /* Free the contents of the apShm[] array. And the array itself. */ |
| 3941 for(i=0; i<p->nShm; i++){ |
| 3942 sqlite3_free(p->apShm[i]); |
| 3943 } |
| 3944 sqlite3_free(p->apShm); |
| 3945 p->apShm = 0; |
| 3946 sqlite3_free(p->zDel); |
| 3947 |
| 3948 if( p->openFlags & SQLITE_OPEN_MAIN_DB ){ |
| 3949 rbu_file **pp; |
| 3950 sqlite3_mutex_enter(p->pRbuVfs->mutex); |
| 3951 for(pp=&p->pRbuVfs->pMain; *pp!=p; pp=&((*pp)->pMainNext)); |
| 3952 *pp = p->pMainNext; |
| 3953 sqlite3_mutex_leave(p->pRbuVfs->mutex); |
| 3954 rbuUnlockShm(p); |
| 3955 p->pReal->pMethods->xShmUnmap(p->pReal, 0); |
| 3956 } |
| 3957 |
| 3958 /* Close the underlying file handle */ |
| 3959 rc = p->pReal->pMethods->xClose(p->pReal); |
| 3960 return rc; |
| 3961 } |
| 3962 |
| 3963 |
| 3964 /* |
| 3965 ** Read and return an unsigned 32-bit big-endian integer from the buffer |
| 3966 ** passed as the only argument. |
| 3967 */ |
| 3968 static u32 rbuGetU32(u8 *aBuf){ |
| 3969 return ((u32)aBuf[0] << 24) |
| 3970 + ((u32)aBuf[1] << 16) |
| 3971 + ((u32)aBuf[2] << 8) |
| 3972 + ((u32)aBuf[3]); |
| 3973 } |
| 3974 |
| 3975 /* |
| 3976 ** Write an unsigned 32-bit value in big-endian format to the supplied |
| 3977 ** buffer. |
| 3978 */ |
| 3979 static void rbuPutU32(u8 *aBuf, u32 iVal){ |
| 3980 aBuf[0] = (iVal >> 24) & 0xFF; |
| 3981 aBuf[1] = (iVal >> 16) & 0xFF; |
| 3982 aBuf[2] = (iVal >> 8) & 0xFF; |
| 3983 aBuf[3] = (iVal >> 0) & 0xFF; |
| 3984 } |
| 3985 |
| 3986 static void rbuPutU16(u8 *aBuf, u16 iVal){ |
| 3987 aBuf[0] = (iVal >> 8) & 0xFF; |
| 3988 aBuf[1] = (iVal >> 0) & 0xFF; |
| 3989 } |
| 3990 |
| 3991 /* |
| 3992 ** Read data from an rbuVfs-file. |
| 3993 */ |
| 3994 static int rbuVfsRead( |
| 3995 sqlite3_file *pFile, |
| 3996 void *zBuf, |
| 3997 int iAmt, |
| 3998 sqlite_int64 iOfst |
| 3999 ){ |
| 4000 rbu_file *p = (rbu_file*)pFile; |
| 4001 sqlite3rbu *pRbu = p->pRbu; |
| 4002 int rc; |
| 4003 |
| 4004 if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){ |
| 4005 assert( p->openFlags & SQLITE_OPEN_WAL ); |
| 4006 rc = rbuCaptureWalRead(p->pRbu, iOfst, iAmt); |
| 4007 }else{ |
| 4008 if( pRbu && pRbu->eStage==RBU_STAGE_OAL |
| 4009 && (p->openFlags & SQLITE_OPEN_WAL) |
| 4010 && iOfst>=pRbu->iOalSz |
| 4011 ){ |
| 4012 rc = SQLITE_OK; |
| 4013 memset(zBuf, 0, iAmt); |
| 4014 }else{ |
| 4015 rc = p->pReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst); |
| 4016 #if 1 |
| 4017 /* If this is being called to read the first page of the target |
| 4018 ** database as part of an rbu vacuum operation, synthesize the |
| 4019 ** contents of the first page if it does not yet exist. Otherwise, |
| 4020 ** SQLite will not check for a *-wal file. */ |
| 4021 if( pRbu && rbuIsVacuum(pRbu) |
| 4022 && rc==SQLITE_IOERR_SHORT_READ && iOfst==0 |
| 4023 && (p->openFlags & SQLITE_OPEN_MAIN_DB) |
| 4024 && pRbu->rc==SQLITE_OK |
| 4025 ){ |
| 4026 sqlite3_file *pFd = (sqlite3_file*)pRbu->pRbuFd; |
| 4027 rc = pFd->pMethods->xRead(pFd, zBuf, iAmt, iOfst); |
| 4028 if( rc==SQLITE_OK ){ |
| 4029 u8 *aBuf = (u8*)zBuf; |
| 4030 u32 iRoot = rbuGetU32(&aBuf[52]) ? 1 : 0; |
| 4031 rbuPutU32(&aBuf[52], iRoot); /* largest root page number */ |
| 4032 rbuPutU32(&aBuf[36], 0); /* number of free pages */ |
| 4033 rbuPutU32(&aBuf[32], 0); /* first page on free list trunk */ |
| 4034 rbuPutU32(&aBuf[28], 1); /* size of db file in pages */ |
| 4035 rbuPutU32(&aBuf[24], pRbu->pRbuFd->iCookie+1); /* Change counter */ |
| 4036 |
| 4037 if( iAmt>100 ){ |
| 4038 memset(&aBuf[100], 0, iAmt-100); |
| 4039 rbuPutU16(&aBuf[105], iAmt & 0xFFFF); |
| 4040 aBuf[100] = 0x0D; |
| 4041 } |
| 4042 } |
| 4043 } |
| 4044 #endif |
| 4045 } |
| 4046 if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){ |
| 4047 /* These look like magic numbers. But they are stable, as they are part |
| 4048 ** of the definition of the SQLite file format, which may not change. */ |
| 4049 u8 *pBuf = (u8*)zBuf; |
| 4050 p->iCookie = rbuGetU32(&pBuf[24]); |
| 4051 p->iWriteVer = pBuf[19]; |
| 4052 } |
| 4053 } |
| 4054 return rc; |
| 4055 } |
| 4056 |
| 4057 /* |
| 4058 ** Write data to an rbuVfs-file. |
| 4059 */ |
| 4060 static int rbuVfsWrite( |
| 4061 sqlite3_file *pFile, |
| 4062 const void *zBuf, |
| 4063 int iAmt, |
| 4064 sqlite_int64 iOfst |
| 4065 ){ |
| 4066 rbu_file *p = (rbu_file*)pFile; |
| 4067 sqlite3rbu *pRbu = p->pRbu; |
| 4068 int rc; |
| 4069 |
| 4070 if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){ |
| 4071 assert( p->openFlags & SQLITE_OPEN_MAIN_DB ); |
| 4072 rc = rbuCaptureDbWrite(p->pRbu, iOfst); |
| 4073 }else{ |
| 4074 if( pRbu && pRbu->eStage==RBU_STAGE_OAL |
| 4075 && (p->openFlags & SQLITE_OPEN_WAL) |
| 4076 && iOfst>=pRbu->iOalSz |
| 4077 ){ |
| 4078 pRbu->iOalSz = iAmt + iOfst; |
| 4079 } |
| 4080 rc = p->pReal->pMethods->xWrite(p->pReal, zBuf, iAmt, iOfst); |
| 4081 if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){ |
| 4082 /* These look like magic numbers. But they are stable, as they are part |
| 4083 ** of the definition of the SQLite file format, which may not change. */ |
| 4084 u8 *pBuf = (u8*)zBuf; |
| 4085 p->iCookie = rbuGetU32(&pBuf[24]); |
| 4086 p->iWriteVer = pBuf[19]; |
| 4087 } |
| 4088 } |
| 4089 return rc; |
| 4090 } |
| 4091 |
| 4092 /* |
| 4093 ** Truncate an rbuVfs-file. |
| 4094 */ |
| 4095 static int rbuVfsTruncate(sqlite3_file *pFile, sqlite_int64 size){ |
| 4096 rbu_file *p = (rbu_file*)pFile; |
| 4097 return p->pReal->pMethods->xTruncate(p->pReal, size); |
| 4098 } |
| 4099 |
| 4100 /* |
| 4101 ** Sync an rbuVfs-file. |
| 4102 */ |
| 4103 static int rbuVfsSync(sqlite3_file *pFile, int flags){ |
| 4104 rbu_file *p = (rbu_file *)pFile; |
| 4105 if( p->pRbu && p->pRbu->eStage==RBU_STAGE_CAPTURE ){ |
| 4106 if( p->openFlags & SQLITE_OPEN_MAIN_DB ){ |
| 4107 return SQLITE_INTERNAL; |
| 4108 } |
| 4109 return SQLITE_OK; |
| 4110 } |
| 4111 return p->pReal->pMethods->xSync(p->pReal, flags); |
| 4112 } |
| 4113 |
| 4114 /* |
| 4115 ** Return the current file-size of an rbuVfs-file. |
| 4116 */ |
| 4117 static int rbuVfsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){ |
| 4118 rbu_file *p = (rbu_file *)pFile; |
| 4119 int rc; |
| 4120 rc = p->pReal->pMethods->xFileSize(p->pReal, pSize); |
| 4121 |
| 4122 /* If this is an RBU vacuum operation and this is the target database, |
| 4123 ** pretend that it has at least one page. Otherwise, SQLite will not |
| 4124 ** check for the existance of a *-wal file. rbuVfsRead() contains |
| 4125 ** similar logic. */ |
| 4126 if( rc==SQLITE_OK && *pSize==0 |
| 4127 && p->pRbu && rbuIsVacuum(p->pRbu) |
| 4128 && (p->openFlags & SQLITE_OPEN_MAIN_DB) |
| 4129 ){ |
| 4130 *pSize = 1024; |
| 4131 } |
| 4132 return rc; |
| 4133 } |
| 4134 |
| 4135 /* |
| 4136 ** Lock an rbuVfs-file. |
| 4137 */ |
| 4138 static int rbuVfsLock(sqlite3_file *pFile, int eLock){ |
| 4139 rbu_file *p = (rbu_file*)pFile; |
| 4140 sqlite3rbu *pRbu = p->pRbu; |
| 4141 int rc = SQLITE_OK; |
| 4142 |
| 4143 assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) ); |
| 4144 if( eLock==SQLITE_LOCK_EXCLUSIVE |
| 4145 && (p->bNolock || (pRbu && pRbu->eStage!=RBU_STAGE_DONE)) |
| 4146 ){ |
| 4147 /* Do not allow EXCLUSIVE locks. Preventing SQLite from taking this |
| 4148 ** prevents it from checkpointing the database from sqlite3_close(). */ |
| 4149 rc = SQLITE_BUSY; |
| 4150 }else{ |
| 4151 rc = p->pReal->pMethods->xLock(p->pReal, eLock); |
| 4152 } |
| 4153 |
| 4154 return rc; |
| 4155 } |
| 4156 |
| 4157 /* |
| 4158 ** Unlock an rbuVfs-file. |
| 4159 */ |
| 4160 static int rbuVfsUnlock(sqlite3_file *pFile, int eLock){ |
| 4161 rbu_file *p = (rbu_file *)pFile; |
| 4162 return p->pReal->pMethods->xUnlock(p->pReal, eLock); |
| 4163 } |
| 4164 |
| 4165 /* |
| 4166 ** Check if another file-handle holds a RESERVED lock on an rbuVfs-file. |
| 4167 */ |
| 4168 static int rbuVfsCheckReservedLock(sqlite3_file *pFile, int *pResOut){ |
| 4169 rbu_file *p = (rbu_file *)pFile; |
| 4170 return p->pReal->pMethods->xCheckReservedLock(p->pReal, pResOut); |
| 4171 } |
| 4172 |
| 4173 /* |
| 4174 ** File control method. For custom operations on an rbuVfs-file. |
| 4175 */ |
| 4176 static int rbuVfsFileControl(sqlite3_file *pFile, int op, void *pArg){ |
| 4177 rbu_file *p = (rbu_file *)pFile; |
| 4178 int (*xControl)(sqlite3_file*,int,void*) = p->pReal->pMethods->xFileControl; |
| 4179 int rc; |
| 4180 |
| 4181 assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) |
| 4182 || p->openFlags & (SQLITE_OPEN_TRANSIENT_DB|SQLITE_OPEN_TEMP_JOURNAL) |
| 4183 ); |
| 4184 if( op==SQLITE_FCNTL_RBU ){ |
| 4185 sqlite3rbu *pRbu = (sqlite3rbu*)pArg; |
| 4186 |
| 4187 /* First try to find another RBU vfs lower down in the vfs stack. If |
| 4188 ** one is found, this vfs will operate in pass-through mode. The lower |
| 4189 ** level vfs will do the special RBU handling. */ |
| 4190 rc = xControl(p->pReal, op, pArg); |
| 4191 |
| 4192 if( rc==SQLITE_NOTFOUND ){ |
| 4193 /* Now search for a zipvfs instance lower down in the VFS stack. If |
| 4194 ** one is found, this is an error. */ |
| 4195 void *dummy = 0; |
| 4196 rc = xControl(p->pReal, SQLITE_FCNTL_ZIPVFS, &dummy); |
| 4197 if( rc==SQLITE_OK ){ |
| 4198 rc = SQLITE_ERROR; |
| 4199 pRbu->zErrmsg = sqlite3_mprintf("rbu/zipvfs setup error"); |
| 4200 }else if( rc==SQLITE_NOTFOUND ){ |
| 4201 pRbu->pTargetFd = p; |
| 4202 p->pRbu = pRbu; |
| 4203 if( p->pWalFd ) p->pWalFd->pRbu = pRbu; |
| 4204 rc = SQLITE_OK; |
| 4205 } |
| 4206 } |
| 4207 return rc; |
| 4208 } |
| 4209 else if( op==SQLITE_FCNTL_RBUCNT ){ |
| 4210 sqlite3rbu *pRbu = (sqlite3rbu*)pArg; |
| 4211 pRbu->nRbu++; |
| 4212 pRbu->pRbuFd = p; |
| 4213 p->bNolock = 1; |
| 4214 } |
| 4215 |
| 4216 rc = xControl(p->pReal, op, pArg); |
| 4217 if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){ |
| 4218 rbu_vfs *pRbuVfs = p->pRbuVfs; |
| 4219 char *zIn = *(char**)pArg; |
| 4220 char *zOut = sqlite3_mprintf("rbu(%s)/%z", pRbuVfs->base.zName, zIn); |
| 4221 *(char**)pArg = zOut; |
| 4222 if( zOut==0 ) rc = SQLITE_NOMEM; |
| 4223 } |
| 4224 |
| 4225 return rc; |
| 4226 } |
| 4227 |
| 4228 /* |
| 4229 ** Return the sector-size in bytes for an rbuVfs-file. |
| 4230 */ |
| 4231 static int rbuVfsSectorSize(sqlite3_file *pFile){ |
| 4232 rbu_file *p = (rbu_file *)pFile; |
| 4233 return p->pReal->pMethods->xSectorSize(p->pReal); |
| 4234 } |
| 4235 |
| 4236 /* |
| 4237 ** Return the device characteristic flags supported by an rbuVfs-file. |
| 4238 */ |
| 4239 static int rbuVfsDeviceCharacteristics(sqlite3_file *pFile){ |
| 4240 rbu_file *p = (rbu_file *)pFile; |
| 4241 return p->pReal->pMethods->xDeviceCharacteristics(p->pReal); |
| 4242 } |
| 4243 |
| 4244 /* |
| 4245 ** Take or release a shared-memory lock. |
| 4246 */ |
| 4247 static int rbuVfsShmLock(sqlite3_file *pFile, int ofst, int n, int flags){ |
| 4248 rbu_file *p = (rbu_file*)pFile; |
| 4249 sqlite3rbu *pRbu = p->pRbu; |
| 4250 int rc = SQLITE_OK; |
| 4251 |
| 4252 #ifdef SQLITE_AMALGAMATION |
| 4253 assert( WAL_CKPT_LOCK==1 ); |
| 4254 #endif |
| 4255 |
| 4256 assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) ); |
| 4257 if( pRbu && (pRbu->eStage==RBU_STAGE_OAL || pRbu->eStage==RBU_STAGE_MOVE) ){ |
| 4258 /* Magic number 1 is the WAL_CKPT_LOCK lock. Preventing SQLite from |
| 4259 ** taking this lock also prevents any checkpoints from occurring. |
| 4260 ** todo: really, it's not clear why this might occur, as |
| 4261 ** wal_autocheckpoint ought to be turned off. */ |
| 4262 if( ofst==WAL_LOCK_CKPT && n==1 ) rc = SQLITE_BUSY; |
| 4263 }else{ |
| 4264 int bCapture = 0; |
| 4265 if( n==1 && (flags & SQLITE_SHM_EXCLUSIVE) |
| 4266 && pRbu && pRbu->eStage==RBU_STAGE_CAPTURE |
| 4267 && (ofst==WAL_LOCK_WRITE || ofst==WAL_LOCK_CKPT || ofst==WAL_LOCK_READ0) |
| 4268 ){ |
| 4269 bCapture = 1; |
| 4270 } |
| 4271 |
| 4272 if( bCapture==0 || 0==(flags & SQLITE_SHM_UNLOCK) ){ |
| 4273 rc = p->pReal->pMethods->xShmLock(p->pReal, ofst, n, flags); |
| 4274 if( bCapture && rc==SQLITE_OK ){ |
| 4275 pRbu->mLock |= (1 << ofst); |
| 4276 } |
| 4277 } |
| 4278 } |
| 4279 |
| 4280 return rc; |
| 4281 } |
| 4282 |
| 4283 /* |
| 4284 ** Obtain a pointer to a mapping of a single 32KiB page of the *-shm file. |
| 4285 */ |
| 4286 static int rbuVfsShmMap( |
| 4287 sqlite3_file *pFile, |
| 4288 int iRegion, |
| 4289 int szRegion, |
| 4290 int isWrite, |
| 4291 void volatile **pp |
| 4292 ){ |
| 4293 rbu_file *p = (rbu_file*)pFile; |
| 4294 int rc = SQLITE_OK; |
| 4295 int eStage = (p->pRbu ? p->pRbu->eStage : 0); |
| 4296 |
| 4297 /* If not in RBU_STAGE_OAL, allow this call to pass through. Or, if this |
| 4298 ** rbu is in the RBU_STAGE_OAL state, use heap memory for *-shm space |
| 4299 ** instead of a file on disk. */ |
| 4300 assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) ); |
| 4301 if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){ |
| 4302 if( iRegion<=p->nShm ){ |
| 4303 int nByte = (iRegion+1) * sizeof(char*); |
| 4304 char **apNew = (char**)sqlite3_realloc64(p->apShm, nByte); |
| 4305 if( apNew==0 ){ |
| 4306 rc = SQLITE_NOMEM; |
| 4307 }else{ |
| 4308 memset(&apNew[p->nShm], 0, sizeof(char*) * (1 + iRegion - p->nShm)); |
| 4309 p->apShm = apNew; |
| 4310 p->nShm = iRegion+1; |
| 4311 } |
| 4312 } |
| 4313 |
| 4314 if( rc==SQLITE_OK && p->apShm[iRegion]==0 ){ |
| 4315 char *pNew = (char*)sqlite3_malloc64(szRegion); |
| 4316 if( pNew==0 ){ |
| 4317 rc = SQLITE_NOMEM; |
| 4318 }else{ |
| 4319 memset(pNew, 0, szRegion); |
| 4320 p->apShm[iRegion] = pNew; |
| 4321 } |
| 4322 } |
| 4323 |
| 4324 if( rc==SQLITE_OK ){ |
| 4325 *pp = p->apShm[iRegion]; |
| 4326 }else{ |
| 4327 *pp = 0; |
| 4328 } |
| 4329 }else{ |
| 4330 assert( p->apShm==0 ); |
| 4331 rc = p->pReal->pMethods->xShmMap(p->pReal, iRegion, szRegion, isWrite, pp); |
| 4332 } |
| 4333 |
| 4334 return rc; |
| 4335 } |
| 4336 |
| 4337 /* |
| 4338 ** Memory barrier. |
| 4339 */ |
| 4340 static void rbuVfsShmBarrier(sqlite3_file *pFile){ |
| 4341 rbu_file *p = (rbu_file *)pFile; |
| 4342 p->pReal->pMethods->xShmBarrier(p->pReal); |
| 4343 } |
| 4344 |
| 4345 /* |
| 4346 ** The xShmUnmap method. |
| 4347 */ |
| 4348 static int rbuVfsShmUnmap(sqlite3_file *pFile, int delFlag){ |
| 4349 rbu_file *p = (rbu_file*)pFile; |
| 4350 int rc = SQLITE_OK; |
| 4351 int eStage = (p->pRbu ? p->pRbu->eStage : 0); |
| 4352 |
| 4353 assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) ); |
| 4354 if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){ |
| 4355 /* no-op */ |
| 4356 }else{ |
| 4357 /* Release the checkpointer and writer locks */ |
| 4358 rbuUnlockShm(p); |
| 4359 rc = p->pReal->pMethods->xShmUnmap(p->pReal, delFlag); |
| 4360 } |
| 4361 return rc; |
| 4362 } |
| 4363 |
| 4364 /* |
| 4365 ** Given that zWal points to a buffer containing a wal file name passed to |
| 4366 ** either the xOpen() or xAccess() VFS method, return a pointer to the |
| 4367 ** file-handle opened by the same database connection on the corresponding |
| 4368 ** database file. |
| 4369 */ |
| 4370 static rbu_file *rbuFindMaindb(rbu_vfs *pRbuVfs, const char *zWal){ |
| 4371 rbu_file *pDb; |
| 4372 sqlite3_mutex_enter(pRbuVfs->mutex); |
| 4373 for(pDb=pRbuVfs->pMain; pDb && pDb->zWal!=zWal; pDb=pDb->pMainNext){} |
| 4374 sqlite3_mutex_leave(pRbuVfs->mutex); |
| 4375 return pDb; |
| 4376 } |
| 4377 |
| 4378 /* |
| 4379 ** A main database named zName has just been opened. The following |
| 4380 ** function returns a pointer to a buffer owned by SQLite that contains |
| 4381 ** the name of the *-wal file this db connection will use. SQLite |
| 4382 ** happens to pass a pointer to this buffer when using xAccess() |
| 4383 ** or xOpen() to operate on the *-wal file. |
| 4384 */ |
| 4385 static const char *rbuMainToWal(const char *zName, int flags){ |
| 4386 int n = (int)strlen(zName); |
| 4387 const char *z = &zName[n]; |
| 4388 if( flags & SQLITE_OPEN_URI ){ |
| 4389 int odd = 0; |
| 4390 while( 1 ){ |
| 4391 if( z[0]==0 ){ |
| 4392 odd = 1 - odd; |
| 4393 if( odd && z[1]==0 ) break; |
| 4394 } |
| 4395 z++; |
| 4396 } |
| 4397 z += 2; |
| 4398 }else{ |
| 4399 while( *z==0 ) z++; |
| 4400 } |
| 4401 z += (n + 8 + 1); |
| 4402 return z; |
| 4403 } |
| 4404 |
| 4405 /* |
| 4406 ** Open an rbu file handle. |
| 4407 */ |
| 4408 static int rbuVfsOpen( |
| 4409 sqlite3_vfs *pVfs, |
| 4410 const char *zName, |
| 4411 sqlite3_file *pFile, |
| 4412 int flags, |
| 4413 int *pOutFlags |
| 4414 ){ |
| 4415 static sqlite3_io_methods rbuvfs_io_methods = { |
| 4416 2, /* iVersion */ |
| 4417 rbuVfsClose, /* xClose */ |
| 4418 rbuVfsRead, /* xRead */ |
| 4419 rbuVfsWrite, /* xWrite */ |
| 4420 rbuVfsTruncate, /* xTruncate */ |
| 4421 rbuVfsSync, /* xSync */ |
| 4422 rbuVfsFileSize, /* xFileSize */ |
| 4423 rbuVfsLock, /* xLock */ |
| 4424 rbuVfsUnlock, /* xUnlock */ |
| 4425 rbuVfsCheckReservedLock, /* xCheckReservedLock */ |
| 4426 rbuVfsFileControl, /* xFileControl */ |
| 4427 rbuVfsSectorSize, /* xSectorSize */ |
| 4428 rbuVfsDeviceCharacteristics, /* xDeviceCharacteristics */ |
| 4429 rbuVfsShmMap, /* xShmMap */ |
| 4430 rbuVfsShmLock, /* xShmLock */ |
| 4431 rbuVfsShmBarrier, /* xShmBarrier */ |
| 4432 rbuVfsShmUnmap, /* xShmUnmap */ |
| 4433 0, 0 /* xFetch, xUnfetch */ |
| 4434 }; |
| 4435 rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs; |
| 4436 sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs; |
| 4437 rbu_file *pFd = (rbu_file *)pFile; |
| 4438 int rc = SQLITE_OK; |
| 4439 const char *zOpen = zName; |
| 4440 int oflags = flags; |
| 4441 |
| 4442 memset(pFd, 0, sizeof(rbu_file)); |
| 4443 pFd->pReal = (sqlite3_file*)&pFd[1]; |
| 4444 pFd->pRbuVfs = pRbuVfs; |
| 4445 pFd->openFlags = flags; |
| 4446 if( zName ){ |
| 4447 if( flags & SQLITE_OPEN_MAIN_DB ){ |
| 4448 /* A main database has just been opened. The following block sets |
| 4449 ** (pFd->zWal) to point to a buffer owned by SQLite that contains |
| 4450 ** the name of the *-wal file this db connection will use. SQLite |
| 4451 ** happens to pass a pointer to this buffer when using xAccess() |
| 4452 ** or xOpen() to operate on the *-wal file. */ |
| 4453 pFd->zWal = rbuMainToWal(zName, flags); |
| 4454 } |
| 4455 else if( flags & SQLITE_OPEN_WAL ){ |
| 4456 rbu_file *pDb = rbuFindMaindb(pRbuVfs, zName); |
| 4457 if( pDb ){ |
| 4458 if( pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){ |
| 4459 /* This call is to open a *-wal file. Intead, open the *-oal. This |
| 4460 ** code ensures that the string passed to xOpen() is terminated by a |
| 4461 ** pair of '\0' bytes in case the VFS attempts to extract a URI |
| 4462 ** parameter from it. */ |
| 4463 const char *zBase = zName; |
| 4464 size_t nCopy; |
| 4465 char *zCopy; |
| 4466 if( rbuIsVacuum(pDb->pRbu) ){ |
| 4467 zBase = sqlite3_db_filename(pDb->pRbu->dbRbu, "main"); |
| 4468 zBase = rbuMainToWal(zBase, SQLITE_OPEN_URI); |
| 4469 } |
| 4470 nCopy = strlen(zBase); |
| 4471 zCopy = sqlite3_malloc64(nCopy+2); |
| 4472 if( zCopy ){ |
| 4473 memcpy(zCopy, zBase, nCopy); |
| 4474 zCopy[nCopy-3] = 'o'; |
| 4475 zCopy[nCopy] = '\0'; |
| 4476 zCopy[nCopy+1] = '\0'; |
| 4477 zOpen = (const char*)(pFd->zDel = zCopy); |
| 4478 }else{ |
| 4479 rc = SQLITE_NOMEM; |
| 4480 } |
| 4481 pFd->pRbu = pDb->pRbu; |
| 4482 } |
| 4483 pDb->pWalFd = pFd; |
| 4484 } |
| 4485 } |
| 4486 } |
| 4487 |
| 4488 if( oflags & SQLITE_OPEN_MAIN_DB |
| 4489 && sqlite3_uri_boolean(zName, "rbu_memory", 0) |
| 4490 ){ |
| 4491 assert( oflags & SQLITE_OPEN_MAIN_DB ); |
| 4492 oflags = SQLITE_OPEN_TEMP_DB | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | |
| 4493 SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE; |
| 4494 zOpen = 0; |
| 4495 } |
| 4496 |
| 4497 if( rc==SQLITE_OK ){ |
| 4498 rc = pRealVfs->xOpen(pRealVfs, zOpen, pFd->pReal, oflags, pOutFlags); |
| 4499 } |
| 4500 if( pFd->pReal->pMethods ){ |
| 4501 /* The xOpen() operation has succeeded. Set the sqlite3_file.pMethods |
| 4502 ** pointer and, if the file is a main database file, link it into the |
| 4503 ** mutex protected linked list of all such files. */ |
| 4504 pFile->pMethods = &rbuvfs_io_methods; |
| 4505 if( flags & SQLITE_OPEN_MAIN_DB ){ |
| 4506 sqlite3_mutex_enter(pRbuVfs->mutex); |
| 4507 pFd->pMainNext = pRbuVfs->pMain; |
| 4508 pRbuVfs->pMain = pFd; |
| 4509 sqlite3_mutex_leave(pRbuVfs->mutex); |
| 4510 } |
| 4511 }else{ |
| 4512 sqlite3_free(pFd->zDel); |
| 4513 } |
| 4514 |
| 4515 return rc; |
| 4516 } |
| 4517 |
| 4518 /* |
| 4519 ** Delete the file located at zPath. |
| 4520 */ |
| 4521 static int rbuVfsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){ |
| 4522 sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs; |
| 4523 return pRealVfs->xDelete(pRealVfs, zPath, dirSync); |
| 4524 } |
| 4525 |
| 4526 /* |
| 4527 ** Test for access permissions. Return true if the requested permission |
| 4528 ** is available, or false otherwise. |
| 4529 */ |
| 4530 static int rbuVfsAccess( |
| 4531 sqlite3_vfs *pVfs, |
| 4532 const char *zPath, |
| 4533 int flags, |
| 4534 int *pResOut |
| 4535 ){ |
| 4536 rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs; |
| 4537 sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs; |
| 4538 int rc; |
| 4539 |
| 4540 rc = pRealVfs->xAccess(pRealVfs, zPath, flags, pResOut); |
| 4541 |
| 4542 /* If this call is to check if a *-wal file associated with an RBU target |
| 4543 ** database connection exists, and the RBU update is in RBU_STAGE_OAL, |
| 4544 ** the following special handling is activated: |
| 4545 ** |
| 4546 ** a) if the *-wal file does exist, return SQLITE_CANTOPEN. This |
| 4547 ** ensures that the RBU extension never tries to update a database |
| 4548 ** in wal mode, even if the first page of the database file has |
| 4549 ** been damaged. |
| 4550 ** |
| 4551 ** b) if the *-wal file does not exist, claim that it does anyway, |
| 4552 ** causing SQLite to call xOpen() to open it. This call will also |
| 4553 ** be intercepted (see the rbuVfsOpen() function) and the *-oal |
| 4554 ** file opened instead. |
| 4555 */ |
| 4556 if( rc==SQLITE_OK && flags==SQLITE_ACCESS_EXISTS ){ |
| 4557 rbu_file *pDb = rbuFindMaindb(pRbuVfs, zPath); |
| 4558 if( pDb && pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){ |
| 4559 if( *pResOut ){ |
| 4560 rc = SQLITE_CANTOPEN; |
| 4561 }else{ |
| 4562 *pResOut = 1; |
| 4563 } |
| 4564 } |
| 4565 } |
| 4566 |
| 4567 return rc; |
| 4568 } |
| 4569 |
| 4570 /* |
| 4571 ** Populate buffer zOut with the full canonical pathname corresponding |
| 4572 ** to the pathname in zPath. zOut is guaranteed to point to a buffer |
| 4573 ** of at least (DEVSYM_MAX_PATHNAME+1) bytes. |
| 4574 */ |
| 4575 static int rbuVfsFullPathname( |
| 4576 sqlite3_vfs *pVfs, |
| 4577 const char *zPath, |
| 4578 int nOut, |
| 4579 char *zOut |
| 4580 ){ |
| 4581 sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs; |
| 4582 return pRealVfs->xFullPathname(pRealVfs, zPath, nOut, zOut); |
| 4583 } |
| 4584 |
| 4585 #ifndef SQLITE_OMIT_LOAD_EXTENSION |
| 4586 /* |
| 4587 ** Open the dynamic library located at zPath and return a handle. |
| 4588 */ |
| 4589 static void *rbuVfsDlOpen(sqlite3_vfs *pVfs, const char *zPath){ |
| 4590 sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs; |
| 4591 return pRealVfs->xDlOpen(pRealVfs, zPath); |
| 4592 } |
| 4593 |
| 4594 /* |
| 4595 ** Populate the buffer zErrMsg (size nByte bytes) with a human readable |
| 4596 ** utf-8 string describing the most recent error encountered associated |
| 4597 ** with dynamic libraries. |
| 4598 */ |
| 4599 static void rbuVfsDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){ |
| 4600 sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs; |
| 4601 pRealVfs->xDlError(pRealVfs, nByte, zErrMsg); |
| 4602 } |
| 4603 |
| 4604 /* |
| 4605 ** Return a pointer to the symbol zSymbol in the dynamic library pHandle. |
| 4606 */ |
| 4607 static void (*rbuVfsDlSym( |
| 4608 sqlite3_vfs *pVfs, |
| 4609 void *pArg, |
| 4610 const char *zSym |
| 4611 ))(void){ |
| 4612 sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs; |
| 4613 return pRealVfs->xDlSym(pRealVfs, pArg, zSym); |
| 4614 } |
| 4615 |
| 4616 /* |
| 4617 ** Close the dynamic library handle pHandle. |
| 4618 */ |
| 4619 static void rbuVfsDlClose(sqlite3_vfs *pVfs, void *pHandle){ |
| 4620 sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs; |
| 4621 pRealVfs->xDlClose(pRealVfs, pHandle); |
| 4622 } |
| 4623 #endif /* SQLITE_OMIT_LOAD_EXTENSION */ |
| 4624 |
| 4625 /* |
| 4626 ** Populate the buffer pointed to by zBufOut with nByte bytes of |
| 4627 ** random data. |
| 4628 */ |
| 4629 static int rbuVfsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){ |
| 4630 sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs; |
| 4631 return pRealVfs->xRandomness(pRealVfs, nByte, zBufOut); |
| 4632 } |
| 4633 |
| 4634 /* |
| 4635 ** Sleep for nMicro microseconds. Return the number of microseconds |
| 4636 ** actually slept. |
| 4637 */ |
| 4638 static int rbuVfsSleep(sqlite3_vfs *pVfs, int nMicro){ |
| 4639 sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs; |
| 4640 return pRealVfs->xSleep(pRealVfs, nMicro); |
| 4641 } |
| 4642 |
| 4643 /* |
| 4644 ** Return the current time as a Julian Day number in *pTimeOut. |
| 4645 */ |
| 4646 static int rbuVfsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){ |
| 4647 sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs; |
| 4648 return pRealVfs->xCurrentTime(pRealVfs, pTimeOut); |
| 4649 } |
| 4650 |
| 4651 /* |
| 4652 ** No-op. |
| 4653 */ |
| 4654 static int rbuVfsGetLastError(sqlite3_vfs *pVfs, int a, char *b){ |
| 4655 return 0; |
| 4656 } |
| 4657 |
| 4658 /* |
| 4659 ** Deregister and destroy an RBU vfs created by an earlier call to |
| 4660 ** sqlite3rbu_create_vfs(). |
| 4661 */ |
| 4662 void sqlite3rbu_destroy_vfs(const char *zName){ |
| 4663 sqlite3_vfs *pVfs = sqlite3_vfs_find(zName); |
| 4664 if( pVfs && pVfs->xOpen==rbuVfsOpen ){ |
| 4665 sqlite3_mutex_free(((rbu_vfs*)pVfs)->mutex); |
| 4666 sqlite3_vfs_unregister(pVfs); |
| 4667 sqlite3_free(pVfs); |
| 4668 } |
| 4669 } |
| 4670 |
| 4671 /* |
| 4672 ** Create an RBU VFS named zName that accesses the underlying file-system |
| 4673 ** via existing VFS zParent. The new object is registered as a non-default |
| 4674 ** VFS with SQLite before returning. |
| 4675 */ |
| 4676 int sqlite3rbu_create_vfs(const char *zName, const char *zParent){ |
| 4677 |
| 4678 /* Template for VFS */ |
| 4679 static sqlite3_vfs vfs_template = { |
| 4680 1, /* iVersion */ |
| 4681 0, /* szOsFile */ |
| 4682 0, /* mxPathname */ |
| 4683 0, /* pNext */ |
| 4684 0, /* zName */ |
| 4685 0, /* pAppData */ |
| 4686 rbuVfsOpen, /* xOpen */ |
| 4687 rbuVfsDelete, /* xDelete */ |
| 4688 rbuVfsAccess, /* xAccess */ |
| 4689 rbuVfsFullPathname, /* xFullPathname */ |
| 4690 |
| 4691 #ifndef SQLITE_OMIT_LOAD_EXTENSION |
| 4692 rbuVfsDlOpen, /* xDlOpen */ |
| 4693 rbuVfsDlError, /* xDlError */ |
| 4694 rbuVfsDlSym, /* xDlSym */ |
| 4695 rbuVfsDlClose, /* xDlClose */ |
| 4696 #else |
| 4697 0, 0, 0, 0, |
| 4698 #endif |
| 4699 |
| 4700 rbuVfsRandomness, /* xRandomness */ |
| 4701 rbuVfsSleep, /* xSleep */ |
| 4702 rbuVfsCurrentTime, /* xCurrentTime */ |
| 4703 rbuVfsGetLastError, /* xGetLastError */ |
| 4704 0, /* xCurrentTimeInt64 (version 2) */ |
| 4705 0, 0, 0 /* Unimplemented version 3 methods */ |
| 4706 }; |
| 4707 |
| 4708 rbu_vfs *pNew = 0; /* Newly allocated VFS */ |
| 4709 int rc = SQLITE_OK; |
| 4710 size_t nName; |
| 4711 size_t nByte; |
| 4712 |
| 4713 nName = strlen(zName); |
| 4714 nByte = sizeof(rbu_vfs) + nName + 1; |
| 4715 pNew = (rbu_vfs*)sqlite3_malloc64(nByte); |
| 4716 if( pNew==0 ){ |
| 4717 rc = SQLITE_NOMEM; |
| 4718 }else{ |
| 4719 sqlite3_vfs *pParent; /* Parent VFS */ |
| 4720 memset(pNew, 0, nByte); |
| 4721 pParent = sqlite3_vfs_find(zParent); |
| 4722 if( pParent==0 ){ |
| 4723 rc = SQLITE_NOTFOUND; |
| 4724 }else{ |
| 4725 char *zSpace; |
| 4726 memcpy(&pNew->base, &vfs_template, sizeof(sqlite3_vfs)); |
| 4727 pNew->base.mxPathname = pParent->mxPathname; |
| 4728 pNew->base.szOsFile = sizeof(rbu_file) + pParent->szOsFile; |
| 4729 pNew->pRealVfs = pParent; |
| 4730 pNew->base.zName = (const char*)(zSpace = (char*)&pNew[1]); |
| 4731 memcpy(zSpace, zName, nName); |
| 4732 |
| 4733 /* Allocate the mutex and register the new VFS (not as the default) */ |
| 4734 pNew->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_RECURSIVE); |
| 4735 if( pNew->mutex==0 ){ |
| 4736 rc = SQLITE_NOMEM; |
| 4737 }else{ |
| 4738 rc = sqlite3_vfs_register(&pNew->base, 0); |
| 4739 } |
| 4740 } |
| 4741 |
| 4742 if( rc!=SQLITE_OK ){ |
| 4743 sqlite3_mutex_free(pNew->mutex); |
| 4744 sqlite3_free(pNew); |
| 4745 } |
| 4746 } |
| 4747 |
| 4748 return rc; |
| 4749 } |
| 4750 |
| 4751 |
| 4752 /**************************************************************************/ |
| 4753 |
| 4754 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU) */ |
OLD | NEW |