Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/sqlite/blob/master/ext/rbu/sqlite3rbu.c # sqlite [Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `master` Branches Tags History `sqlite / ext / rbu / sqlite3rbu.c` 5511 lines ยท 177920 bytes Raw Blame History 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 "-oal" instead of "-wal". 28 ** Because regular SQLite clients do not look for file named 29 ** "-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 "-oal" file is moved to the equivalent "-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 84 #include 85 #include 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 /* Delta checksums disabled by default. Compile with -DRBU_ENABLE_DELTA_CKSUM 100 ** to enable checksum verification. 101 */ 102 #ifndef RBU_ENABLE_DELTA_CKSUM 103 # define RBU_ENABLE_DELTA_CKSUM 0 104 #endif 105 106 /* 107 ** Swap two objects of type TYPE. 108 */ 109 #if !defined(SQLITE_AMALGAMATION) 110 # define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;} 111 #endif 112 113 /* 114 ** Name of the URI option that causes RBU to take an exclusive lock as 115 ** part of the incremental checkpoint operation. 116 */ 117 #define RBU_EXCLUSIVE_CHECKPOINT "rbu_exclusive_checkpoint" 118 119 120 /* 121 ** The rbu_state table is used to save the state of a partially applied 122 ** update so that it can be resumed later. The table consists of integer 123 ** keys mapped to values as follows: 124 ** 125 ** RBU_STATE_STAGE: 126 ** May be set to integer values 1, 2, 4 or 5. As follows: 127 ** 1: the *-rbu file is currently under construction. 128 ** 2: the *-rbu file has been constructed, but not yet moved 129 ** to the *-wal path. 130 ** 4: the checkpoint is underway. 131 ** 5: the rbu update has been checkpointed. 132 ** 133 ** RBU_STATE_TBL: 134 ** Only valid if STAGE==1. The target database name of the table 135 ** currently being written. 136 ** 137 ** RBU_STATE_IDX: 138 ** Only valid if STAGE==1. The target database name of the index 139 ** currently being written, or NULL if the main table is currently being 140 ** updated. 141 ** 142 ** RBU_STATE_ROW: 143 ** Only valid if STAGE==1. Number of rows already processed for the current 144 ** table/index. 145 ** 146 ** RBU_STATE_PROGRESS: 147 ** Trbul number of sqlite3rbu_step() calls made so far as part of this 148 ** rbu update. 149 ** 150 ** RBU_STATE_CKPT: 151 ** Valid if STAGE==4. The 64-bit checksum associated with the wal-index 152 ** header created by recovering the *-wal file. This is used to detect 153 ** cases when another client appends frames to the *-wal file in the 154 ** middle of an incremental checkpoint (an incremental checkpoint cannot 155 ** be continued if this happens). 156 ** 157 ** RBU_STATE_COOKIE: 158 ** Valid if STAGE==1. The current change-counter cookie value in the 159 ** target db file. 160 ** 161 ** RBU_STATE_OALSZ: 162 ** Valid if STAGE==1. The size in bytes of the *-oal file. 163 ** 164 ** RBU_STATE_DATATBL: 165 ** Only valid if STAGE==1. The RBU database name of the table 166 ** currently being read. 167 */ 168 #define RBU_STATE_STAGE 1 169 #define RBU_STATE_TBL 2 170 #define RBU_STATE_IDX 3 171 #define RBU_STATE_ROW 4 172 #define RBU_STATE_PROGRESS 5 173 #define RBU_STATE_CKPT 6 174 #define RBU_STATE_COOKIE 7 175 #define RBU_STATE_OALSZ 8 176 #define RBU_STATE_PHASEONESTEP 9 177 #define RBU_STATE_DATATBL 10 178 179 #define RBU_STAGE_OAL 1 180 #define RBU_STAGE_MOVE 2 181 #define RBU_STAGE_CAPTURE 3 182 #define RBU_STAGE_CKPT 4 183 #define RBU_STAGE_DONE 5 184 185 186 #define RBU_CREATE_STATE \ 187 "CREATE TABLE IF NOT EXISTS %s.rbu_state(k INTEGER PRIMARY KEY, v)" 188 189 typedef struct RbuFrame RbuFrame; 190 typedef struct RbuObjIter RbuObjIter; 191 typedef struct RbuState RbuState; 192 typedef struct RbuSpan RbuSpan; 193 typedef struct rbu_vfs rbu_vfs; 194 typedef struct rbu_file rbu_file; 195 typedef struct RbuUpdateStmt RbuUpdateStmt; 196 197 #if !defined(SQLITE_AMALGAMATION) 198 typedef unsigned int u32; 199 typedef unsigned short u16; 200 typedef unsigned char u8; 201 typedef sqlite3_int64 i64; 202 typedef sqlite3_uint64 u64; 203 #endif 204 205 /* 206 ** These values must match the values defined in wal.c for the equivalent 207 ** locks. These are not magic numbers as they are part of the SQLite file 208 ** format. 209 */ 210 #define WAL_LOCK_WRITE 0 211 #define WAL_LOCK_CKPT 1 212 #define WAL_LOCK_READ0 3 213 214 #define SQLITE_FCNTL_RBUCNT `5149216` 215 216 /* 217 ** A structure to store values read from the rbu_state table in memory. 218 */ 219 struct RbuState { 220 int eStage; 221 char *zTbl; 222 char *zDataTbl; 223 char *zIdx; 224 i64 iWalCksum; 225 int nRow; 226 i64 nProgress; 227 u32 iCookie; 228 i64 iOalSz; 229 i64 nPhaseOneStep; 230 }; 231 232 struct RbuUpdateStmt { 233 char *zMask; /* Copy of update mask used with pUpdate */ 234 sqlite3_stmt *pUpdate; /* Last update statement (or NULL) */ 235 RbuUpdateStmt *pNext; 236 }; 237 238 struct RbuSpan { 239 const char *zSpan; 240 int nSpan; 241 }; 242 243 /* 244 ** An iterator of this type is used to iterate through all objects in 245 ** the target database that require updating. For each such table, the 246 ** iterator visits, in order: 247 ** 248 ** * the table itself, 249 ** * each index of the table (zero or more points to visit), and 250 ** * a special "cleanup table" state. 251 ** 252 ** abIndexed: 253 ** If the table has no indexes on it, abIndexed is set to NULL. Otherwise, 254 ** it points to an array of flags nTblCol elements in size. The flag is 255 ** set for each column that is either a part of the PK or a part of an 256 ** index. Or clear otherwise. 257 ** 258 ** If there are one or more partial indexes on the table, all fields of 259 ** this array set set to 1. This is because in that case, the module has 260 ** no way to tell which fields will be required to add and remove entries 261 ** from the partial indexes. 262 ** 263 */ 264 struct RbuObjIter { 265 sqlite3_stmt *pTblIter; /* Iterate through tables */ 266 sqlite3_stmt *pIdxIter; /* Index iterator */ 267 int nTblCol; /* Size of azTblCol[] array */ 268 char **azTblCol; /* Array of unquoted target column names */ 269 char **azTblType; /* Array of target column types */ 270 char **azTblDflt; /* Array of target column DEFAULT exprs */ 271 int *aiSrcOrder; /* src table col -> target table col */ 272 u8 *abTblPk; /* Array of flags, set on target PK columns */ 273 u8 *abNotNull; /* Array of flags, set on NOT NULL columns */ 274 u8 *abIndexed; /* Array of flags, set on indexed & PK cols */ 275 int eType; /* Table type - an RBU_PK_XXX value */ 276 277 /* Output variables. zTbl==0 implies EOF. */ 278 int bCleanup; /* True in "cleanup" state */ 279 const char *zTbl; /* Name of target db table */ 280 const char *zDataTbl; /* Name of rbu db table (or null) */ 281 const char *zIdx; /* Name of target db index (or null) */ 282 int iTnum; /* Root page of current object */ 283 int iPkTnum; /* If eType==EXTERNAL, root of PK index */ 284 int bUnique; /* Current index is unique */ 285 int nIndex; /* Number of aux. indexes on table zTbl */ 286 287 /* Statements created by rbuObjIterPrepareAll() */ 288 int nCol; /* Number of columns in current object */ 289 sqlite3_stmt *pSelect; /* Source data */ 290 sqlite3_stmt *pInsert; /* Statement for INSERT operations */ 291 sqlite3_stmt *pDelete; /* Statement for DELETE ops */ 292 sqlite3_stmt *pTmpInsert; /* Insert into rbu_tmp_$zDataTbl */ 293 int nIdxCol; 294 RbuSpan *aIdxCol; 295 char *zIdxSql; 296 297 /* Last UPDATE used (for PK b-tree updates only), or NULL. */ 298 RbuUpdateStmt *pRbuUpdate; 299 }; 300 301 /* 302 ** Values for RbuObjIter.eType 303 ** 304 ** 0: Table does not exist (error) 305 ** 1: Table has an implicit rowid. 306 ** 2: Table has an explicit IPK column. 307 ** 3: Table has an external PK index. 308 ** 4: Table is WITHOUT ROWID. 309 ** 5: Table is a virtual table. 310 */ 311 #define RBU_PK_NOTABLE 0 312 #define RBU_PK_NONE 1 313 #define RBU_PK_IPK 2 314 #define RBU_PK_EXTERNAL 3 315 #define RBU_PK_WITHOUT_ROWID 4 316 #define RBU_PK_VTAB 5 317 318 319 /* 320 ** Within the RBU_STAGE_OAL stage, each call to sqlite3rbu_step() performs 321 ** one of the following operations. 322 */ 323 #define RBU_INSERT 1 /* Insert on a main table b-tree */ 324 #define RBU_DELETE 2 /* Delete a row from a main table b-tree */ 325 #define RBU_REPLACE 3 /* Delete and then insert a row */ 326 #define RBU_IDX_DELETE 4 /* Delete a row from an aux. index b-tree */ 327 #define RBU_IDX_INSERT 5 /* Insert on an aux. index b-tree */ 328 329 #define RBU_UPDATE 6 /* Update a row in a main table b-tree */ 330 331 /* 332 ** A single step of an incremental checkpoint - frame iWalFrame of the wal 333 ** file should be copied to page iDbPage of the database file. 334 */ 335 struct RbuFrame { 336 u32 iDbPage; 337 u32 iWalFrame; 338 }; 339 340 #ifndef UNUSED_PARAMETER 341 /* 342 ** The following macros are used to suppress compiler warnings and to 343 ** make it clear to human readers when a function parameter is deliberately 344 ** left unused within the body of a function. This usually happens when 345 ** a function is called via a function pointer. For example the 346 ** implementation of an SQL aggregate step callback may not use the 347 ** parameter indicating the number of arguments passed to the aggregate, 348 ** if it knows that this is enforced elsewhere. 349 ** 350 ** When a function parameter is not used at all within the body of a function, 351 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer. 352 ** However, these macros may also be used to suppress warnings related to 353 ** parameters that may or may not be used depending on compilation options. 354 ** For example those parameters only used in assert() statements. In these 355 ** cases the parameters are named as per the usual conventions. 356 */ 357 #define UNUSED_PARAMETER(x) (void)(x) 358 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y) 359 #endif 360 361 /* 362 ** RBU handle. 363 ** 364 ** nPhaseOneStep: 365 ** If the RBU database contains an rbu_count table, this value is set to 366 ** a running estimate of the number of b-tree operations required to 367 ** finish populating the *-oal file. This allows the sqlite3_bp_progress() 368 ** API to calculate the permyriadage progress of populating the *-oal file 369 ** using the formula: 370 ** 371 ** permyriadage = (10000 * nProgress) / nPhaseOneStep 372 ** 373 ** nPhaseOneStep is initialized to the sum of: 374 ** 375 ** nRow * (nIndex + 1) 376 ** 377 ** for all source tables in the RBU database, where nRow is the number 378 ** of rows in the source table and nIndex the number of indexes on the 379 ** corresponding target database table. 380 ** 381 ** This estimate is accurate if the RBU update consists entirely of 382 ** INSERT operations. However, it is inaccurate if: 383 ** 384 ** * the RBU update contains any UPDATE operations. If the PK specified 385 ** for an UPDATE operation does not exist in the target table, then 386 ** no b-tree operations are required on index b-trees. Or if the 387 ** specified PK does exist, then (nIndex*2) such operations are 388 ** required (one delete and one insert on each index b-tree). 389 ** 390 ** * the RBU update contains any DELETE operations for which the specified 391 ** PK does not exist. In this case no operations are required on index 392 ** b-trees. 393 ** 394 ** * the RBU update contains REPLACE operations. These are similar to 395 ** UPDATE operations. 396 ** 397 ** nPhaseOneStep is updated to account for the conditions above during the 398 ** first pass of each source table. The updated nPhaseOneStep value is 399 ** stored in the rbu_state table if the RBU update is suspended. 400 */ 401 struct sqlite3rbu { 402 int eStage; /* Value of RBU_STATE_STAGE field */ 403 sqlite3 *dbMain; /* target database handle */ 404 sqlite3 *dbRbu; /* rbu database handle */ 405 char *zTarget; /* Path to target db */ 406 char *zRbu; /* Path to rbu db */ 407 char *zState; /* Path to state db (or NULL if zRbu) */ 408 char zStateDb[5]; /* Db name for state ("stat" or "main") */ 409 int rc; /* Value returned by last rbu_step() call */ 410 char *zErrmsg; /* Error message if rc!=SQLITE_OK */ 411 int nStep; /* Rows processed for current object */ 412 sqlite3_int64 nProgress; /* Rows processed for all objects */ 413 RbuObjIter objiter; /* Iterator for skipping through tbl/idx */ 414 const char *zVfsName; /* Name of automatically created rbu vfs */ 415 rbu_file *pTargetFd; /* File handle open on target db */ 416 int nPagePerSector; /* Pages per sector for pTargetFd */ 417 i64 iOalSz; 418 i64 nPhaseOneStep; 419 void *pRenameArg; 420 int (*xRename)(void*, const char*, const char*); 421 422 /* The following state variables are used as part of the incremental 423 ** checkpoint stage (eStage==RBU_STAGE_CKPT). See comments surrounding 424 ** function rbuSetupCheckpoint() for details. */ 425 u32 iMaxFrame; /* Largest iWalFrame value in aFrame[] */ 426 u32 mLock; 427 int nFrame; /* Entries in aFrame[] array */ 428 int nFrameAlloc; /* Allocated size of aFrame[] array */ 429 RbuFrame *aFrame; 430 int pgsz; 431 u8 *aBuf; 432 i64 iWalCksum; 433 i64 szTemp; /* Current size of all temp files in use */ 434 i64 szTempLimit; /* Total size limit for temp files */ 435 436 /* Used in RBU vacuum mode only */ 437 int nRbu; /* Number of RBU VFS in the stack */ 438 rbu_file *pRbuFd; /* Fd for main db of dbRbu */ 439 }; 440 441 /* 442 ** An rbu VFS is implemented using an instance of this structure. 443 ** 444 ** Variable pRbu is only non-NULL for automatically created RBU VFS objects. 445 ** It is NULL for RBU VFS objects created explicitly using 446 ** sqlite3rbu_create_vfs(). It is used to track the total amount of temp 447 ** space used by the RBU handle. 448 */ 449 struct rbu_vfs { 450 sqlite3_vfs base; /* rbu VFS shim methods */ 451 sqlite3_vfs *pRealVfs; /* Underlying VFS */ 452 sqlite3_mutex *mutex; /* Mutex to protect pMain */ 453 sqlite3rbu *pRbu; /* Owner RBU object */ 454 rbu_file *pMain; /* List of main db files */ 455 rbu_file *pMainRbu; /* List of main db files with pRbu!=0 */ 456 }; 457 458 /* 459 ** Each file opened by an rbu VFS is represented by an instance of 460 ** the following structure. 461 ** 462 ** If this is a temporary file (pRbu!=0 && flags&DELETE_ON_CLOSE), variable 463 ** "sz" is set to the current size of the database file. 464 */ 465 struct rbu_file { 466 sqlite3_file base; /* sqlite3_file methods */ 467 sqlite3_file *pReal; /* Underlying file handle */ 468 rbu_vfs *pRbuVfs; /* Pointer to the rbu_vfs object */ 469 sqlite3rbu *pRbu; /* Pointer to rbu object (rbu target only) */ 470 i64 sz; /* Size of file in bytes (temp only) */ 471 472 int openFlags; /* Flags this file was opened with */ 473 u32 iCookie; /* Cookie value for main db files */ 474 u8 iWriteVer; /* "write-version" value for main db files */ 475 u8 bNolock; /* True to fail EXCLUSIVE locks */ 476 477 int nShm; /* Number of entries in apShm[] array */ 478 char **apShm; /* Array of mmap'd *-shm regions */ 479 char *zDel; /* Delete this when closing file */ 480 481 const char *zWal; /* Wal filename for this main db file */ 482 rbu_file *pWalFd; /* Wal file descriptor for this main db */ 483 rbu_file *pMainNext; /* Next MAIN_DB file */ 484 rbu_file *pMainRbuNext; /* Next MAIN_DB file with pRbu!=0 */ 485 }; 486 487 /* 488 ** True for an RBU vacuum handle, or false otherwise. 489 */ 490 #define rbuIsVacuum(p) ((p)->zTarget==0) 491 492 493 /************************************************************************* 494 ** The following three functions, found below: 495 ** 496 ** rbuDeltaGetInt() 497 ** rbuDeltaChecksum() 498 ** rbuDeltaApply() 499 ** 500 ** are lifted from the fossil source code (http://fossil-scm.org). They 501 ** are used to implement the scalar SQL function rbu_fossil_delta(). 502 */ 503 504 /* 505 ** Read bytes from *pz and convert them into a positive integer. When 506 ** finished, leave *pz pointing to the first character past the end of 507 ** the integer. The *pLen parameter holds the length of the string 508 ** in *pz and is decremented once for each character in the integer. 509 */ 510 static unsigned int rbuDeltaGetInt(const char **pz, int *pLen){ 511 static const signed char zValue[] = { 512 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 513 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 514 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 515 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, 516 -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 517 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, 36, 518 -1, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 519 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, -1, -1, -1, 63, -1, 520 521 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 522 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 523 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 524 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 525 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 526 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 527 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 528 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 529 }; 530 unsigned int v = 0; 531 int c; 532 unsigned char *z = (unsigned char*)*pz; 533 unsigned char *zEnd = z + (*pLen); 534 while( z=0 ){ 535 v = (v<<6) + c; 536 z++; 537 } 538 539 *pLen -= (int)(z - (unsigned char*)*pz); 540 *pz = (char*)z; 541 return v; 542 } 543 544 #if RBU_ENABLE_DELTA_CKSUM 545 /* 546 ** Compute a 32-bit checksum on the N-byte buffer. Return the result. 547 */ 548 static unsigned int rbuDeltaChecksum(const char *zIn, size_t N){ 549 const unsigned char *z = (const unsigned char *)zIn; 550 unsigned sum0 = 0; 551 unsigned sum1 = 0; 552 unsigned sum2 = 0; 553 unsigned sum3 = 0; 554 while(N >= 16){ 555 sum0 += ((unsigned)z[0] + z[4] + z[8] + z[12]); 556 sum1 += ((unsigned)z[1] + z[5] + z[9] + z[13]); 557 sum2 += ((unsigned)z[2] + z[6] + z[10]+ z[14]); 558 sum3 += ((unsigned)z[3] + z[7] + z[11]+ z[15]); 559 z += 16; 560 N -= 16; 561 } 562 while(N >= 4){ 563 sum0 += z[0]; 564 sum1 += z[1]; 565 sum2 += z[2]; 566 sum3 += z[3]; 567 z += 4; 568 N -= 4; 569 } 570 sum3 += (sum2 << 8) + (sum1 << 16) + (sum0 << 24); 571 switch(N){ 572 case 3: sum3 += (z[2] << 8); 573 case 2: sum3 += (z[1] << 16); 574 case 1: sum3 += (z[0] << 24); 575 default: ; 576 } 577 return sum3; 578 } 579 #endif 580 581 /* 582 ** Apply a delta. 583 ** 584 ** The output buffer should be big enough to hold the whole output 585 ** file and a NUL terminator at the end. The delta_output_size() 586 ** routine will determine this size for you. 587 ** 588 ** The delta string should be null-terminated. But the delta string 589 ** may contain embedded NUL characters (if the input and output are 590 ** binary files) so we also have to pass in the length of the delta in 591 ** the lenDelta parameter. 592 ** 593 ** This function returns the size of the output file in bytes (excluding 594 ** the final NUL terminator character). Except, if the delta string is 595 ** malformed or intended for use with a source file other than zSrc, 596 ** then this routine returns -1. 597 ** 598 ** Refer to the delta_create() documentation above for a description 599 ** of the delta file format. 600 */ 601 static int rbuDeltaApply( 602 const char *zSrc, /* The source or pattern file */ 603 int lenSrc, /* Length of the source file */ 604 const char *zDelta, /* Delta to apply to the pattern */ 605 int lenDelta, /* Length of the delta */ 606 char *zOut /* Write the output into this preallocated buffer */ 607 ){ 608 sqlite3_uint64 limit; 609 sqlite3_uint64 total = 0; 610 #if RBU_ENABLE_DELTA_CKSUM 611 char *zOrigOut = zOut; 612 #endif 613 614 limit = rbuDeltaGetInt(&zDelta, &lenDelta); 615 if( lenDelta<=0 || *zDelta!='\n' ){ 616 /* ERROR: size integer not terminated by "\n" */ 617 return -1; 618 } 619 zDelta++; lenDelta--; /* Skip the \n */ 620 while( lenDelta>0 && zDelta[0] ){ 621 unsigned int cnt, ofst; 622 cnt = rbuDeltaGetInt(&zDelta, &lenDelta); 623 if( lenDelta<=0 ) return -1; 624 switch( zDelta[0] ){ 625 case '@': { 626 zDelta++; lenDelta--; 627 ofst = rbuDeltaGetInt(&zDelta, &lenDelta); 628 if( lenDelta>0 && zDelta[0]!=',' ){ 629 /* ERROR: copy command not terminated by ',' */ 630 return -1; 631 } 632 zDelta++; lenDelta--; 633 total += cnt; 634 if( total>limit ){ 635 /* ERROR: copy exceeds output file size */ 636 return -1; 637 } 638 if( (u64)ofst+(u64)cnt > (u64)lenSrc ){ 639 /* ERROR: copy extends past end of input */ 640 return -1; 641 } 642 memcpy(zOut, &zSrc[ofst], cnt); 643 zOut += cnt; 644 break; 645 } 646 case ':': { 647 zDelta++; lenDelta--; 648 total += cnt; 649 if( total>limit ){ 650 /* ERROR: insert command gives an output larger than predicted */ 651 return -1; 652 } 653 if( cnt>lenDelta ){ 654 /* ERROR: insert count exceeds size of delta */ 655 return -1; 656 } 657 memcpy(zOut, zDelta, cnt); 658 zOut += cnt; 659 zDelta += cnt; 660 lenDelta -= cnt; 661 break; 662 } 663 case ';': { 664 zDelta++; lenDelta--; 665 zOut[0] = 0; 666 #if RBU_ENABLE_DELTA_CKSUM 667 if( cnt!=rbuDeltaChecksum(zOrigOut, total) ){ 668 /* ERROR: bad checksum */ 669 return -1; 670 } 671 #endif 672 if( total!=limit ){ 673 /* ERROR: generated size does not match predicted size */ 674 return -1; 675 } 676 return total; 677 } 678 default: { 679 /* ERROR: unknown delta operator */ 680 return -1; 681 } 682 } 683 } 684 /* ERROR: unterminated delta */ 685 return -1; 686 } 687 688 static int rbuDeltaOutputSize(const char *zDelta, int lenDelta){ 689 int size; 690 size = rbuDeltaGetInt(&zDelta, &lenDelta); 691 if( lenDelta<=0 || *zDelta!='\n' ){ 692 /* ERROR: size integer not terminated by "\n" */ 693 return -1; 694 } 695 return size; 696 } 697 698 /* 699 ** End of code taken from fossil. 700 *************************************************************************/ 701 702 /* 703 ** Implementation of SQL scalar function rbu_fossil_delta(). 704 ** 705 ** This function applies a fossil delta patch to a blob. Exactly two 706 ** arguments must be passed to this function. The first is the blob to 707 ** patch and the second the patch to apply. If no error occurs, this 708 ** function returns the patched blob. 709 */ 710 static void rbuFossilDeltaFunc( 711 sqlite3_context *context, 712 int argc, 713 sqlite3_value **argv 714 ){ 715 const char *aDelta; 716 int nDelta; 717 const char *aOrig; 718 int nOrig; 719 720 int nOut; 721 int nOut2; 722 char *aOut; 723 724 assert( argc==2 ); 725 UNUSED_PARAMETER(argc); 726 727 nOrig = sqlite3_value_bytes(argv[0]); 728 aOrig = (const char*)sqlite3_value_blob(argv[0]); 729 nDelta = sqlite3_value_bytes(argv[1]); 730 aDelta = (const char*)sqlite3_value_blob(argv[1]); 731 732 /* Figure out the size of the output */ 733 nOut = rbuDeltaOutputSize(aDelta, nDelta); 734 if( nOut<0 ){ 735 sqlite3_result_error(context, "corrupt fossil delta", -1); 736 return; 737 } 738 739 aOut = sqlite3_malloc64((i64)nOut+1); 740 if( aOut==0 ){ 741 sqlite3_result_error_nomem(context); 742 }else{ 743 nOut2 = rbuDeltaApply(aOrig, nOrig, aDelta, nDelta, aOut); 744 if( nOut2!=nOut ){ 745 sqlite3_free(aOut); 746 sqlite3_result_error(context, "corrupt fossil delta", -1); 747 }else{ 748 sqlite3_result_blob(context, aOut, nOut, sqlite3_free); 749 } 750 } 751 } 752 753 754 /* 755 ** Prepare the SQL statement in buffer zSql against database handle db. 756 ** If successful, set *ppStmt to point to the new statement and return 757 ** SQLITE_OK. 758 ** 759 ** Otherwise, if an error does occur, set *ppStmt to NULL and return 760 ** an SQLite error code. Additionally, set output variable *pzErrmsg to 761 ** point to a buffer containing an error message. It is the responsibility 762 ** of the caller to (eventually) free this buffer using sqlite3_free(). 763 */ 764 static int prepareAndCollectError( 765 sqlite3 *db, 766 sqlite3_stmt **ppStmt, 767 char **pzErrmsg, 768 const char *zSql 769 ){ 770 int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0); 771 if( rc!=SQLITE_OK ){ 772 *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db)); 773 *ppStmt = 0; 774 } 775 return rc; 776 } 777 778 /* 779 ** Reset the SQL statement passed as the first argument. Return a copy 780 ** of the value returned by sqlite3_reset(). 781 ** 782 ** If an error has occurred, then set *pzErrmsg to point to a buffer 783 ** containing an error message. It is the responsibility of the caller 784 ** to eventually free this buffer using sqlite3_free(). 785 */ 786 static int resetAndCollectError(sqlite3_stmt *pStmt, char **pzErrmsg){ 787 int rc = sqlite3_reset(pStmt); 788 if( rc!=SQLITE_OK ){ 789 *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(sqlite3_db_handle(pStmt))); 790 } 791 return rc; 792 } 793 794 /* 795 ** Unless it is NULL, argument zSql points to a buffer allocated using 796 ** sqlite3_malloc containing an SQL statement. This function prepares the SQL 797 ** statement against database db and frees the buffer. If statement 798 ** compilation is successful, *ppStmt is set to point to the new statement 799 ** handle and SQLITE_OK is returned. 800 ** 801 ** Otherwise, if an error occurs, *ppStmt is set to NULL and an error code 802 ** returned. In this case, *pzErrmsg may also be set to point to an error 803 ** message. It is the responsibility of the caller to free this error message 804 ** buffer using sqlite3_free(). 805 ** 806 ** If argument zSql is NULL, this function assumes that an OOM has occurred. 807 ** In this case SQLITE_NOMEM is returned and *ppStmt set to NULL. 808 */ 809 static int prepareFreeAndCollectError( 810 sqlite3 *db, 811 sqlite3_stmt **ppStmt, 812 char **pzErrmsg, 813 char *zSql 814 ){ 815 int rc; 816 assert( *pzErrmsg==0 ); 817 if( zSql==0 ){ 818 rc = SQLITE_NOMEM; 819 *ppStmt = 0; 820 }else{ 821 rc = prepareAndCollectError(db, ppStmt, pzErrmsg, zSql); 822 sqlite3_free(zSql); 823 } 824 return rc; 825 } 826 827 /* 828 ** Free the RbuObjIter.azTblCol[] and RbuObjIter.abTblPk[] arrays allocated 829 ** by an earlier call to rbuObjIterCacheTableInfo(). 830 */ 831 static void rbuObjIterFreeCols(RbuObjIter *pIter){ 832 int i; 833 for(i=0; inTblCol; i++){ 834 sqlite3_free(pIter->azTblCol[i]); 835 sqlite3_free(pIter->azTblType[i]); 836 sqlite3_free(pIter->azTblDflt[i]); 837 } 838 sqlite3_free(pIter->azTblCol); 839 pIter->azTblCol = 0; 840 pIter->azTblType = 0; 841 pIter->azTblDflt = 0; 842 pIter->aiSrcOrder = 0; 843 pIter->abTblPk = 0; 844 pIter->abNotNull = 0; 845 pIter->nTblCol = 0; 846 pIter->eType = 0; /* Invalid value */ 847 } 848 849 /* 850 ** Finalize all statements and free all allocations that are specific to 851 ** the current object (table/index pair). 852 */ 853 static void rbuObjIterClearStatements(RbuObjIter *pIter){ 854 RbuUpdateStmt *pUp; 855 856 sqlite3_finalize(pIter->pSelect); 857 sqlite3_finalize(pIter->pInsert); 858 sqlite3_finalize(pIter->pDelete); 859 sqlite3_finalize(pIter->pTmpInsert); 860 pUp = pIter->pRbuUpdate; 861 while( pUp ){ 862 RbuUpdateStmt *pTmp = pUp->pNext; 863 sqlite3_finalize(pUp->pUpdate); 864 sqlite3_free(pUp); 865 pUp = pTmp; 866 } 867 sqlite3_free(pIter->aIdxCol); 868 sqlite3_free(pIter->zIdxSql); 869 870 pIter->pSelect = 0; 871 pIter->pInsert = 0; 872 pIter->pDelete = 0; 873 pIter->pRbuUpdate = 0; 874 pIter->pTmpInsert = 0; 875 pIter->nCol = 0; 876 pIter->nIdxCol = 0; 877 pIter->aIdxCol = 0; 878 pIter->zIdxSql = 0; 879 } 880 881 /* 882 ** Clean up any resources allocated as part of the iterator object passed 883 ** as the only argument. 884 */ 885 static void rbuObjIterFinalize(RbuObjIter *pIter){ 886 rbuObjIterClearStatements(pIter); 887 sqlite3_finalize(pIter->pTblIter); 888 sqlite3_finalize(pIter->pIdxIter); 889 rbuObjIterFreeCols(pIter); 890 memset(pIter, 0, sizeof(RbuObjIter)); 891 } 892 893 /* 894 ** Advance the iterator to the next position. 895 ** 896 ** If no error occurs, SQLITE_OK is returned and the iterator is left 897 ** pointing to the next entry. Otherwise, an error code and message is 898 ** left in the RBU handle passed as the first argument. A copy of the 899 ** error code is returned. 900 */ 901 static int rbuObjIterNext(sqlite3rbu *p, RbuObjIter *pIter){ 902 int rc = p->rc; 903 if( rc==SQLITE_OK ){ 904 905 /* Free any SQLite statements used while processing the previous object */ 906 rbuObjIterClearStatements(pIter); 907 if( pIter->zIdx==0 ){ 908 rc = sqlite3_exec(p->dbMain, 909 "DROP TRIGGER IF EXISTS temp.rbu_insert_tr;" 910 "DROP TRIGGER IF EXISTS temp.rbu_update1_tr;" 911 "DROP TRIGGER IF EXISTS temp.rbu_update2_tr;" 912 "DROP TRIGGER IF EXISTS temp.rbu_delete_tr;" 913 , 0, 0, &p->zErrmsg 914 ); 915 } 916 917 if( rc==SQLITE_OK ){ 918 if( pIter->bCleanup ){ 919 rbuObjIterFreeCols(pIter); 920 pIter->bCleanup = 0; 921 rc = sqlite3_step(pIter->pTblIter); 922 if( rc!=SQLITE_ROW ){ 923 rc = resetAndCollectError(pIter->pTblIter, &p->zErrmsg); 924 pIter->zTbl = 0; 925 pIter->zDataTbl = 0; 926 }else{ 927 pIter->zTbl = (const char*)sqlite3_column_text(pIter->pTblIter, 0); 928 pIter->zDataTbl = (const char*)sqlite3_column_text(pIter->pTblIter,1); 929 rc = (pIter->zDataTbl && pIter->zTbl) ? SQLITE_OK : SQLITE_NOMEM; 930 } 931 }else{ 932 if( pIter->zIdx==0 ){ 933 sqlite3_stmt *pIdx = pIter->pIdxIter; 934 rc = sqlite3_bind_text(pIdx, 1, pIter->zTbl, -1, SQLITE_STATIC); 935 } 936 if( rc==SQLITE_OK ){ 937 rc = sqlite3_step(pIter->pIdxIter); 938 if( rc!=SQLITE_ROW ){ 939 rc = resetAndCollectError(pIter->pIdxIter, &p->zErrmsg); 940 pIter->bCleanup = 1; 941 pIter->zIdx = 0; 942 }else{ 943 pIter->zIdx = (const char*)sqlite3_column_text(pIter->pIdxIter, 0); 944 pIter->iTnum = sqlite3_column_int(pIter->pIdxIter, 1); 945 pIter->bUnique = sqlite3_column_int(pIter->pIdxIter, 2); 946 rc = pIter->zIdx ? SQLITE_OK : SQLITE_NOMEM; 947 } 948 } 949 } 950 } 951 } 952 953 if( rc!=SQLITE_OK ){ 954 rbuObjIterFinalize(pIter); 955 p->rc = rc; 956 } 957 return rc; 958 } 959 960 961 /* 962 ** The implementation of the rbu_target_name() SQL function. This function 963 ** accepts one or two arguments. The first argument is the name of a table - 964 ** the name of a table in the RBU database. The second, if it is present, is 1 965 ** for a view or 0 for a table. 966 ** 967 ** For a non-vacuum RBU handle, if the table name matches the pattern: 968 ** 969 ** data[0-9]_ 970 ** 971 ** where is any sequence of 1 or more characters, is returned. 972 ** Otherwise, if the only argument does not match the above pattern, an SQL 973 ** NULL is returned. 974 ** 975 ** "data_t1" -> "t1" 976 ** "data0123_t2" -> "t2" 977 ** "dataAB_t3" -> NULL 978 ** 979 ** For an rbu vacuum handle, a copy of the first argument is returned if 980 ** the second argument is either missing or 0 (not a view). 981 */ 982 static void rbuTargetNameFunc( 983 sqlite3_context *pCtx, 984 int argc, 985 sqlite3_value **argv 986 ){ 987 sqlite3rbu *p = sqlite3_user_data(pCtx); 988 const char *zIn; 989 assert( argc==1 || argc==2 ); 990 991 zIn = (const char*)sqlite3_value_text(argv[0]); 992 if( zIn ){ 993 if( rbuIsVacuum(p) ){ 994 assert( argc==2 || argc==1 ); 995 if( argc==1 || 0==sqlite3_value_int(argv[1]) ){ 996 sqlite3_result_text(pCtx, zIn, -1, SQLITE_STATIC); 997 } 998 }else{ 999 if( strlen(zIn)>4 && memcmp("data", zIn, 4)==0 ){ 1000 int i; 1001 for(i=4; zIn[i]>='0' && zIn[i]<='9'; i++); 1002 if( zIn[i]=='_' && zIn[i+1] ){ 1003 sqlite3_result_text(pCtx, &zIn[i+1], -1, SQLITE_STATIC); 1004 } 1005 } 1006 } 1007 } 1008 } 1009 1010 /* 1011 ** Initialize the iterator structure passed as the second argument. 1012 ** 1013 ** If no error occurs, SQLITE_OK is returned and the iterator is left 1014 ** pointing to the first entry. Otherwise, an error code and message is 1015 ** left in the RBU handle passed as the first argument. A copy of the 1016 ** error code is returned. 1017 */ 1018 static int rbuObjIterFirst(sqlite3rbu *p, RbuObjIter *pIter){ 1019 int rc; 1020 memset(pIter, 0, sizeof(RbuObjIter)); 1021 1022 rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pTblIter, &p->zErrmsg, 1023 sqlite3_mprintf( 1024 "SELECT rbu_target_name(name, type='view') AS target, name " 1025 "FROM sqlite_schema " 1026 "WHERE type IN ('table', 'view') AND target IS NOT NULL " 1027 " %s " 1028 "ORDER BY name" 1029 , rbuIsVacuum(p) ? "AND rootpage!=0 AND rootpage IS NOT NULL" : "")); 1030 1031 if( rc==SQLITE_OK ){ 1032 rc = prepareAndCollectError(p->dbMain, &pIter->pIdxIter, &p->zErrmsg, 1033 "SELECT name, rootpage, sql IS NULL OR substr(8, 6)=='UNIQUE' " 1034 " FROM main.sqlite_schema " 1035 " WHERE type='index' AND tbl_name = ?" 1036 ); 1037 } 1038 1039 pIter->bCleanup = 1; 1040 p->rc = rc; 1041 return rbuObjIterNext(p, pIter); 1042 } 1043 1044 /* 1045 ** This is a wrapper around "sqlite3_mprintf(zFmt, ...)". If an OOM occurs, 1046 ** an error code is stored in the RBU handle passed as the first argument. 1047 ** 1048 ** If an error has already occurred (p->rc is already set to something other 1049 ** than SQLITE_OK), then this function returns NULL without modifying the 1050 ** stored error code. In this case it still calls sqlite3_free() on any 1051 ** printf() parameters associated with %z conversions. 1052 */ 1053 static char *rbuMPrintf(sqlite3rbu *p, const char *zFmt, ...){ 1054 char *zSql = 0; 1055 va_list ap; 1056 va_start(ap, zFmt); 1057 zSql = sqlite3_vmprintf(zFmt, ap); 1058 if( p->rc==SQLITE_OK ){ 1059 if( zSql==0 ) p->rc = SQLITE_NOMEM; 1060 }else{ 1061 sqlite3_free(zSql); 1062 zSql = 0; 1063 } 1064 va_end(ap); 1065 return zSql; 1066 } 1067 1068 /* 1069 ** Argument zFmt is a sqlite3_mprintf() style format string. The trailing 1070 ** arguments are the usual subsitution values. This function performs 1071 ** the printf() style substitutions and executes the result as an SQL 1072 ** statement on the RBU handles database. 1073 ** 1074 ** If an error occurs, an error code and error message is stored in the 1075 ** RBU handle. If an error has already occurred when this function is 1076 ** called, it is a no-op. 1077 */ 1078 static int rbuMPrintfExec(sqlite3rbu *p, sqlite3 *db, const char *zFmt, ...){ 1079 va_list ap; 1080 char *zSql; 1081 va_start(ap, zFmt); 1082 zSql = sqlite3_vmprintf(zFmt, ap); 1083 if( p->rc==SQLITE_OK ){ 1084 if( zSql==0 ){ 1085 p->rc = SQLITE_NOMEM; 1086 }else{ 1087 p->rc = sqlite3_exec(db, zSql, 0, 0, &p->zErrmsg); 1088 } 1089 } 1090 sqlite3_free(zSql); 1091 va_end(ap); 1092 return p->rc; 1093 } 1094 1095 /* 1096 ** Attempt to allocate and return a pointer to a zeroed block of nByte 1097 ** bytes. 1098 ** 1099 ** If an error (i.e. an OOM condition) occurs, return NULL and leave an 1100 ** error code in the rbu handle passed as the first argument. Or, if an 1101 ** error has already occurred when this function is called, return NULL 1102 ** immediately without attempting the allocation or modifying the stored 1103 ** error code. 1104 */ 1105 static void *rbuMalloc(sqlite3rbu *p, sqlite3_int64 nByte){ 1106 void *pRet = 0; 1107 if( p->rc==SQLITE_OK ){ 1108 assert( nByte>0 ); 1109 pRet = sqlite3_malloc64(nByte); 1110 if( pRet==0 ){ 1111 p->rc = SQLITE_NOMEM; 1112 }else{ 1113 memset(pRet, 0, nByte); 1114 } 1115 } 1116 return pRet; 1117 } 1118 1119 1120 /* 1121 ** Allocate and zero the pIter->azTblCol[] and abTblPk[] arrays so that 1122 ** there is room for at least nCol elements. If an OOM occurs, store an 1123 ** error code in the RBU handle passed as the first argument. 1124 */ 1125 static void rbuAllocateIterArrays(sqlite3rbu *p, RbuObjIter *pIter, int nCol){ 1126 sqlite3_int64 nByte = (3*sizeof(char*) + sizeof(int) + 3*sizeof(u8)) * nCol; 1127 char **azNew; 1128 1129 azNew = (char**)rbuMalloc(p, nByte); 1130 if( azNew ){ 1131 pIter->azTblCol = azNew; 1132 pIter->azTblType = &azNew[nCol]; 1133 pIter->azTblDflt = &azNew[nCol*2]; 1134 pIter->aiSrcOrder = (int*)&pIter->azTblDflt[nCol]; 1135 pIter->abTblPk = (u8*)&pIter->aiSrcOrder[nCol]; 1136 pIter->abNotNull = (u8*)&pIter->abTblPk[nCol]; 1137 pIter->abIndexed = (u8*)&pIter->abNotNull[nCol]; 1138 } 1139 } 1140 1141 /* 1142 ** The first argument must be a nul-terminated string. This function 1143 ** returns a copy of the string in memory obtained from sqlite3_malloc(). 1144 ** It is the responsibility of the caller to eventually free this memory 1145 ** using sqlite3_free(). 1146 ** 1147 ** If an OOM condition is encountered when attempting to allocate memory, 1148 ** output variable (*pRc) is set to SQLITE_NOMEM before returning. Otherwise, 1149 ** if the allocation succeeds, (*pRc) is left unchanged. 1150 */ 1151 static char *rbuStrndup(const char *zStr, int *pRc){ 1152 char *zRet = 0; 1153 1154 if( *pRc==SQLITE_OK ){ 1155 if( zStr ){ 1156 size_t nCopy = strlen(zStr) + 1; 1157 zRet = (char*)sqlite3_malloc64(nCopy); 1158 if( zRet ){ 1159 memcpy(zRet, zStr, nCopy); 1160 }else{ 1161 *pRc = SQLITE_NOMEM; 1162 } 1163 } 1164 } 1165 1166 return zRet; 1167 } 1168 1169 /* 1170 ** Finalize the statement passed as the second argument. 1171 ** 1172 ** If the sqlite3_finalize() call indicates that an error occurs, and the 1173 ** rbu handle error code is not already set, set the error code and error 1174 ** message accordingly. 1175 */ 1176 static void rbuFinalize(sqlite3rbu *p, sqlite3_stmt *pStmt){ 1177 sqlite3 *db = sqlite3_db_handle(pStmt); 1178 int rc = sqlite3_finalize(pStmt); 1179 if( p->rc==SQLITE_OK && rc!=SQLITE_OK ){ 1180 p->rc = rc; 1181 p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db)); 1182 } 1183 } 1184 1185 /* Determine the type of a table. 1186 ** 1187 ** peType is of type (int*), a pointer to an output parameter of type 1188 ** (int). This call sets the output parameter as follows, depending 1189 ** on the type of the table specified by parameters dbName and zTbl. 1190 ** 1191 ** RBU_PK_NOTABLE: No such table. 1192 ** RBU_PK_NONE: Table has an implicit rowid. 1193 ** RBU_PK_IPK: Table has an explicit IPK column. 1194 ** RBU_PK_EXTERNAL: Table has an external PK index. 1195 ** RBU_PK_WITHOUT_ROWID: Table is WITHOUT ROWID. 1196 ** RBU_PK_VTAB: Table is a virtual table. 1197 ** 1198 ** Argument *piPk is also of type (int*), and also points to an output 1199 ** parameter. Unless the table has an external primary key index 1200 ** (i.e. unless *peType is set to 3), then *piPk is set to zero. Or, 1201 ** if the table does have an external primary key index, then *piPk 1202 ** is set to the root page number of the primary key index before 1203 ** returning. 1204 ** 1205 ** ALGORITHM: 1206 ** 1207 ** if( no entry exists in sqlite_schema ){ 1208 ** return RBU_PK_NOTABLE 1209 ** }else if( sql for the entry starts with "CREATE VIRTUAL" ){ 1210 ** return RBU_PK_VTAB 1211 ** }else if( "PRAGMA index_list()" for the table contains a "pk" index ){ 1212 ** if( the index that is the pk exists in sqlite_schema ){ 1213 ** *piPK = rootpage of that index. 1214 ** return RBU_PK_EXTERNAL 1215 ** }else{ 1216 ** return RBU_PK_WITHOUT_ROWID 1217 ** } 1218 ** }else if( "PRAGMA table_info()" lists one or more "pk" columns ){ 1219 ** return RBU_PK_IPK 1220 ** }else{ 1221 ** return RBU_PK_NONE 1222 ** } 1223 */ 1224 static void rbuTableType( 1225 sqlite3rbu *p, 1226 const char *zTab, 1227 int *peType, 1228 int *piTnum, 1229 int *piPk 1230 ){ 1231 /* 1232 ** 0) SELECT count(*) FROM sqlite_schema where name=%Q AND IsVirtual(%Q) 1233 ** 1) PRAGMA index_list = ? 1234 ** 2) SELECT count(*) FROM sqlite_schema where name=%Q 1235 ** 3) PRAGMA table_info = ? 1236 */ 1237 sqlite3_stmt *aStmt[4] = {0, 0, 0, 0}; 1238 1239 *peType = RBU_PK_NOTABLE; 1240 *piPk = 0; 1241 1242 assert( p->rc==SQLITE_OK ); 1243 p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[0], &p->zErrmsg, 1244 sqlite3_mprintf( 1245 "SELECT " 1246 " (sql COLLATE nocase BETWEEN 'CREATE VIRTUAL' AND 'CREATE VIRTUAM')," 1247 " rootpage" 1248 " FROM sqlite_schema" 1249 " WHERE name=%Q", zTab 1250 )); 1251 if( p->rc!=SQLITE_OK || sqlite3_step(aStmt[0])!=SQLITE_ROW ){ 1252 /* Either an error, or no such table. */ 1253 goto rbuTableType_end; 1254 } 1255 if( sqlite3_column_int(aStmt[0], 0) ){ 1256 *peType = RBU_PK_VTAB; /* virtual table */ 1257 goto rbuTableType_end; 1258 } 1259 *piTnum = sqlite3_column_int(aStmt[0], 1); 1260 1261 p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[1], &p->zErrmsg, 1262 sqlite3_mprintf("PRAGMA index_list=%Q",zTab) 1263 ); 1264 if( p->rc ) goto rbuTableType_end; 1265 while( sqlite3_step(aStmt[1])==SQLITE_ROW ){ 1266 const u8 *zOrig = sqlite3_column_text(aStmt[1], 3); 1267 const u8 *zIdx = sqlite3_column_text(aStmt[1], 1); 1268 if( zOrig && zIdx && zOrig[0]=='p' ){ 1269 p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[2], &p->zErrmsg, 1270 sqlite3_mprintf( 1271 "SELECT rootpage FROM sqlite_schema WHERE name = %Q", zIdx 1272 )); 1273 if( p->rc==SQLITE_OK ){ 1274 if( sqlite3_step(aStmt[2])==SQLITE_ROW ){ 1275 *piPk = sqlite3_column_int(aStmt[2], 0); 1276 *peType = RBU_PK_EXTERNAL; 1277 }else{ 1278 *peType = RBU_PK_WITHOUT_ROWID; 1279 } 1280 } 1281 goto rbuTableType_end; 1282 } 1283 } 1284 1285 p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[3], &p->zErrmsg, 1286 sqlite3_mprintf("PRAGMA table_info=%Q",zTab) 1287 ); 1288 if( p->rc==SQLITE_OK ){ 1289 while( sqlite3_step(aStmt[3])==SQLITE_ROW ){ 1290 if( sqlite3_column_int(aStmt[3],5)>0 ){ 1291 *peType = RBU_PK_IPK; /* explicit IPK column */ 1292 goto rbuTableType_end; 1293 } 1294 } 1295 *peType = RBU_PK_NONE; 1296 } 1297 1298 rbuTableType_end: { 1299 unsigned int i; 1300 for(i=0; iabIndexed[] array. 1309 */ 1310 static void rbuObjIterCacheIndexedCols(sqlite3rbu *p, RbuObjIter *pIter){ 1311 sqlite3_stmt *pList = 0; 1312 int bIndex = 0; 1313 1314 if( p->rc==SQLITE_OK ){ 1315 memcpy(pIter->abIndexed, pIter->abTblPk, sizeof(u8)*pIter->nTblCol); 1316 p->rc = prepareFreeAndCollectError(p->dbMain, &pList, &p->zErrmsg, 1317 sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl) 1318 ); 1319 } 1320 1321 pIter->nIndex = 0; 1322 while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pList) ){ 1323 const char *zIdx = (const char*)sqlite3_column_text(pList, 1); 1324 int bPartial = sqlite3_column_int(pList, 4); 1325 sqlite3_stmt *pXInfo = 0; 1326 if( zIdx==0 ) break; 1327 if( bPartial ){ 1328 memset(pIter->abIndexed, 0x01, sizeof(u8)*pIter->nTblCol); 1329 } 1330 p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg, 1331 sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx) 1332 ); 1333 while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){ 1334 int iCid = sqlite3_column_int(pXInfo, 1); 1335 if( iCid>=0 ) pIter->abIndexed[iCid] = 1; 1336 if( iCid==-2 ){ 1337 memset(pIter->abIndexed, 0x01, sizeof(u8)*pIter->nTblCol); 1338 } 1339 } 1340 rbuFinalize(p, pXInfo); 1341 bIndex = 1; 1342 pIter->nIndex++; 1343 } 1344 1345 if( pIter->eType==RBU_PK_WITHOUT_ROWID ){ 1346 /* "PRAGMA index_list" includes the main PK b-tree */ 1347 pIter->nIndex--; 1348 } 1349 1350 rbuFinalize(p, pList); 1351 if( bIndex==0 ) pIter->abIndexed = 0; 1352 } 1353 1354 /* 1355 ** Return true if table zTbl in the main database of the target is a 1356 ** STRICT table, or false otherwise. If an error occurs, an error code 1357 ** and message are left in the RBU handle and zero is returned. 1358 */ 1359 static int rbuTableIsStrict(sqlite3rbu *p, const char *zTbl){ 1360 int bStrict = 0; 1361 sqlite3_stmt *pStmt = 0; 1362 if( p->rc==SQLITE_OK ){ 1363 p->rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &p->zErrmsg, 1364 sqlite3_mprintf("PRAGMA main.table_list(%Q)", zTbl) 1365 ); 1366 if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 1367 bStrict = sqlite3_column_int(pStmt, 5); 1368 } 1369 rbuFinalize(p, pStmt); 1370 } 1371 return bStrict; 1372 } 1373 1374 /* 1375 ** If they are not already populated, populate the pIter->azTblCol[], 1376 ** pIter->abTblPk[], pIter->nTblCol and pIter->bRowid variables according to 1377 ** the table (not index) that the iterator currently points to. 1378 ** 1379 ** Return SQLITE_OK if successful, or an SQLite error code otherwise. If 1380 ** an error does occur, an error code and error message are also left in 1381 ** the RBU handle. 1382 */ 1383 static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){ 1384 if( pIter->azTblCol==0 ){ 1385 sqlite3_stmt *pStmt = 0; 1386 int nCol = 0; 1387 int i; /* for() loop iterator variable */ 1388 int bRbuRowid = 0; /* If input table has column "rbu_rowid" */ 1389 int iOrder = 0; 1390 int iTnum = 0; 1391 int bStrict = 0; /* True if target is a STRICT table */ 1392 1393 /* Figure out the type of table this step will deal with. */ 1394 assert( pIter->eType==0 ); 1395 rbuTableType(p, pIter->zTbl, &pIter->eType, &iTnum, &pIter->iPkTnum); 1396 if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_NOTABLE ){ 1397 p->rc = SQLITE_ERROR; 1398 p->zErrmsg = sqlite3_mprintf("no such table: %s", pIter->zTbl); 1399 } 1400 if( p->rc ) return p->rc; 1401 if( pIter->zIdx==0 ) pIter->iTnum = iTnum; 1402 1403 assert( pIter->eType==RBU_PK_NONE || pIter->eType==RBU_PK_IPK 1404 || pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_WITHOUT_ROWID 1405 || pIter->eType==RBU_PK_VTAB 1406 ); 1407 1408 /* Populate the azTblCol[] and nTblCol variables based on the columns 1409 ** of the input table. Ignore any input table columns that begin with 1410 ** "rbu_". */ 1411 p->rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg, 1412 sqlite3_mprintf("SELECT * FROM '%q'", pIter->zDataTbl) 1413 ); 1414 if( p->rc==SQLITE_OK ){ 1415 nCol = sqlite3_column_count(pStmt); 1416 rbuAllocateIterArrays(p, pIter, nCol); 1417 } 1418 for(i=0; p->rc==SQLITE_OK && irc); 1422 pIter->aiSrcOrder[pIter->nTblCol] = pIter->nTblCol; 1423 pIter->azTblCol[pIter->nTblCol++] = zCopy; 1424 } 1425 else if( 0==sqlite3_stricmp("rbu_rowid", zName) ){ 1426 bRbuRowid = 1; 1427 } 1428 } 1429 sqlite3_finalize(pStmt); 1430 pStmt = 0; 1431 1432 if( p->rc==SQLITE_OK 1433 && rbuIsVacuum(p)==0 1434 && bRbuRowid!=(pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE) 1435 ){ 1436 p->rc = SQLITE_ERROR; 1437 p->zErrmsg = sqlite3_mprintf( 1438 "table %q %s rbu_rowid column", pIter->zDataTbl, 1439 (bRbuRowid ? "may not have" : "requires") 1440 ); 1441 } 1442 1443 bStrict = rbuTableIsStrict(p, pIter->zTbl); 1444 1445 /* Check that all non-HIDDEN columns in the destination table are also 1446 ** present in the input table. Populate the abTblPk[], azTblType[], 1447 ** azTblDflt[] and aiTblOrder[] arrays at the same time. 1448 ** 1449 ** RBU does not support tables with GENERATED columns. If the target 1450 ** table has any, return an error. */ 1451 if( p->rc==SQLITE_OK ){ 1452 p->rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &p->zErrmsg, 1453 sqlite3_mprintf("PRAGMA table_xinfo(%Q)", pIter->zTbl) 1454 ); 1455 } 1456 while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 1457 const char *zName = (const char*)sqlite3_column_text(pStmt, 1); 1458 int eHidden = sqlite3_column_int(pStmt, 6); 1459 if( zName==0 ) break; /* An OOM. Bail out */ 1460 if( eHidden==1 ) continue; /* Hidden column. Ignore */ 1461 if( eHidden!=0 ){ 1462 p->rc = SQLITE_ERROR; 1463 p->zErrmsg = sqlite3_mprintf( 1464 "generated columns not supported: %s.%s", pIter->zTbl, zName 1465 ); 1466 break; 1467 } 1468 for(i=iOrder; inTblCol; i++){ 1469 if( 0==strcmp(zName, pIter->azTblCol[i]) ) break; 1470 } 1471 if( i==pIter->nTblCol ){ 1472 p->rc = SQLITE_ERROR; 1473 p->zErrmsg = sqlite3_mprintf("column missing from %q: %s", 1474 pIter->zDataTbl, zName 1475 ); 1476 }else{ 1477 int iPk = sqlite3_column_int(pStmt, 5); 1478 int bNotNull = sqlite3_column_int(pStmt, 3); 1479 const char *zType = (const char*)sqlite3_column_text(pStmt, 2); 1480 const char *zDflt = (const char*)sqlite3_column_text(pStmt, 4); 1481 1482 if( i!=iOrder ){ 1483 SWAP(int, pIter->aiSrcOrder[i], pIter->aiSrcOrder[iOrder]); 1484 SWAP(char*, pIter->azTblCol[i], pIter->azTblCol[iOrder]); 1485 } 1486 1487 /* In a STRICT table, ANY means no affinity. In the non-STRICT 1488 ** imposter it would mean NUMERIC, so declare it without a type. */ 1489 if( bStrict && sqlite3_stricmp(zType, "ANY")==0 ) zType = ""; 1490 pIter->azTblType[iOrder] = rbuStrndup(zType, &p->rc); 1491 pIter->azTblDflt[iOrder] = rbuStrndup(zDflt, &p->rc); 1492 assert( iPk>=0 ); 1493 pIter->abTblPk[iOrder] = (u8)iPk; 1494 pIter->abNotNull[iOrder] = (u8)bNotNull || (iPk!=0); 1495 iOrder++; 1496 } 1497 } 1498 1499 rbuFinalize(p, pStmt); 1500 rbuObjIterCacheIndexedCols(p, pIter); 1501 assert( pIter->eType!=RBU_PK_VTAB || pIter->abIndexed==0 ); 1502 assert( pIter->eType!=RBU_PK_VTAB || pIter->nIndex==0 ); 1503 } 1504 1505 return p->rc; 1506 } 1507 1508 /* 1509 ** This function constructs and returns a pointer to a nul-terminated 1510 ** string containing some SQL clause or list based on one or more of the 1511 ** column names currently stored in the pIter->azTblCol[] array. 1512 */ 1513 static char *rbuObjIterGetCollist( 1514 sqlite3rbu *p, /* RBU object */ 1515 RbuObjIter *pIter /* Object iterator for column names */ 1516 ){ 1517 char *zList = 0; 1518 const char *zSep = ""; 1519 int i; 1520 for(i=0; inTblCol; i++){ 1521 const char *z = pIter->azTblCol[i]; 1522 zList = rbuMPrintf(p, "%z%s\"%w\"", zList, zSep, z); 1523 zSep = ", "; 1524 } 1525 return zList; 1526 } 1527 1528 /* 1529 ** Return a comma separated list of the quoted PRIMARY KEY column names, 1530 ** in order, for the current table. Before each column name, add the text 1531 ** zPre. After each column name, add the zPost text. Use zSeparator as 1532 ** the separator text (usually ", "). 1533 */ 1534 static char *rbuObjIterGetPkList( 1535 sqlite3rbu *p, /* RBU object */ 1536 RbuObjIter *pIter, /* Object iterator for column names */ 1537 const char *zPre, /* Before each quoted column name */ 1538 const char *zSeparator, /* Separator to use between columns */ 1539 const char *zPost /* After each quoted column name */ 1540 ){ 1541 int iPk = 1; 1542 char *zRet = 0; 1543 const char *zSep = ""; 1544 while( 1 ){ 1545 int i; 1546 for(i=0; inTblCol; i++){ 1547 if( (int)pIter->abTblPk[i]==iPk ){ 1548 const char *zCol = pIter->azTblCol[i]; 1549 zRet = rbuMPrintf(p, "%z%s%s\"%w\"%s", zRet, zSep, zPre, zCol, zPost); 1550 zSep = zSeparator; 1551 break; 1552 } 1553 } 1554 if( i==pIter->nTblCol ) break; 1555 iPk++; 1556 } 1557 return zRet; 1558 } 1559 1560 /* 1561 ** This function is called as part of restarting an RBU vacuum within 1562 ** stage 1 of the process (while the *-oal file is being built) while 1563 ** updating a table (not an index). The table may be a rowid table or 1564 ** a WITHOUT ROWID table. It queries the target database to find the 1565 ** largest key that has already been written to the target table and 1566 ** constructs a WHERE clause that can be used to extract the remaining 1567 ** rows from the source table. For a rowid table, the WHERE clause 1568 ** is of the form: 1569 ** 1570 ** "WHERE _rowid_ > ?" 1571 ** 1572 ** and for WITHOUT ROWID tables: 1573 ** 1574 ** "WHERE (key1, key2) > (?, ?)" 1575 ** 1576 ** Instead of "?" placeholders, the actual WHERE clauses created by 1577 ** this function contain literal SQL values. 1578 */ 1579 static char *rbuVacuumTableStart( 1580 sqlite3rbu *p, /* RBU handle */ 1581 RbuObjIter *pIter, /* RBU iterator object */ 1582 int bRowid, /* True for a rowid table */ 1583 const char *zWrite /* Target table name prefix */ 1584 ){ 1585 sqlite3_stmt *pMax = 0; 1586 char *zRet = 0; 1587 if( bRowid ){ 1588 p->rc = prepareFreeAndCollectError(p->dbMain, &pMax, &p->zErrmsg, 1589 sqlite3_mprintf( 1590 "SELECT max(_rowid_) FROM \"%s%w\"", zWrite, pIter->zTbl 1591 ) 1592 ); 1593 if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){ 1594 sqlite3_int64 iMax = sqlite3_column_int64(pMax, 0); 1595 zRet = rbuMPrintf(p, " WHERE _rowid_ > %lld ", iMax); 1596 } 1597 rbuFinalize(p, pMax); 1598 }else{ 1599 char *zOrder = rbuObjIterGetPkList(p, pIter, "", ", ", " DESC"); 1600 char *zSelect = rbuObjIterGetPkList(p, pIter, "quote(", "||','||", ")"); 1601 char *zList = rbuObjIterGetPkList(p, pIter, "", ", ", ""); 1602 1603 if( p->rc==SQLITE_OK ){ 1604 p->rc = prepareFreeAndCollectError(p->dbMain, &pMax, &p->zErrmsg, 1605 sqlite3_mprintf( 1606 "SELECT %s FROM \"%s%w\" ORDER BY %s LIMIT 1", 1607 zSelect, zWrite, pIter->zTbl, zOrder 1608 ) 1609 ); 1610 if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){ 1611 const char *zVal = (const char*)sqlite3_column_text(pMax, 0); 1612 zRet = rbuMPrintf(p, " WHERE (%s) > (%s) ", zList, zVal); 1613 } 1614 rbuFinalize(p, pMax); 1615 } 1616 1617 sqlite3_free(zOrder); 1618 sqlite3_free(zSelect); 1619 sqlite3_free(zList); 1620 } 1621 return zRet; 1622 } 1623 1624 /* 1625 ** This function is called as part of restating an RBU vacuum when the 1626 ** current operation is writing content to an index. If possible, it 1627 ** queries the target index b-tree for the largest key already written to 1628 ** it, then composes and returns an expression that can be used in a WHERE 1629 ** clause to select the remaining required rows from the source table. 1630 ** It is only possible to return such an expression if: 1631 ** 1632 ** * The index contains no DESC columns, and 1633 ** * The last key written to the index before the operation was 1634 ** suspended does not contain any NULL values. 1635 ** 1636 ** The expression is of the form: 1637 ** 1638 ** (index-field1, index-field2, ...) > (?, ?, ...) 1639 ** 1640 ** except that the "?" placeholders are replaced with literal values. 1641 ** 1642 ** If the expression cannot be created, NULL is returned. In this case, 1643 ** the caller has to use an OFFSET clause to extract only the required 1644 ** rows from the sourct table, just as it does for an RBU update operation. 1645 */ 1646 static char *rbuVacuumIndexStart( 1647 sqlite3rbu *p, /* RBU handle */ 1648 RbuObjIter *pIter /* RBU iterator object */ 1649 ){ 1650 char *zOrder = 0; 1651 char *zLhs = 0; 1652 char *zSelect = 0; 1653 char *zVector = 0; 1654 char *zRet = 0; 1655 int bFailed = 0; 1656 const char *zSep = ""; 1657 int iCol = 0; 1658 sqlite3_stmt *pXInfo = 0; 1659 1660 p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg, 1661 sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter->zIdx) 1662 ); 1663 while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){ 1664 int iCid = sqlite3_column_int(pXInfo, 1); 1665 const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4); 1666 const char *zCol; 1667 if( sqlite3_column_int(pXInfo, 3) ){ 1668 bFailed = 1; 1669 break; 1670 } 1671 1672 if( iCid<0 ){ 1673 if( pIter->eType==RBU_PK_IPK ){ 1674 int i; 1675 for(i=0; pIter->abTblPk[i]==0; i++); 1676 assert( inTblCol ); 1677 zCol = pIter->azTblCol[i]; 1678 }else{ 1679 zCol = "_rowid_"; 1680 } 1681 }else{ 1682 zCol = pIter->azTblCol[iCid]; 1683 } 1684 1685 zLhs = rbuMPrintf(p, "%z%s \"%w\" COLLATE %Q", 1686 zLhs, zSep, zCol, zCollate 1687 ); 1688 zOrder = rbuMPrintf(p, "%z%s \"rbu_imp_%d%w\" COLLATE %Q DESC", 1689 zOrder, zSep, iCol, zCol, zCollate 1690 ); 1691 zSelect = rbuMPrintf(p, "%z%s quote(\"rbu_imp_%d%w\")", 1692 zSelect, zSep, iCol, zCol 1693 ); 1694 zSep = ", "; 1695 iCol++; 1696 } 1697 rbuFinalize(p, pXInfo); 1698 if( bFailed ) goto index_start_out; 1699 1700 if( p->rc==SQLITE_OK ){ 1701 sqlite3_stmt *pSel = 0; 1702 1703 p->rc = prepareFreeAndCollectError(p->dbMain, &pSel, &p->zErrmsg, 1704 sqlite3_mprintf("SELECT %s FROM \"rbu_imp_%w\" ORDER BY %s LIMIT 1", 1705 zSelect, pIter->zTbl, zOrder 1706 ) 1707 ); 1708 if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSel) ){ 1709 zSep = ""; 1710 for(iCol=0; iColnCol; iCol++){ 1711 const char *zQuoted = (const char*)sqlite3_column_text(pSel, iCol); 1712 if( zQuoted==0 ){ 1713 p->rc = SQLITE_NOMEM; 1714 }else if( zQuoted[0]=='N' ){ 1715 bFailed = 1; 1716 break; 1717 } 1718 zVector = rbuMPrintf(p, "%z%s%s", zVector, zSep, zQuoted); 1719 zSep = ", "; 1720 } 1721 1722 if( !bFailed ){ 1723 zRet = rbuMPrintf(p, "(%s) > (%s)", zLhs, zVector); 1724 } 1725 } 1726 rbuFinalize(p, pSel); 1727 } 1728 1729 index_start_out: 1730 sqlite3_free(zOrder); 1731 sqlite3_free(zSelect); 1732 sqlite3_free(zVector); 1733 sqlite3_free(zLhs); 1734 return zRet; 1735 } 1736 1737 /* 1738 ** This function is used to create a SELECT list (the list of SQL 1739 ** expressions that follows a SELECT keyword) for a SELECT statement 1740 ** used to read from an data_xxx or rbu_tmp_xxx table while updating the 1741 ** index object currently indicated by the iterator object passed as the 1742 ** second argument. A "PRAGMA index_xinfo = " statement is used 1743 ** to obtain the required information. 1744 ** 1745 ** If the index is of the following form: 1746 ** 1747 ** CREATE INDEX i1 ON t1(c, b COLLATE nocase); 1748 ** 1749 ** and "t1" is a table with an explicit INTEGER PRIMARY KEY column 1750 ** "ipk", the returned string is: 1751 ** 1752 ** "`c` COLLATE 'BINARY', `b` COLLATE 'NOCASE', `ipk` COLLATE 'BINARY'" 1753 ** 1754 ** As well as the returned string, three other malloc'd strings are 1755 ** returned via output parameters. As follows: 1756 ** 1757 ** pzImposterCols: ... 1758 ** pzImposterPk: ... 1759 ** pzWhere: ... 1760 */ 1761 static char *rbuObjIterGetIndexCols( 1762 sqlite3rbu *p, /* RBU object */ 1763 RbuObjIter *pIter, /* Object iterator for column names */ 1764 char **pzImposterCols, /* OUT: Columns for imposter table */ 1765 char **pzImposterPk, /* OUT: Imposter PK clause */ 1766 char **pzWhere, /* OUT: WHERE clause */ 1767 int *pnBind /* OUT: Trbul number of columns */ 1768 ){ 1769 int rc = p->rc; /* Error code */ 1770 int rc2; /* sqlite3_finalize() return code */ 1771 char *zRet = 0; /* String to return */ 1772 char *zImpCols = 0; /* String to return via *pzImposterCols */ 1773 char *zImpPK = 0; /* String to return via *pzImposterPK */ 1774 char *zWhere = 0; /* String to return via *pzWhere */ 1775 int nBind = 0; /* Value to return via *pnBind */ 1776 const char *zCom = ""; /* Set to ", " later on */ 1777 const char *zAnd = ""; /* Set to " AND " later on */ 1778 sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = ? */ 1779 1780 if( rc==SQLITE_OK ){ 1781 assert( p->zErrmsg==0 ); 1782 rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg, 1783 sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter->zIdx) 1784 ); 1785 } 1786 1787 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){ 1788 int iCid = sqlite3_column_int(pXInfo, 1); 1789 int bDesc = sqlite3_column_int(pXInfo, 3); 1790 const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4); 1791 const char *zCol = 0; 1792 const char *zType; 1793 1794 if( iCid==-2 ){ 1795 int iSeq = sqlite3_column_int(pXInfo, 0); 1796 zRet = sqlite3_mprintf("%z%s(%.*s) COLLATE %Q", zRet, zCom, 1797 pIter->aIdxCol[iSeq].nSpan, pIter->aIdxCol[iSeq].zSpan, zCollate 1798 ); 1799 zType = ""; 1800 }else { 1801 if( iCid<0 ){ 1802 /* An integer primary key. If the table has an explicit IPK, use 1803 ** its name. Otherwise, use "rbu_rowid". */ 1804 if( pIter->eType==RBU_PK_IPK ){ 1805 int i; 1806 for(i=0; pIter->abTblPk[i]==0; i++); 1807 assert( inTblCol ); 1808 zCol = pIter->azTblCol[i]; 1809 }else if( rbuIsVacuum(p) ){ 1810 zCol = "_rowid_"; 1811 }else{ 1812 zCol = "rbu_rowid"; 1813 } 1814 zType = "INTEGER"; 1815 }else{ 1816 zCol = pIter->azTblCol[iCid]; 1817 zType = pIter->azTblType[iCid]; 1818 } 1819 zRet = sqlite3_mprintf("%z%s\"%w\" COLLATE %Q", zRet, zCom,zCol,zCollate); 1820 } 1821 1822 if( pIter->bUnique==0 || sqlite3_column_int(pXInfo, 5) ){ 1823 const char *zOrder = (bDesc ? " DESC" : ""); 1824 zImpPK = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\"%s", 1825 zImpPK, zCom, nBind, zCol, zOrder 1826 ); 1827 } 1828 zImpCols = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\" %s COLLATE %Q", 1829 zImpCols, zCom, nBind, zCol, zType, zCollate 1830 ); 1831 zWhere = sqlite3_mprintf( 1832 "%z%s\"rbu_imp_%d%w\" IS ?", zWhere, zAnd, nBind, zCol 1833 ); 1834 if( zRet==0 || zImpPK==0 || zImpCols==0 || zWhere==0 ) rc = SQLITE_NOMEM; 1835 zCom = ", "; 1836 zAnd = " AND "; 1837 nBind++; 1838 } 1839 1840 rc2 = sqlite3_finalize(pXInfo); 1841 if( rc==SQLITE_OK ) rc = rc2; 1842 1843 if( rc!=SQLITE_OK ){ 1844 sqlite3_free(zRet); 1845 sqlite3_free(zImpCols); 1846 sqlite3_free(zImpPK); 1847 sqlite3_free(zWhere); 1848 zRet = 0; 1849 zImpCols = 0; 1850 zImpPK = 0; 1851 zWhere = 0; 1852 p->rc = rc; 1853 } 1854 1855 *pzImposterCols = zImpCols; 1856 *pzImposterPk = zImpPK; 1857 *pzWhere = zWhere; 1858 *pnBind = nBind; 1859 return zRet; 1860 } 1861 1862 /* 1863 ** Assuming the current table columns are "a", "b" and "c", and the zObj 1864 ** paramter is passed "old", return a string of the form: 1865 ** 1866 ** "old.a, old.b, old.b" 1867 ** 1868 ** With the column names escaped. 1869 ** 1870 ** For tables with implicit rowids - RBU_PK_EXTERNAL and RBU_PK_NONE, append 1871 ** the text ", old._rowid_" to the returned value. 1872 */ 1873 static char *rbuObjIterGetOldlist( 1874 sqlite3rbu *p, 1875 RbuObjIter *pIter, 1876 const char *zObj 1877 ){ 1878 char *zList = 0; 1879 if( p->rc==SQLITE_OK && pIter->abIndexed ){ 1880 const char *zS = ""; 1881 int i; 1882 for(i=0; inTblCol; i++){ 1883 if( pIter->abIndexed[i] ){ 1884 const char *zCol = pIter->azTblCol[i]; 1885 zList = sqlite3_mprintf("%z%s%s.\"%w\"", zList, zS, zObj, zCol); 1886 }else{ 1887 zList = sqlite3_mprintf("%z%sNULL", zList, zS); 1888 } 1889 zS = ", "; 1890 if( zList==0 ){ 1891 p->rc = SQLITE_NOMEM; 1892 break; 1893 } 1894 } 1895 1896 /* For a table with implicit rowids, append "old._rowid_" to the list. */ 1897 if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){ 1898 zList = rbuMPrintf(p, "%z, %s._rowid_", zList, zObj); 1899 } 1900 } 1901 return zList; 1902 } 1903 1904 /* 1905 ** Return an expression that can be used in a WHERE clause to match the 1906 ** primary key of the current table. For example, if the table is: 1907 ** 1908 ** CREATE TABLE t1(a, b, c, PRIMARY KEY(b, c)); 1909 ** 1910 ** Return the string: 1911 ** 1912 ** "b = ?1 AND c = ?2" 1913 */ 1914 static char *rbuObjIterGetWhere( 1915 sqlite3rbu *p, 1916 RbuObjIter *pIter 1917 ){ 1918 char *zList = 0; 1919 if( pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE ){ 1920 zList = rbuMPrintf(p, "_rowid_ = ?%d", pIter->nTblCol+1); 1921 }else if( pIter->eType==RBU_PK_EXTERNAL ){ 1922 const char *zSep = ""; 1923 int i; 1924 for(i=0; inTblCol; i++){ 1925 if( pIter->abTblPk[i] ){ 1926 zList = rbuMPrintf(p, "%z%sc%d=?%d", zList, zSep, i, i+1); 1927 zSep = " AND "; 1928 } 1929 } 1930 zList = rbuMPrintf(p, 1931 "_rowid_ = (SELECT id FROM rbu_imposter2 WHERE %z)", zList 1932 ); 1933 1934 }else{ 1935 const char *zSep = ""; 1936 int i; 1937 for(i=0; inTblCol; i++){ 1938 if( pIter->abTblPk[i] ){ 1939 const char *zCol = pIter->azTblCol[i]; 1940 zList = rbuMPrintf(p, "%z%s\"%w\"=?%d", zList, zSep, zCol, i+1); 1941 zSep = " AND "; 1942 } 1943 } 1944 } 1945 return zList; 1946 } 1947 1948 /* 1949 ** The SELECT statement iterating through the keys for the current object 1950 ** (p->objiter.pSelect) currently points to a valid row. However, there 1951 ** is something wrong with the rbu_control value in the rbu_control value 1952 ** stored in the (p->nCol+1)'th column. Set the error code and error message 1953 ** of the RBU handle to something reflecting this. 1954 */ 1955 static void rbuBadControlError(sqlite3rbu *p){ 1956 p->rc = SQLITE_ERROR; 1957 p->zErrmsg = sqlite3_mprintf("invalid rbu_control value"); 1958 } 1959 1960 1961 /* 1962 ** Return a nul-terminated string containing the comma separated list of 1963 ** assignments that should be included following the "SET" keyword of 1964 ** an UPDATE statement used to update the table object that the iterator 1965 ** passed as the second argument currently points to if the rbu_control 1966 ** column of the data_xxx table entry is set to zMask. 1967 ** 1968 ** The memory for the returned string is obtained from sqlite3_malloc(). 1969 ** It is the responsibility of the caller to eventually free it using 1970 ** sqlite3_free(). 1971 ** 1972 ** If an OOM error is encountered when allocating space for the new 1973 ** string, an error code is left in the rbu handle passed as the first 1974 ** argument and NULL is returned. Or, if an error has already occurred 1975 ** when this function is called, NULL is returned immediately, without 1976 ** attempting the allocation or modifying the stored error code. 1977 */ 1978 static char *rbuObjIterGetSetlist( 1979 sqlite3rbu *p, 1980 RbuObjIter *pIter, 1981 const char *zMask 1982 ){ 1983 char *zList = 0; 1984 if( p->rc==SQLITE_OK ){ 1985 int i; 1986 1987 if( (int)strlen(zMask)!=pIter->nTblCol ){ 1988 rbuBadControlError(p); 1989 }else{ 1990 const char *zSep = ""; 1991 for(i=0; inTblCol; i++){ 1992 char c = zMask[pIter->aiSrcOrder[i]]; 1993 if( c=='x' ){ 1994 zList = rbuMPrintf(p, "%z%s\"%w\"=?%d", 1995 zList, zSep, pIter->azTblCol[i], i+1 1996 ); 1997 zSep = ", "; 1998 } 1999 else if( c=='d' ){ 2000 zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_delta(\"%w\", ?%d)", 2001 zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1 2002 ); 2003 zSep = ", "; 2004 } 2005 else if( c=='f' ){ 2006 zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_fossil_delta(\"%w\", ?%d)", 2007 zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1 2008 ); 2009 zSep = ", "; 2010 } 2011 } 2012 } 2013 } 2014 return zList; 2015 } 2016 2017 /* 2018 ** Return a nul-terminated string consisting of nByte comma separated 2019 ** "?" expressions. For example, if nByte is 3, return a pointer to 2020 ** a buffer containing the string "?,?,?". 2021 ** 2022 ** The memory for the returned string is obtained from sqlite3_malloc(). 2023 ** It is the responsibility of the caller to eventually free it using 2024 ** sqlite3_free(). 2025 ** 2026 ** If an OOM error is encountered when allocating space for the new 2027 ** string, an error code is left in the rbu handle passed as the first 2028 ** argument and NULL is returned. Or, if an error has already occurred 2029 ** when this function is called, NULL is returned immediately, without 2030 ** attempting the allocation or modifying the stored error code. 2031 */ 2032 static char *rbuObjIterGetBindlist(sqlite3rbu *p, int nBind){ 2033 char *zRet = 0; 2034 sqlite3_int64 nByte = 2*(sqlite3_int64)nBind + 1; 2035 2036 zRet = (char*)rbuMalloc(p, nByte); 2037 if( zRet ){ 2038 int i; 2039 for(i=0; izIdx==0 ); 2062 if( p->rc==SQLITE_OK ){ 2063 const char *zSep = "PRIMARY KEY("; 2064 sqlite3_stmt *pXList = 0; /* PRAGMA index_list = (pIter->zTbl) */ 2065 sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = */ 2066 2067 p->rc = prepareFreeAndCollectError(p->dbMain, &pXList, &p->zErrmsg, 2068 sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl) 2069 ); 2070 while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXList) ){ 2071 const char *zOrig = (const char*)sqlite3_column_text(pXList,3); 2072 if( zOrig && strcmp(zOrig, "pk")==0 ){ 2073 const char *zIdx = (const char*)sqlite3_column_text(pXList,1); 2074 if( zIdx ){ 2075 p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg, 2076 sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx) 2077 ); 2078 } 2079 break; 2080 } 2081 } 2082 rbuFinalize(p, pXList); 2083 2084 while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){ 2085 if( sqlite3_column_int(pXInfo, 5) ){ 2086 /* int iCid = sqlite3_column_int(pXInfo, 0); */ 2087 const char *zCol = (const char*)sqlite3_column_text(pXInfo, 2); 2088 const char *zDesc = sqlite3_column_int(pXInfo, 3) ? " DESC" : ""; 2089 z = rbuMPrintf(p, "%z%s\"%w\"%s", z, zSep, zCol, zDesc); 2090 zSep = ", "; 2091 } 2092 } 2093 z = rbuMPrintf(p, "%z)", z); 2094 rbuFinalize(p, pXInfo); 2095 } 2096 return z; 2097 } 2098 2099 /* 2100 ** This function creates the second imposter table used when writing to 2101 ** a table b-tree where the table has an external primary key. If the 2102 ** iterator passed as the second argument does not currently point to 2103 ** a table (not index) with an external primary key, this function is a 2104 ** no-op. 2105 ** 2106 ** Assuming the iterator does point to a table with an external PK, this 2107 ** function creates a WITHOUT ROWID imposter table named "rbu_imposter2" 2108 ** used to access that PK index. For example, if the target table is 2109 ** declared as follows: 2110 ** 2111 ** CREATE TABLE t1(a, b TEXT, c REAL, PRIMARY KEY(b, c)); 2112 ** 2113 ** then the imposter table schema is: 2114 ** 2115 ** CREATE TABLE rbu_imposter2(c1 TEXT, c2 REAL, id INTEGER) WITHOUT ROWID; 2116 ** 2117 */ 2118 static void rbuCreateImposterTable2(sqlite3rbu *p, RbuObjIter *pIter){ 2119 if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_EXTERNAL ){ 2120 int tnum = pIter->iPkTnum; /* Root page of PK index */ 2121 sqlite3_stmt *pQuery = 0; /* SELECT name ... WHERE rootpage = $tnum */ 2122 const char *zIdx = 0; /* Name of PK index */ 2123 sqlite3_stmt *pXInfo = 0; /* PRAGMA main.index_xinfo = $zIdx */ 2124 const char *zComma = ""; 2125 char *zCols = 0; /* Used to build up list of table cols */ 2126 char *zPk = 0; /* Used to build up table PK declaration */ 2127 2128 /* Figure out the name of the primary key index for the current table. 2129 ** This is needed for the argument to "PRAGMA index_xinfo". Set 2130 ** zIdx to point to a nul-terminated string containing this name. */ 2131 p->rc = prepareAndCollectError(p->dbMain, &pQuery, &p->zErrmsg, 2132 "SELECT name FROM sqlite_schema WHERE rootpage = ?" 2133 ); 2134 if( p->rc==SQLITE_OK ){ 2135 sqlite3_bind_int(pQuery, 1, tnum); 2136 if( SQLITE_ROW==sqlite3_step(pQuery) ){ 2137 zIdx = (const char*)sqlite3_column_text(pQuery, 0); 2138 } 2139 } 2140 if( zIdx ){ 2141 p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg, 2142 sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx) 2143 ); 2144 } 2145 rbuFinalize(p, pQuery); 2146 2147 while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){ 2148 int bKey = sqlite3_column_int(pXInfo, 5); 2149 if( bKey ){ 2150 int iCid = sqlite3_column_int(pXInfo, 1); 2151 int bDesc = sqlite3_column_int(pXInfo, 3); 2152 const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4); 2153 zCols = rbuMPrintf(p, "%z%sc%d %s COLLATE %Q", zCols, zComma, 2154 iCid, pIter->azTblType[iCid], zCollate 2155 ); 2156 zPk = rbuMPrintf(p, "%z%sc%d%s", zPk, zComma, iCid, bDesc?" DESC":""); 2157 zComma = ", "; 2158 } 2159 } 2160 zCols = rbuMPrintf(p, "%z, id INTEGER", zCols); 2161 rbuFinalize(p, pXInfo); 2162 2163 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum); 2164 rbuMPrintfExec(p, p->dbMain, 2165 "CREATE TABLE rbu_imposter2(%z, PRIMARY KEY(%z)) WITHOUT ROWID", 2166 zCols, zPk 2167 ); 2168 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0); 2169 } 2170 } 2171 2172 /* 2173 ** If an error has already occurred when this function is called, it 2174 ** immediately returns zero (without doing any work). Or, if an error 2175 ** occurs during the execution of this function, it sets the error code 2176 ** in the sqlite3rbu object indicated by the first argument and returns 2177 ** zero. 2178 ** 2179 ** The iterator passed as the second argument is guaranteed to point to 2180 ** a table (not an index) when this function is called. This function 2181 ** attempts to create any imposter table required to write to the main 2182 ** table b-tree of the table before returning. Non-zero is returned if 2183 ** an imposter table are created, or zero otherwise. 2184 ** 2185 ** An imposter table is required in all cases except RBU_PK_VTAB. Only 2186 ** virtual tables are written to directly. The imposter table has the 2187 ** same schema as the actual target table (less any UNIQUE constraints). 2188 ** More precisely, the "same schema" means the same columns, types, 2189 ** collation sequences. For tables that do not have an external PRIMARY 2190 ** KEY, it also means the same PRIMARY KEY declaration. 2191 */ 2192 static void rbuCreateImposterTable(sqlite3rbu *p, RbuObjIter *pIter){ 2193 if( p->rc==SQLITE_OK && pIter->eType!=RBU_PK_VTAB ){ 2194 int tnum = pIter->iTnum; 2195 const char *zComma = ""; 2196 char *zSql = 0; 2197 int iCol; 2198 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1); 2199 2200 for(iCol=0; p->rc==SQLITE_OK && iColnTblCol; iCol++){ 2201 const char *zPk = ""; 2202 const char *zCol = pIter->azTblCol[iCol]; 2203 const char *zColl = 0; 2204 2205 p->rc = sqlite3_table_column_metadata( 2206 p->dbMain, "main", pIter->zTbl, zCol, 0, &zColl, 0, 0, 0 2207 ); 2208 2209 if( pIter->eType==RBU_PK_IPK && pIter->abTblPk[iCol] ){ 2210 /* If the target table column is an "INTEGER PRIMARY KEY", add 2211 ** "PRIMARY KEY" to the imposter table column declaration. */ 2212 zPk = "PRIMARY KEY "; 2213 } 2214 zSql = rbuMPrintf(p, "%z%s\"%w\" %s %sCOLLATE %Q%s%s%s", 2215 zSql, zComma, zCol, pIter->azTblType[iCol], zPk, zColl, 2216 (pIter->abNotNull[iCol] ? " NOT NULL" : ""), 2217 (pIter->azTblDflt[iCol] ? " DEFAULT " : ""), 2218 (pIter->azTblDflt[iCol] ? pIter->azTblDflt[iCol] : "") 2219 ); 2220 zComma = ", "; 2221 } 2222 2223 if( pIter->eType==RBU_PK_WITHOUT_ROWID ){ 2224 char *zPk = rbuWithoutRowidPK(p, pIter); 2225 if( zPk ){ 2226 zSql = rbuMPrintf(p, "%z, %z", zSql, zPk); 2227 } 2228 } 2229 2230 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum); 2231 rbuMPrintfExec(p, p->dbMain, "CREATE TABLE \"rbu_imp_%w\"(%z)%s", 2232 pIter->zTbl, zSql, 2233 (pIter->eType==RBU_PK_WITHOUT_ROWID ? " WITHOUT ROWID" : "") 2234 ); 2235 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0); 2236 } 2237 } 2238 2239 /* 2240 ** Prepare a statement used to insert rows into the "rbu_tmp_xxx" table. 2241 ** Specifically a statement of the form: 2242 ** 2243 ** INSERT INTO rbu_tmp_xxx VALUES(?, ?, ? ...); 2244 ** 2245 ** The number of bound variables is equal to the number of columns in 2246 ** the target table, plus one (for the rbu_control column), plus one more 2247 ** (for the rbu_rowid column) if the target table is an implicit IPK or 2248 ** virtual table. 2249 */ 2250 static void rbuObjIterPrepareTmpInsert( 2251 sqlite3rbu *p, 2252 RbuObjIter *pIter, 2253 const char *zCollist, 2254 const char *zRbuRowid 2255 ){ 2256 int bRbuRowid = (pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE); 2257 char *zBind = rbuObjIterGetBindlist(p, pIter->nTblCol + 1 + bRbuRowid); 2258 if( zBind ){ 2259 assert( pIter->pTmpInsert==0 ); 2260 p->rc = prepareFreeAndCollectError( 2261 p->dbRbu, &pIter->pTmpInsert, &p->zErrmsg, sqlite3_mprintf( 2262 "INSERT INTO %s.'rbu_tmp_%q'(rbu_control,%s%s) VALUES(%z)", 2263 p->zStateDb, pIter->zDataTbl, zCollist, zRbuRowid, zBind 2264 )); 2265 } 2266 } 2267 2268 static void rbuTmpInsertFunc( 2269 sqlite3_context *pCtx, 2270 int nVal, 2271 sqlite3_value **apVal 2272 ){ 2273 sqlite3rbu *p = sqlite3_user_data(pCtx); 2274 int rc = SQLITE_OK; 2275 int i; 2276 2277 assert( sqlite3_value_int(apVal[0])!=0 2278 || p->objiter.eType==RBU_PK_EXTERNAL 2279 || p->objiter.eType==RBU_PK_NONE 2280 ); 2281 if( sqlite3_value_int(apVal[0])!=0 ){ 2282 p->nPhaseOneStep += p->objiter.nIndex; 2283 } 2284 2285 for(i=0; rc==SQLITE_OK && iobjiter.pTmpInsert, i+1, apVal[i]); 2287 } 2288 if( rc==SQLITE_OK ){ 2289 sqlite3_step(p->objiter.pTmpInsert); 2290 rc = sqlite3_reset(p->objiter.pTmpInsert); 2291 } 2292 2293 if( rc!=SQLITE_OK ){ 2294 sqlite3_result_error_code(pCtx, rc); 2295 } 2296 } 2297 2298 static char *rbuObjIterGetIndexWhere(sqlite3rbu *p, RbuObjIter *pIter){ 2299 sqlite3_stmt *pStmt = 0; 2300 int rc = p->rc; 2301 char *zRet = 0; 2302 2303 assert( pIter->zIdxSql==0 && pIter->nIdxCol==0 && pIter->aIdxCol==0 ); 2304 2305 if( rc==SQLITE_OK ){ 2306 rc = prepareAndCollectError(p->dbMain, &pStmt, &p->zErrmsg, 2307 "SELECT trim(sql) FROM sqlite_schema WHERE type='index' AND name=?" 2308 ); 2309 } 2310 if( rc==SQLITE_OK ){ 2311 int rc2; 2312 rc = sqlite3_bind_text(pStmt, 1, pIter->zIdx, -1, SQLITE_STATIC); 2313 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 2314 char *zSql = (char*)sqlite3_column_text(pStmt, 0); 2315 if( zSql ){ 2316 pIter->zIdxSql = zSql = rbuStrndup(zSql, &rc); 2317 } 2318 if( zSql ){ 2319 int nParen = 0; /* Number of open parenthesis */ 2320 int i; 2321 int iIdxCol = 0; 2322 int nIdxAlloc = 0; 2323 for(i=0; zSql[i]; i++){ 2324 char c = zSql[i]; 2325 2326 /* If necessary, grow the pIter->aIdxCol[] array */ 2327 if( iIdxCol>=(nIdxAlloc-1) ){ 2328 RbuSpan *aIdxCol = (RbuSpan*)sqlite3_realloc64( 2329 pIter->aIdxCol, nIdxAlloc*sizeof(RbuSpan) + 16*sizeof(RbuSpan) 2330 ); 2331 if( aIdxCol==0 ){ 2332 rc = SQLITE_NOMEM; 2333 break; 2334 } 2335 pIter->aIdxCol = aIdxCol; 2336 nIdxAlloc += 16; 2337 } 2338 2339 if( c=='(' ){ 2340 if( nParen==0 ){ 2341 assert( iIdxCol==0 ); 2342 pIter->aIdxCol[0].zSpan = &zSql[i+1]; 2343 } 2344 nParen++; 2345 } 2346 else if( c==')' ){ 2347 nParen--; 2348 if( nParen==0 ){ 2349 int nSpan = (int)(&zSql[i] - pIter->aIdxCol[iIdxCol].zSpan); 2350 pIter->aIdxCol[iIdxCol++].nSpan = nSpan; 2351 i++; 2352 break; 2353 } 2354 }else if( c==',' && nParen==1 ){ 2355 int nSpan = (int)(&zSql[i] - pIter->aIdxCol[iIdxCol].zSpan); 2356 pIter->aIdxCol[iIdxCol++].nSpan = nSpan; 2357 pIter->aIdxCol[iIdxCol].zSpan = &zSql[i+1]; 2358 }else if( c=='"' || c=='\'' || c=='`' ){ 2359 for(i++; 1; i++){ 2360 if( zSql[i]==c ){ 2361 if( zSql[i+1]!=c ) break; 2362 i++; 2363 } 2364 } 2365 }else if( c=='[' ){ 2366 for(i++; 1; i++){ 2367 if( zSql[i]==']' ) break; 2368 } 2369 }else if( c=='-' && zSql[i+1]=='-' ){ 2370 for(i=i+2; zSql[i] && zSql[i]!='\n'; i++); 2371 if( zSql[i]=='\0' ) break; 2372 }else if( c=='/' && zSql[i+1]=='*' ){ 2373 for(i=i+2; zSql[i] && (zSql[i]!='*' || zSql[i+1]!='/'); i++); 2374 if( zSql[i]=='\0' ) break; 2375 i++; 2376 } 2377 } 2378 if( zSql[i] ){ 2379 zRet = rbuStrndup(&zSql[i], &rc); 2380 } 2381 pIter->nIdxCol = iIdxCol; 2382 } 2383 } 2384 2385 rc2 = sqlite3_finalize(pStmt); 2386 if( rc==SQLITE_OK ) rc = rc2; 2387 } 2388 2389 p->rc = rc; 2390 return zRet; 2391 } 2392 2393 /* 2394 ** Ensure that the SQLite statement handles required to update the 2395 ** target database object currently indicated by the iterator passed 2396 ** as the second argument are available. 2397 */ 2398 static int rbuObjIterPrepareAll( 2399 sqlite3rbu *p, 2400 RbuObjIter *pIter, 2401 int nOffset /* Add "LIMIT -1 OFFSET $nOffset" to SELECT */ 2402 ){ 2403 assert( pIter->bCleanup==0 ); 2404 if( pIter->pSelect==0 && rbuObjIterCacheTableInfo(p, pIter)==SQLITE_OK ){ 2405 const int tnum = pIter->iTnum; 2406 char *zCollist = 0; /* List of indexed columns */ 2407 char **pz = &p->zErrmsg; 2408 const char *zIdx = pIter->zIdx; 2409 char *zLimit = 0; 2410 2411 if( nOffset ){ 2412 zLimit = sqlite3_mprintf(" LIMIT -1 OFFSET %d", nOffset); 2413 if( !zLimit ) p->rc = SQLITE_NOMEM; 2414 } 2415 2416 if( zIdx ){ 2417 const char *zTbl = pIter->zTbl; 2418 char *zImposterCols = 0; /* Columns for imposter table */ 2419 char *zImposterPK = 0; /* Primary key declaration for imposter */ 2420 char *zWhere = 0; /* WHERE clause on PK columns */ 2421 char *zBind = 0; 2422 char *zPart = 0; 2423 int nBind = 0; 2424 2425 assert( pIter->eType!=RBU_PK_VTAB ); 2426 zPart = rbuObjIterGetIndexWhere(p, pIter); 2427 zCollist = rbuObjIterGetIndexCols( 2428 p, pIter, &zImposterCols, &zImposterPK, &zWhere, &nBind 2429 ); 2430 zBind = rbuObjIterGetBindlist(p, nBind); 2431 2432 /* Create the imposter table used to write to this index. */ 2433 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1); 2434 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1,tnum); 2435 rbuMPrintfExec(p, p->dbMain, 2436 "CREATE TABLE \"rbu_imp_%w\"( %s, PRIMARY KEY( %s ) ) WITHOUT ROWID", 2437 zTbl, zImposterCols, zImposterPK 2438 ); 2439 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0); 2440 2441 /* Create the statement to insert index entries */ 2442 pIter->nCol = nBind; 2443 if( p->rc==SQLITE_OK ){ 2444 p->rc = prepareFreeAndCollectError( 2445 p->dbMain, &pIter->pInsert, &p->zErrmsg, 2446 sqlite3_mprintf("INSERT INTO \"rbu_imp_%w\" VALUES(%s)", zTbl, zBind) 2447 ); 2448 } 2449 2450 /* And to delete index entries */ 2451 if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){ 2452 p->rc = prepareFreeAndCollectError( 2453 p->dbMain, &pIter->pDelete, &p->zErrmsg, 2454 sqlite3_mprintf("DELETE FROM \"rbu_imp_%w\" WHERE %s", zTbl, zWhere) 2455 ); 2456 } 2457 2458 /* Create the SELECT statement to read keys in sorted order */ 2459 if( p->rc==SQLITE_OK ){ 2460 char *zSql; 2461 if( rbuIsVacuum(p) ){ 2462 char *zStart = 0; 2463 if( nOffset ){ 2464 zStart = rbuVacuumIndexStart(p, pIter); 2465 if( zStart ){ 2466 sqlite3_free(zLimit); 2467 zLimit = 0; 2468 } 2469 } 2470 2471 zSql = sqlite3_mprintf( 2472 "SELECT %s, 0 AS rbu_control FROM '%q' %s %s %s ORDER BY %s%s", 2473 zCollist, 2474 pIter->zDataTbl, 2475 zPart, 2476 (zStart ? (zPart ? "AND" : "WHERE") : ""), zStart, 2477 zCollist, zLimit 2478 ); 2479 sqlite3_free(zStart); 2480 }else 2481 2482 if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){ 2483 zSql = sqlite3_mprintf( 2484 "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' %s ORDER BY %s%s", 2485 zCollist, p->zStateDb, pIter->zDataTbl, 2486 zPart, zCollist, zLimit 2487 ); 2488 }else{ 2489 zSql = sqlite3_mprintf( 2490 "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' %s " 2491 "UNION ALL " 2492 "SELECT %s, rbu_control FROM '%q' " 2493 "%s %s typeof(rbu_control)='integer' AND rbu_control!=1 " 2494 "ORDER BY %s%s", 2495 zCollist, p->zStateDb, pIter->zDataTbl, zPart, 2496 zCollist, pIter->zDataTbl, 2497 zPart, 2498 (zPart ? "AND" : "WHERE"), 2499 zCollist, zLimit 2500 ); 2501 } 2502 if( p->rc==SQLITE_OK ){ 2503 p->rc = prepareFreeAndCollectError(p->dbRbu,&pIter->pSelect,pz,zSql); 2504 }else{ 2505 sqlite3_free(zSql); 2506 } 2507 } 2508 2509 sqlite3_free(zImposterCols); 2510 sqlite3_free(zImposterPK); 2511 sqlite3_free(zWhere); 2512 sqlite3_free(zBind); 2513 sqlite3_free(zPart); 2514 }else{ 2515 int bRbuRowid = (pIter->eType==RBU_PK_VTAB) 2516 ||(pIter->eType==RBU_PK_NONE) 2517 ||(pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p)); 2518 const char *zTbl = pIter->zTbl; /* Table this step applies to */ 2519 const char *zWrite; /* Imposter table name */ 2520 2521 char *zBindings = rbuObjIterGetBindlist(p, pIter->nTblCol + bRbuRowid); 2522 char *zWhere = rbuObjIterGetWhere(p, pIter); 2523 char *zOldlist = rbuObjIterGetOldlist(p, pIter, "old"); 2524 char *zNewlist = rbuObjIterGetOldlist(p, pIter, "new"); 2525 2526 zCollist = rbuObjIterGetCollist(p, pIter); 2527 pIter->nCol = pIter->nTblCol; 2528 2529 /* Create the imposter table or tables (if required). */ 2530 rbuCreateImposterTable(p, pIter); 2531 rbuCreateImposterTable2(p, pIter); 2532 zWrite = (pIter->eType==RBU_PK_VTAB ? "" : "rbu_imp_"); 2533 2534 /* Create the INSERT statement to write to the target PK b-tree */ 2535 if( p->rc==SQLITE_OK ){ 2536 p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pInsert, pz, 2537 sqlite3_mprintf( 2538 "INSERT INTO \"%s%w\"(%s%s) VALUES(%s)", 2539 zWrite, zTbl, zCollist, (bRbuRowid ? ", _rowid_" : ""), zBindings 2540 ) 2541 ); 2542 } 2543 2544 /* Create the DELETE statement to write to the target PK b-tree. 2545 ** Because it only performs INSERT operations, this is not required for 2546 ** an rbu vacuum handle. */ 2547 if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){ 2548 p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pDelete, pz, 2549 sqlite3_mprintf( 2550 "DELETE FROM \"%s%w\" WHERE %s", zWrite, zTbl, zWhere 2551 ) 2552 ); 2553 } 2554 2555 if( rbuIsVacuum(p)==0 && pIter->abIndexed ){ 2556 const char *zRbuRowid = ""; 2557 if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){ 2558 zRbuRowid = ", rbu_rowid"; 2559 } 2560 2561 /* Create the rbu_tmp_xxx table and the triggers to populate it. */ 2562 rbuMPrintfExec(p, p->dbRbu, 2563 "CREATE TABLE IF NOT EXISTS %s.'rbu_tmp_%q' AS " 2564 "SELECT *%s FROM '%q' WHERE 0;" 2565 , p->zStateDb, pIter->zDataTbl 2566 , (pIter->eType==RBU_PK_EXTERNAL ? ", 0 AS rbu_rowid" : "") 2567 , pIter->zDataTbl 2568 ); 2569 2570 rbuMPrintfExec(p, p->dbMain, 2571 "CREATE TEMP TRIGGER rbu_delete_tr BEFORE DELETE ON \"%s%w\" " 2572 "BEGIN " 2573 " SELECT rbu_tmp_insert(3, %s);" 2574 "END;" 2575 2576 "CREATE TEMP TRIGGER rbu_update1_tr BEFORE UPDATE ON \"%s%w\" " 2577 "BEGIN " 2578 " SELECT rbu_tmp_insert(3, %s);" 2579 "END;" 2580 2581 "CREATE TEMP TRIGGER rbu_update2_tr AFTER UPDATE ON \"%s%w\" " 2582 "BEGIN " 2583 " SELECT rbu_tmp_insert(4, %s);" 2584 "END;", 2585 zWrite, zTbl, zOldlist, 2586 zWrite, zTbl, zOldlist, 2587 zWrite, zTbl, zNewlist 2588 ); 2589 2590 if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){ 2591 rbuMPrintfExec(p, p->dbMain, 2592 "CREATE TEMP TRIGGER rbu_insert_tr AFTER INSERT ON \"%s%w\" " 2593 "BEGIN " 2594 " SELECT rbu_tmp_insert(0, %s);" 2595 "END;", 2596 zWrite, zTbl, zNewlist 2597 ); 2598 } 2599 2600 rbuObjIterPrepareTmpInsert(p, pIter, zCollist, zRbuRowid); 2601 } 2602 2603 /* Create the SELECT statement to read keys from data_xxx */ 2604 if( p->rc==SQLITE_OK ){ 2605 const char *zRbuRowid = ""; 2606 char *zStart = 0; 2607 char *zOrder = 0; 2608 if( bRbuRowid ){ 2609 zRbuRowid = rbuIsVacuum(p) ? ",_rowid_ " : ",rbu_rowid"; 2610 } 2611 2612 if( rbuIsVacuum(p) ){ 2613 if( nOffset ){ 2614 zStart = rbuVacuumTableStart(p, pIter, bRbuRowid, zWrite); 2615 if( zStart ){ 2616 sqlite3_free(zLimit); 2617 zLimit = 0; 2618 } 2619 } 2620 if( bRbuRowid ){ 2621 zOrder = rbuMPrintf(p, "_rowid_"); 2622 }else{ 2623 zOrder = rbuObjIterGetPkList(p, pIter, "", ", ", ""); 2624 } 2625 } 2626 2627 if( p->rc==SQLITE_OK ){ 2628 p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz, 2629 sqlite3_mprintf( 2630 "SELECT %s,%s rbu_control%s FROM '%q'%s %s %s %s", 2631 zCollist, 2632 (rbuIsVacuum(p) ? "0 AS " : ""), 2633 zRbuRowid, 2634 pIter->zDataTbl, (zStart ? zStart : ""), 2635 (zOrder ? "ORDER BY" : ""), zOrder, 2636 zLimit 2637 ) 2638 ); 2639 } 2640 sqlite3_free(zStart); 2641 sqlite3_free(zOrder); 2642 } 2643 2644 sqlite3_free(zWhere); 2645 sqlite3_free(zOldlist); 2646 sqlite3_free(zNewlist); 2647 sqlite3_free(zBindings); 2648 } 2649 sqlite3_free(zCollist); 2650 sqlite3_free(zLimit); 2651 } 2652 2653 return p->rc; 2654 } 2655 2656 /* 2657 ** Set output variable *ppStmt to point to an UPDATE statement that may 2658 ** be used to update the imposter table for the main table b-tree of the 2659 ** table object that pIter currently points to, assuming that the 2660 ** rbu_control column of the data_xyz table contains zMask. 2661 ** 2662 ** If the zMask string does not specify any columns to update, then this 2663 ** is not an error. Output variable *ppStmt is set to NULL in this case. 2664 */ 2665 static int rbuGetUpdateStmt( 2666 sqlite3rbu *p, /* RBU handle */ 2667 RbuObjIter *pIter, /* Object iterator */ 2668 const char *zMask, /* rbu_control value ('x.x.') */ 2669 sqlite3_stmt **ppStmt /* OUT: UPDATE statement handle */ 2670 ){ 2671 RbuUpdateStmt **pp; 2672 RbuUpdateStmt *pUp = 0; 2673 int nUp = 0; 2674 2675 /* In case an error occurs */ 2676 *ppStmt = 0; 2677 2678 /* Search for an existing statement. If one is found, shift it to the front 2679 ** of the LRU queue and return immediately. Otherwise, leave nUp pointing 2680 ** to the number of statements currently in the cache and pUp to the 2681 ** last object in the list. */ 2682 for(pp=&pIter->pRbuUpdate; *pp; pp=&((*pp)->pNext)){ 2683 pUp = *pp; 2684 if( strcmp(pUp->zMask, zMask)==0 ){ 2685 *pp = pUp->pNext; 2686 pUp->pNext = pIter->pRbuUpdate; 2687 pIter->pRbuUpdate = pUp; 2688 *ppStmt = pUp->pUpdate; 2689 return SQLITE_OK; 2690 } 2691 nUp++; 2692 } 2693 assert( pUp==0 || pUp->pNext==0 ); 2694 2695 if( nUp>=SQLITE_RBU_UPDATE_CACHESIZE ){ 2696 for(pp=&pIter->pRbuUpdate; *pp!=pUp; pp=&((*pp)->pNext)); 2697 *pp = 0; 2698 sqlite3_finalize(pUp->pUpdate); 2699 pUp->pUpdate = 0; 2700 }else{ 2701 pUp = (RbuUpdateStmt*)rbuMalloc(p, sizeof(RbuUpdateStmt)+pIter->nTblCol+1); 2702 } 2703 2704 if( pUp ){ 2705 char *zWhere = rbuObjIterGetWhere(p, pIter); 2706 char *zSet = rbuObjIterGetSetlist(p, pIter, zMask); 2707 char *zUpdate = 0; 2708 2709 pUp->zMask = (char*)&pUp[1]; 2710 pUp->pNext = pIter->pRbuUpdate; 2711 pIter->pRbuUpdate = pUp; 2712 2713 if( zSet ){ 2714 const char *zPrefix = ""; 2715 assert( p->rc==SQLITE_OK ); 2716 memcpy(pUp->zMask, zMask, pIter->nTblCol); 2717 if( pIter->eType!=RBU_PK_VTAB ) zPrefix = "rbu_imp_"; 2718 zUpdate = sqlite3_mprintf("UPDATE \"%s%w\" SET %s WHERE %s", 2719 zPrefix, pIter->zTbl, zSet, zWhere 2720 ); 2721 p->rc = prepareFreeAndCollectError( 2722 p->dbMain, &pUp->pUpdate, &p->zErrmsg, zUpdate 2723 ); 2724 *ppStmt = pUp->pUpdate; 2725 } 2726 sqlite3_free(zWhere); 2727 sqlite3_free(zSet); 2728 } 2729 2730 return p->rc; 2731 } 2732 2733 static sqlite3 *rbuOpenDbhandle( 2734 sqlite3rbu *p, 2735 const char *zName, 2736 int bUseVfs 2737 ){ 2738 sqlite3 *db = 0; 2739 if( p->rc==SQLITE_OK ){ 2740 const int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_URI; 2741 p->rc = sqlite3_open_v2(zName, &db, flags, bUseVfs ? p->zVfsName : 0); 2742 if( p->rc ){ 2743 p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db)); 2744 sqlite3_close(db); 2745 db = 0; 2746 } 2747 } 2748 return db; 2749 } 2750 2751 /* 2752 ** Free an RbuState object allocated by rbuLoadState(). 2753 */ 2754 static void rbuFreeState(RbuState *p){ 2755 if( p ){ 2756 sqlite3_free(p->zTbl); 2757 sqlite3_free(p->zDataTbl); 2758 sqlite3_free(p->zIdx); 2759 sqlite3_free(p); 2760 } 2761 } 2762 2763 /* 2764 ** Allocate an RbuState object and load the contents of the rbu_state 2765 ** table into it. Return a pointer to the new object. It is the 2766 ** responsibility of the caller to eventually free the object using 2767 ** sqlite3_free(). 2768 ** 2769 ** If an error occurs, leave an error code and message in the rbu handle 2770 ** and return NULL. 2771 */ 2772 static RbuState *rbuLoadState(sqlite3rbu *p){ 2773 RbuState *pRet = 0; 2774 sqlite3_stmt *pStmt = 0; 2775 int rc; 2776 int rc2; 2777 2778 pRet = (RbuState*)rbuMalloc(p, sizeof(RbuState)); 2779 if( pRet==0 ) return 0; 2780 2781 rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg, 2782 sqlite3_mprintf("SELECT k, v FROM %s.rbu_state", p->zStateDb) 2783 ); 2784 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 2785 switch( sqlite3_column_int(pStmt, 0) ){ 2786 case RBU_STATE_STAGE: 2787 pRet->eStage = sqlite3_column_int(pStmt, 1); 2788 if( pRet->eStage!=RBU_STAGE_OAL 2789 && pRet->eStage!=RBU_STAGE_MOVE 2790 && pRet->eStage!=RBU_STAGE_CKPT 2791 ){ 2792 p->rc = SQLITE_CORRUPT; 2793 } 2794 break; 2795 2796 case RBU_STATE_TBL: 2797 pRet->zTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc); 2798 break; 2799 2800 case RBU_STATE_IDX: 2801 pRet->zIdx = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc); 2802 break; 2803 2804 case RBU_STATE_ROW: 2805 pRet->nRow = sqlite3_column_int(pStmt, 1); 2806 if( pRet->nRow<0 ){ 2807 rc = SQLITE_CORRUPT; 2808 } 2809 break; 2810 2811 case RBU_STATE_PROGRESS: 2812 pRet->nProgress = sqlite3_column_int64(pStmt, 1); 2813 break; 2814 2815 case RBU_STATE_CKPT: 2816 pRet->iWalCksum = sqlite3_column_int64(pStmt, 1); 2817 break; 2818 2819 case RBU_STATE_COOKIE: 2820 pRet->iCookie = (u32)sqlite3_column_int64(pStmt, 1); 2821 break; 2822 2823 case RBU_STATE_OALSZ: 2824 pRet->iOalSz = sqlite3_column_int64(pStmt, 1); 2825 break; 2826 2827 case RBU_STATE_PHASEONESTEP: 2828 pRet->nPhaseOneStep = sqlite3_column_int64(pStmt, 1); 2829 break; 2830 2831 case RBU_STATE_DATATBL: 2832 pRet->zDataTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc); 2833 break; 2834 2835 default: 2836 rc = SQLITE_CORRUPT; 2837 break; 2838 } 2839 } 2840 rc2 = sqlite3_finalize(pStmt); 2841 if( rc==SQLITE_OK ) rc = rc2; 2842 2843 p->rc = rc; 2844 return pRet; 2845 } 2846 2847 2848 /* 2849 ** Open the database handle and attach the RBU database as "rbu". If an 2850 ** error occurs, leave an error code and message in the RBU handle. 2851 ** 2852 ** If argument dbMain is not NULL, then it is a database handle already 2853 ** open on the target database. Use this handle instead of opening a new 2854 ** one. 2855 */ 2856 static void rbuOpenDatabase(sqlite3rbu *p, sqlite3 *dbMain, int *pbRetry){ 2857 assert( p->rc || (p->dbMain==0 && p->dbRbu==0) ); 2858 assert( p->rc || rbuIsVacuum(p) || p->zTarget!=0 ); 2859 assert( dbMain==0 || rbuIsVacuum(p)==0 ); 2860 2861 /* Open the RBU database */ 2862 p->dbRbu = rbuOpenDbhandle(p, p->zRbu, 1); 2863 p->dbMain = dbMain; 2864 2865 if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){ 2866 sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p); 2867 if( p->zState==0 ){ 2868 const char *zFile = sqlite3_db_filename(p->dbRbu, "main"); 2869 p->zState = rbuMPrintf(p, "file:///%s-vacuum?modeof=%s", zFile, zFile); 2870 } 2871 } 2872 2873 /* If using separate RBU and state databases, attach the state database to 2874 ** the RBU db handle now. */ 2875 if( p->zState ){ 2876 rbuMPrintfExec(p, p->dbRbu, "ATTACH %Q AS stat", p->zState); 2877 memcpy(p->zStateDb, "stat", 4); 2878 }else{ 2879 memcpy(p->zStateDb, "main", 4); 2880 } 2881 2882 #if 0 2883 if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){ 2884 p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, 0); 2885 } 2886 #endif 2887 2888 /* If it has not already been created, create the rbu_state table */ 2889 rbuMPrintfExec(p, p->dbRbu, RBU_CREATE_STATE, p->zStateDb); 2890 2891 #if 0 2892 if( rbuIsVacuum(p) ){ 2893 if( p->rc==SQLITE_OK ){ 2894 int rc2; 2895 int bOk = 0; 2896 sqlite3_stmt *pCnt = 0; 2897 p->rc = prepareAndCollectError(p->dbRbu, &pCnt, &p->zErrmsg, 2898 "SELECT count(*) FROM stat.sqlite_schema" 2899 ); 2900 if( p->rc==SQLITE_OK 2901 && sqlite3_step(pCnt)==SQLITE_ROW 2902 && 1==sqlite3_column_int(pCnt, 0) 2903 ){ 2904 bOk = 1; 2905 } 2906 rc2 = sqlite3_finalize(pCnt); 2907 if( p->rc==SQLITE_OK ) p->rc = rc2; 2908 2909 if( p->rc==SQLITE_OK && bOk==0 ){ 2910 p->rc = SQLITE_ERROR; 2911 p->zErrmsg = sqlite3_mprintf("invalid state database"); 2912 } 2913 2914 if( p->rc==SQLITE_OK ){ 2915 p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0); 2916 } 2917 } 2918 } 2919 #endif 2920 2921 if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){ 2922 int bOpen = 0; 2923 int rc; 2924 p->nRbu = 0; 2925 p->pRbuFd = 0; 2926 rc = sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p); 2927 if( rc!=SQLITE_NOTFOUND || p->pRbuFd==0 ) p->rc = rc; 2928 if( p->eStage>=RBU_STAGE_MOVE ){ 2929 bOpen = 1; 2930 }else{ 2931 RbuState *pState = rbuLoadState(p); 2932 if( pState ){ 2933 bOpen = (pState->eStage>=RBU_STAGE_MOVE); 2934 rbuFreeState(pState); 2935 } 2936 } 2937 if( bOpen ) p->dbMain = rbuOpenDbhandle(p, p->zRbu, p->nRbu<=1); 2938 } 2939 2940 p->eStage = 0; 2941 if( p->rc==SQLITE_OK && p->dbMain==0 ){ 2942 if( !rbuIsVacuum(p) ){ 2943 p->dbMain = rbuOpenDbhandle(p, p->zTarget, 1); 2944 }else if( p->pRbuFd->pWalFd ){ 2945 if( pbRetry ){ 2946 p->pRbuFd->bNolock = 0; 2947 sqlite3_close(p->dbRbu); 2948 sqlite3_close(p->dbMain); 2949 p->dbMain = 0; 2950 p->dbRbu = 0; 2951 *pbRetry = 1; 2952 return; 2953 } 2954 p->rc = SQLITE_ERROR; 2955 p->zErrmsg = sqlite3_mprintf("cannot vacuum wal mode database"); 2956 }else{ 2957 char *zTarget; 2958 char *zExtra = 0; 2959 if( strlen(p->zRbu)>=5 && 0==memcmp("file:", p->zRbu, 5) ){ 2960 zExtra = &p->zRbu[5]; 2961 while( *zExtra ){ 2962 if( *zExtra++=='?' ) break; 2963 } 2964 if( *zExtra=='\0' ) zExtra = 0; 2965 } 2966 2967 zTarget = sqlite3_mprintf("file:%s-vactmp?rbu_memory=1%s%s", 2968 sqlite3_db_filename(p->dbRbu, "main"), 2969 (zExtra==0 ? "" : "&"), (zExtra==0 ? "" : zExtra) 2970 ); 2971 2972 if( zTarget==0 ){ 2973 p->rc = SQLITE_NOMEM; 2974 return; 2975 } 2976 p->dbMain = rbuOpenDbhandle(p, zTarget, p->nRbu<=1); 2977 sqlite3_free(zTarget); 2978 } 2979 } 2980 2981 if( p->rc==SQLITE_OK ){ 2982 p->rc = sqlite3_create_function(p->dbMain, 2983 "rbu_tmp_insert", -1, SQLITE_UTF8, (void*)p, rbuTmpInsertFunc, 0, 0 2984 ); 2985 } 2986 2987 if( p->rc==SQLITE_OK ){ 2988 p->rc = sqlite3_create_function(p->dbMain, 2989 "rbu_fossil_delta", 2, SQLITE_UTF8, 0, rbuFossilDeltaFunc, 0, 0 2990 ); 2991 } 2992 2993 if( p->rc==SQLITE_OK ){ 2994 p->rc = sqlite3_create_function(p->dbRbu, 2995 "rbu_target_name", -1, SQLITE_UTF8, (void*)p, rbuTargetNameFunc, 0, 0 2996 ); 2997 } 2998 2999 if( p->rc==SQLITE_OK ){ 3000 p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p); 3001 } 3002 rbuMPrintfExec(p, p->dbMain, "SELECT * FROM sqlite_schema"); 3003 3004 /* Mark the database file just opened as an RBU target database. If 3005 ** this call returns SQLITE_NOTFOUND, then the RBU vfs is not in use. 3006 ** This is an error. */ 3007 if( p->rc==SQLITE_OK ){ 3008 p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p); 3009 } 3010 3011 if( p->rc==SQLITE_NOTFOUND ){ 3012 p->rc = SQLITE_ERROR; 3013 p->zErrmsg = sqlite3_mprintf("rbu vfs not found"); 3014 } 3015 } 3016 3017 /* 3018 ** This routine is a copy of the sqlite3FileSuffix3() routine from the core. 3019 ** It is a no-op unless SQLITE_ENABLE_8_3_NAMES is defined. 3020 ** 3021 ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database 3022 ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and 3023 ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than 3024 ** three characters, then shorten the suffix on z[] to be the last three 3025 ** characters of the original suffix. 3026 ** 3027 ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always 3028 ** do the suffix shortening regardless of URI parameter. 3029 ** 3030 ** Examples: 3031 ** 3032 ** test.db-journal => test.nal 3033 ** test.db-wal => test.wal 3034 ** test.db-shm => test.shm 3035 ** test.db-mj7f3319fa => test.9fa 3036 */ 3037 static void rbuFileSuffix3(const char *zBase, char *z){ 3038 #ifdef SQLITE_ENABLE_8_3_NAMES 3039 #if SQLITE_ENABLE_8_3_NAMES<2 3040 if( sqlite3_uri_boolean(zBase, "8_3_names", 0) ) 3041 #endif 3042 { 3043 int i, sz; 3044 sz = (int)strlen(z)&0xffffff; 3045 for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){} 3046 if( z[i]=='.' && sz>i+4 ) memmove(&z[i+1], &z[sz-3], 4); 3047 } 3048 #else 3049 UNUSED_PARAMETER2(zBase,z); 3050 #endif 3051 } 3052 3053 /* 3054 ** Return the current wal-index header checksum for the target database 3055 ** as a 64-bit integer. 3056 ** 3057 ** The checksum is store in the first page of xShmMap memory as an 8-byte 3058 ** blob starting at byte offset 40. 3059 */ 3060 static i64 rbuShmChecksum(sqlite3rbu *p){ 3061 i64 iRet = 0; 3062 if( p->rc==SQLITE_OK ){ 3063 sqlite3_file *pDb = p->pTargetFd->pReal; 3064 u32 volatile *ptr; 3065 p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, (void volatile**)&ptr); 3066 if( p->rc==SQLITE_OK ){ 3067 iRet = (i64)(((u64)ptr[10] << 32) + ptr[11]); 3068 } 3069 } 3070 return iRet; 3071 } 3072 3073 /* 3074 ** This function is called as part of initializing or reinitializing an 3075 ** incremental checkpoint. 3076 ** 3077 ** It populates the sqlite3rbu.aFrame[] array with the set of 3078 ** (wal frame -> db page) copy operations required to checkpoint the 3079 ** current wal file, and obtains the set of shm locks required to safely 3080 ** perform the copy operations directly on the file-system. 3081 ** 3082 ** If argument pState is not NULL, then the incremental checkpoint is 3083 ** being resumed. In this case, if the checksum of the wal-index-header 3084 ** following recovery is not the same as the checksum saved in the RbuState 3085 ** object, then the rbu handle is set to DONE state. This occurs if some 3086 ** other client appends a transaction to the wal file in the middle of 3087 ** an incremental checkpoint. 3088 */ 3089 static void rbuSetupCheckpoint(sqlite3rbu *p, RbuState *pState){ 3090 3091 /* If pState is NULL, then the wal file may not have been opened and 3092 ** recovered. Running a read-statement here to ensure that doing so 3093 ** does not interfere with the "capture" process below. */ 3094 if( pState==0 ){ 3095 p->eStage = 0; 3096 if( p->rc==SQLITE_OK ){ 3097 p->rc = sqlite3_exec(p->dbMain, "SELECT * FROM sqlite_schema", 0, 0, 0); 3098 } 3099 } 3100 3101 /* Assuming no error has occurred, run a "restart" checkpoint with the 3102 ** sqlite3rbu.eStage variable set to CAPTURE. This turns on the following 3103 ** special behaviour in the rbu VFS: 3104 ** 3105 ** * If the exclusive shm WRITER or READ0 lock cannot be obtained, 3106 ** the checkpoint fails with SQLITE_BUSY (normally SQLite would 3107 ** proceed with running a passive checkpoint instead of failing). 3108 ** 3109 ** * Attempts to read from the *-wal file or write to the database file 3110 ** do not perform any IO. Instead, the frame/page combinations that 3111 ** would be read/written are recorded in the sqlite3rbu.aFrame[] 3112 ** array. 3113 ** 3114 ** * Calls to xShmLock(UNLOCK) to release the exclusive shm WRITER, 3115 ** READ0 and CHECKPOINT locks taken as part of the checkpoint are 3116 ** no-ops. These locks will not be released until the connection 3117 ** is closed. 3118 ** 3119 ** * Attempting to xSync() the database file causes an SQLITE_NOTICE 3120 ** error. 3121 ** 3122 ** As a result, unless an error (i.e. OOM or SQLITE_BUSY) occurs, the 3123 ** checkpoint below fails with SQLITE_NOTICE, and leaves the aFrame[] 3124 ** array populated with a set of (frame -> page) mappings. Because the 3125 ** WRITER, CHECKPOINT and READ0 locks are still held, it is safe to copy 3126 ** data from the wal file into the database file according to the 3127 ** contents of aFrame[]. 3128 */ 3129 if( p->rc==SQLITE_OK ){ 3130 int rc2; 3131 p->eStage = RBU_STAGE_CAPTURE; 3132 rc2 = sqlite3_exec(p->dbMain, "PRAGMA main.wal_checkpoint=restart", 0, 0,0); 3133 if( rc2!=SQLITE_NOTICE ) p->rc = rc2; 3134 } 3135 3136 if( p->rc==SQLITE_OK && p->nFrame>0 ){ 3137 p->eStage = RBU_STAGE_CKPT; 3138 p->nStep = (pState ? pState->nRow : 0); 3139 p->aBuf = rbuMalloc(p, p->pgsz); 3140 p->iWalCksum = rbuShmChecksum(p); 3141 } 3142 3143 if( p->rc==SQLITE_OK ){ 3144 if( p->nFrame==0 || (pState && pState->iWalCksum!=p->iWalCksum) ){ 3145 p->rc = SQLITE_DONE; 3146 p->eStage = RBU_STAGE_DONE; 3147 }else{ 3148 int nSectorSize; 3149 sqlite3_file *pDb = p->pTargetFd->pReal; 3150 sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal; 3151 assert( p->nPagePerSector==0 ); 3152 nSectorSize = pDb->pMethods->xSectorSize(pDb); 3153 if( nSectorSize>p->pgsz ){ 3154 p->nPagePerSector = nSectorSize / p->pgsz; 3155 }else{ 3156 p->nPagePerSector = 1; 3157 } 3158 3159 /* Call xSync() on the wal file. This causes SQLite to sync the 3160 ** directory in which the target database and the wal file reside, in 3161 ** case it has not been synced since the rename() call in 3162 ** rbuMoveOalFile(). */ 3163 p->rc = pWal->pMethods->xSync(pWal, SQLITE_SYNC_NORMAL); 3164 } 3165 } 3166 } 3167 3168 /* 3169 ** Called when iAmt bytes are read from offset iOff of the wal file while 3170 ** the rbu object is in capture mode. Record the frame number of the frame 3171 ** being read in the aFrame[] array. 3172 */ 3173 static int rbuCaptureWalRead(sqlite3rbu *pRbu, i64 iOff, int iAmt){ 3174 const u32 mReq = (1<mLock!=mReq ){ 3178 pRbu->rc = SQLITE_BUSY; 3179 return SQLITE_NOTICE_RBU; 3180 } 3181 3182 pRbu->pgsz = iAmt; 3183 if( pRbu->nFrame==pRbu->nFrameAlloc ){ 3184 int nNew = (pRbu->nFrameAlloc ? pRbu->nFrameAlloc : 64) * 2; 3185 RbuFrame *aNew; 3186 aNew = (RbuFrame*)sqlite3_realloc64(pRbu->aFrame, nNew * sizeof(RbuFrame)); 3187 if( aNew==0 ) return SQLITE_NOMEM; 3188 pRbu->aFrame = aNew; 3189 pRbu->nFrameAlloc = nNew; 3190 } 3191 3192 iFrame = (u32)((iOff-32) / (i64)(iAmt+24)) + 1; 3193 if( pRbu->iMaxFrame