4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
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.
11 *************************************************************************
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.
23 ** The update proceeds in three stages:
25 ** 1) The database is updated. The modified database pages are written
26 ** to a *-oal file. A *-oal file is just like a *-wal file, except
27 ** that it is named "<database>-oal" instead of "<database>-wal".
28 ** Because regular SQLite clients do not look for file named
29 ** "<database>-oal", they go on using the original database in
30 ** rollback mode while the *-oal file is being generated.
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.
39 ** 2) The "<database>-oal" file is moved to the equivalent "<database>-wal"
40 ** location using a call to rename(2). Before doing this the RBU
41 ** module takes an EXCLUSIVE lock on the database file, ensuring
42 ** that there are no other active readers.
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.
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
59 ** The rename() call might not be portable. And RBU is not currently
60 ** syncing the directory after renaming the file.
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).
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.
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.
89 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU)
90 #include "sqlite3rbu.h"
92 #if defined(_WIN32_WCE)
96 /* Maximum number of prepared UPDATE statements held by this module */
97 #define SQLITE_RBU_UPDATE_CACHESIZE 16
99 /* Delta checksums disabled by default. Compile with -DRBU_ENABLE_DELTA_CKSUM
100 ** to enable checksum verification.
102 #ifndef RBU_ENABLE_DELTA_CKSUM
103 # define RBU_ENABLE_DELTA_CKSUM 0
107 ** Swap two objects of type TYPE.
109 #if !defined(SQLITE_AMALGAMATION)
110 # define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
114 ** Name of the URI option that causes RBU to take an exclusive lock as
115 ** part of the incremental checkpoint operation.
117 #define RBU_EXCLUSIVE_CHECKPOINT "rbu_exclusive_checkpoint"
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:
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.
134 ** Only valid if STAGE==1. The target database name of the table
135 ** currently being written.
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
143 ** Only valid if STAGE==1. Number of rows already processed for the current
146 ** RBU_STATE_PROGRESS:
147 ** Trbul number of sqlite3rbu_step() calls made so far as part of this
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).
158 ** Valid if STAGE==1. The current change-counter cookie value in the
162 ** Valid if STAGE==1. The size in bytes of the *-oal file.
164 ** RBU_STATE_DATATBL:
165 ** Only valid if STAGE==1. The RBU database name of the table
166 ** currently being read.
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
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
186 #define RBU_CREATE_STATE \
187 "CREATE TABLE IF NOT EXISTS %s.rbu_state(k INTEGER PRIMARY KEY, v)"
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
;
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
;
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
210 #define WAL_LOCK_WRITE 0
211 #define WAL_LOCK_CKPT 1
212 #define WAL_LOCK_READ0 3
214 #define SQLITE_FCNTL_RBUCNT 5149216
217 ** A structure to store values read from the rbu_state table in memory.
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
;
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:
248 ** * the table itself,
249 ** * each index of the table (zero or more points to visit), and
250 ** * a special "cleanup table" state.
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.
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.
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 int *aiSrcOrder
; /* src table col -> target table col */
271 u8
*abTblPk
; /* Array of flags, set on target PK columns */
272 u8
*abNotNull
; /* Array of flags, set on NOT NULL columns */
273 u8
*abIndexed
; /* Array of flags, set on indexed & PK cols */
274 int eType
; /* Table type - an RBU_PK_XXX value */
276 /* Output variables. zTbl==0 implies EOF. */
277 int bCleanup
; /* True in "cleanup" state */
278 const char *zTbl
; /* Name of target db table */
279 const char *zDataTbl
; /* Name of rbu db table (or null) */
280 const char *zIdx
; /* Name of target db index (or null) */
281 int iTnum
; /* Root page of current object */
282 int iPkTnum
; /* If eType==EXTERNAL, root of PK index */
283 int bUnique
; /* Current index is unique */
284 int nIndex
; /* Number of aux. indexes on table zTbl */
286 /* Statements created by rbuObjIterPrepareAll() */
287 int nCol
; /* Number of columns in current object */
288 sqlite3_stmt
*pSelect
; /* Source data */
289 sqlite3_stmt
*pInsert
; /* Statement for INSERT operations */
290 sqlite3_stmt
*pDelete
; /* Statement for DELETE ops */
291 sqlite3_stmt
*pTmpInsert
; /* Insert into rbu_tmp_$zDataTbl */
296 /* Last UPDATE used (for PK b-tree updates only), or NULL. */
297 RbuUpdateStmt
*pRbuUpdate
;
301 ** Values for RbuObjIter.eType
303 ** 0: Table does not exist (error)
304 ** 1: Table has an implicit rowid.
305 ** 2: Table has an explicit IPK column.
306 ** 3: Table has an external PK index.
307 ** 4: Table is WITHOUT ROWID.
308 ** 5: Table is a virtual table.
310 #define RBU_PK_NOTABLE 0
311 #define RBU_PK_NONE 1
313 #define RBU_PK_EXTERNAL 3
314 #define RBU_PK_WITHOUT_ROWID 4
315 #define RBU_PK_VTAB 5
319 ** Within the RBU_STAGE_OAL stage, each call to sqlite3rbu_step() performs
320 ** one of the following operations.
322 #define RBU_INSERT 1 /* Insert on a main table b-tree */
323 #define RBU_DELETE 2 /* Delete a row from a main table b-tree */
324 #define RBU_REPLACE 3 /* Delete and then insert a row */
325 #define RBU_IDX_DELETE 4 /* Delete a row from an aux. index b-tree */
326 #define RBU_IDX_INSERT 5 /* Insert on an aux. index b-tree */
328 #define RBU_UPDATE 6 /* Update a row in a main table b-tree */
331 ** A single step of an incremental checkpoint - frame iWalFrame of the wal
332 ** file should be copied to page iDbPage of the database file.
343 ** If the RBU database contains an rbu_count table, this value is set to
344 ** a running estimate of the number of b-tree operations required to
345 ** finish populating the *-oal file. This allows the sqlite3_bp_progress()
346 ** API to calculate the permyriadage progress of populating the *-oal file
347 ** using the formula:
349 ** permyriadage = (10000 * nProgress) / nPhaseOneStep
351 ** nPhaseOneStep is initialized to the sum of:
353 ** nRow * (nIndex + 1)
355 ** for all source tables in the RBU database, where nRow is the number
356 ** of rows in the source table and nIndex the number of indexes on the
357 ** corresponding target database table.
359 ** This estimate is accurate if the RBU update consists entirely of
360 ** INSERT operations. However, it is inaccurate if:
362 ** * the RBU update contains any UPDATE operations. If the PK specified
363 ** for an UPDATE operation does not exist in the target table, then
364 ** no b-tree operations are required on index b-trees. Or if the
365 ** specified PK does exist, then (nIndex*2) such operations are
366 ** required (one delete and one insert on each index b-tree).
368 ** * the RBU update contains any DELETE operations for which the specified
369 ** PK does not exist. In this case no operations are required on index
372 ** * the RBU update contains REPLACE operations. These are similar to
373 ** UPDATE operations.
375 ** nPhaseOneStep is updated to account for the conditions above during the
376 ** first pass of each source table. The updated nPhaseOneStep value is
377 ** stored in the rbu_state table if the RBU update is suspended.
380 int eStage
; /* Value of RBU_STATE_STAGE field */
381 sqlite3
*dbMain
; /* target database handle */
382 sqlite3
*dbRbu
; /* rbu database handle */
383 char *zTarget
; /* Path to target db */
384 char *zRbu
; /* Path to rbu db */
385 char *zState
; /* Path to state db (or NULL if zRbu) */
386 char zStateDb
[5]; /* Db name for state ("stat" or "main") */
387 int rc
; /* Value returned by last rbu_step() call */
388 char *zErrmsg
; /* Error message if rc!=SQLITE_OK */
389 int nStep
; /* Rows processed for current object */
390 int nProgress
; /* Rows processed for all objects */
391 RbuObjIter objiter
; /* Iterator for skipping through tbl/idx */
392 const char *zVfsName
; /* Name of automatically created rbu vfs */
393 rbu_file
*pTargetFd
; /* File handle open on target db */
394 int nPagePerSector
; /* Pages per sector for pTargetFd */
398 int (*xRename
)(void*, const char*, const char*);
400 /* The following state variables are used as part of the incremental
401 ** checkpoint stage (eStage==RBU_STAGE_CKPT). See comments surrounding
402 ** function rbuSetupCheckpoint() for details. */
403 u32 iMaxFrame
; /* Largest iWalFrame value in aFrame[] */
405 int nFrame
; /* Entries in aFrame[] array */
406 int nFrameAlloc
; /* Allocated size of aFrame[] array */
411 i64 szTemp
; /* Current size of all temp files in use */
412 i64 szTempLimit
; /* Total size limit for temp files */
414 /* Used in RBU vacuum mode only */
415 int nRbu
; /* Number of RBU VFS in the stack */
416 rbu_file
*pRbuFd
; /* Fd for main db of dbRbu */
420 ** An rbu VFS is implemented using an instance of this structure.
422 ** Variable pRbu is only non-NULL for automatically created RBU VFS objects.
423 ** It is NULL for RBU VFS objects created explicitly using
424 ** sqlite3rbu_create_vfs(). It is used to track the total amount of temp
425 ** space used by the RBU handle.
428 sqlite3_vfs base
; /* rbu VFS shim methods */
429 sqlite3_vfs
*pRealVfs
; /* Underlying VFS */
430 sqlite3_mutex
*mutex
; /* Mutex to protect pMain */
431 sqlite3rbu
*pRbu
; /* Owner RBU object */
432 rbu_file
*pMain
; /* List of main db files */
433 rbu_file
*pMainRbu
; /* List of main db files with pRbu!=0 */
437 ** Each file opened by an rbu VFS is represented by an instance of
438 ** the following structure.
440 ** If this is a temporary file (pRbu!=0 && flags&DELETE_ON_CLOSE), variable
441 ** "sz" is set to the current size of the database file.
444 sqlite3_file base
; /* sqlite3_file methods */
445 sqlite3_file
*pReal
; /* Underlying file handle */
446 rbu_vfs
*pRbuVfs
; /* Pointer to the rbu_vfs object */
447 sqlite3rbu
*pRbu
; /* Pointer to rbu object (rbu target only) */
448 i64 sz
; /* Size of file in bytes (temp only) */
450 int openFlags
; /* Flags this file was opened with */
451 u32 iCookie
; /* Cookie value for main db files */
452 u8 iWriteVer
; /* "write-version" value for main db files */
453 u8 bNolock
; /* True to fail EXCLUSIVE locks */
455 int nShm
; /* Number of entries in apShm[] array */
456 char **apShm
; /* Array of mmap'd *-shm regions */
457 char *zDel
; /* Delete this when closing file */
459 const char *zWal
; /* Wal filename for this main db file */
460 rbu_file
*pWalFd
; /* Wal file descriptor for this main db */
461 rbu_file
*pMainNext
; /* Next MAIN_DB file */
462 rbu_file
*pMainRbuNext
; /* Next MAIN_DB file with pRbu!=0 */
466 ** True for an RBU vacuum handle, or false otherwise.
468 #define rbuIsVacuum(p) ((p)->zTarget==0)
471 /*************************************************************************
472 ** The following three functions, found below:
475 ** rbuDeltaChecksum()
478 ** are lifted from the fossil source code (http://fossil-scm.org). They
479 ** are used to implement the scalar SQL function rbu_fossil_delta().
483 ** Read bytes from *pz and convert them into a positive integer. When
484 ** finished, leave *pz pointing to the first character past the end of
485 ** the integer. The *pLen parameter holds the length of the string
486 ** in *pz and is decremented once for each character in the integer.
488 static unsigned int rbuDeltaGetInt(const char **pz
, int *pLen
){
489 static const signed char zValue
[] = {
490 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
491 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
492 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
493 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
494 -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
495 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, 36,
496 -1, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
497 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, -1, -1, -1, 63, -1,
501 unsigned char *z
= (unsigned char*)*pz
;
502 unsigned char *zStart
= z
;
503 while( (c
= zValue
[0x7f&*(z
++)])>=0 ){
512 #if RBU_ENABLE_DELTA_CKSUM
514 ** Compute a 32-bit checksum on the N-byte buffer. Return the result.
516 static unsigned int rbuDeltaChecksum(const char *zIn
, size_t N
){
517 const unsigned char *z
= (const unsigned char *)zIn
;
523 sum0
+= ((unsigned)z
[0] + z
[4] + z
[8] + z
[12]);
524 sum1
+= ((unsigned)z
[1] + z
[5] + z
[9] + z
[13]);
525 sum2
+= ((unsigned)z
[2] + z
[6] + z
[10]+ z
[14]);
526 sum3
+= ((unsigned)z
[3] + z
[7] + z
[11]+ z
[15]);
538 sum3
+= (sum2
<< 8) + (sum1
<< 16) + (sum0
<< 24);
540 case 3: sum3
+= (z
[2] << 8);
541 case 2: sum3
+= (z
[1] << 16);
542 case 1: sum3
+= (z
[0] << 24);
552 ** The output buffer should be big enough to hold the whole output
553 ** file and a NUL terminator at the end. The delta_output_size()
554 ** routine will determine this size for you.
556 ** The delta string should be null-terminated. But the delta string
557 ** may contain embedded NUL characters (if the input and output are
558 ** binary files) so we also have to pass in the length of the delta in
559 ** the lenDelta parameter.
561 ** This function returns the size of the output file in bytes (excluding
562 ** the final NUL terminator character). Except, if the delta string is
563 ** malformed or intended for use with a source file other than zSrc,
564 ** then this routine returns -1.
566 ** Refer to the delta_create() documentation above for a description
567 ** of the delta file format.
569 static int rbuDeltaApply(
570 const char *zSrc
, /* The source or pattern file */
571 int lenSrc
, /* Length of the source file */
572 const char *zDelta
, /* Delta to apply to the pattern */
573 int lenDelta
, /* Length of the delta */
574 char *zOut
/* Write the output into this preallocated buffer */
577 unsigned int total
= 0;
578 #if RBU_ENABLE_DELTA_CKSUM
579 char *zOrigOut
= zOut
;
582 limit
= rbuDeltaGetInt(&zDelta
, &lenDelta
);
584 /* ERROR: size integer not terminated by "\n" */
587 zDelta
++; lenDelta
--;
588 while( *zDelta
&& lenDelta
>0 ){
589 unsigned int cnt
, ofst
;
590 cnt
= rbuDeltaGetInt(&zDelta
, &lenDelta
);
593 zDelta
++; lenDelta
--;
594 ofst
= rbuDeltaGetInt(&zDelta
, &lenDelta
);
595 if( lenDelta
>0 && zDelta
[0]!=',' ){
596 /* ERROR: copy command not terminated by ',' */
599 zDelta
++; lenDelta
--;
602 /* ERROR: copy exceeds output file size */
605 if( (int)(ofst
+cnt
) > lenSrc
){
606 /* ERROR: copy extends past end of input */
609 memcpy(zOut
, &zSrc
[ofst
], cnt
);
614 zDelta
++; lenDelta
--;
617 /* ERROR: insert command gives an output larger than predicted */
620 if( (int)cnt
>lenDelta
){
621 /* ERROR: insert count exceeds size of delta */
624 memcpy(zOut
, zDelta
, cnt
);
631 zDelta
++; lenDelta
--;
633 #if RBU_ENABLE_DELTA_CKSUM
634 if( cnt
!=rbuDeltaChecksum(zOrigOut
, total
) ){
635 /* ERROR: bad checksum */
640 /* ERROR: generated size does not match predicted size */
646 /* ERROR: unknown delta operator */
651 /* ERROR: unterminated delta */
655 static int rbuDeltaOutputSize(const char *zDelta
, int lenDelta
){
657 size
= rbuDeltaGetInt(&zDelta
, &lenDelta
);
659 /* ERROR: size integer not terminated by "\n" */
666 ** End of code taken from fossil.
667 *************************************************************************/
670 ** Implementation of SQL scalar function rbu_fossil_delta().
672 ** This function applies a fossil delta patch to a blob. Exactly two
673 ** arguments must be passed to this function. The first is the blob to
674 ** patch and the second the patch to apply. If no error occurs, this
675 ** function returns the patched blob.
677 static void rbuFossilDeltaFunc(
678 sqlite3_context
*context
,
693 nOrig
= sqlite3_value_bytes(argv
[0]);
694 aOrig
= (const char*)sqlite3_value_blob(argv
[0]);
695 nDelta
= sqlite3_value_bytes(argv
[1]);
696 aDelta
= (const char*)sqlite3_value_blob(argv
[1]);
698 /* Figure out the size of the output */
699 nOut
= rbuDeltaOutputSize(aDelta
, nDelta
);
701 sqlite3_result_error(context
, "corrupt fossil delta", -1);
705 aOut
= sqlite3_malloc(nOut
+1);
707 sqlite3_result_error_nomem(context
);
709 nOut2
= rbuDeltaApply(aOrig
, nOrig
, aDelta
, nDelta
, aOut
);
712 sqlite3_result_error(context
, "corrupt fossil delta", -1);
714 sqlite3_result_blob(context
, aOut
, nOut
, sqlite3_free
);
721 ** Prepare the SQL statement in buffer zSql against database handle db.
722 ** If successful, set *ppStmt to point to the new statement and return
725 ** Otherwise, if an error does occur, set *ppStmt to NULL and return
726 ** an SQLite error code. Additionally, set output variable *pzErrmsg to
727 ** point to a buffer containing an error message. It is the responsibility
728 ** of the caller to (eventually) free this buffer using sqlite3_free().
730 static int prepareAndCollectError(
732 sqlite3_stmt
**ppStmt
,
736 int rc
= sqlite3_prepare_v2(db
, zSql
, -1, ppStmt
, 0);
738 *pzErrmsg
= sqlite3_mprintf("%s", sqlite3_errmsg(db
));
745 ** Reset the SQL statement passed as the first argument. Return a copy
746 ** of the value returned by sqlite3_reset().
748 ** If an error has occurred, then set *pzErrmsg to point to a buffer
749 ** containing an error message. It is the responsibility of the caller
750 ** to eventually free this buffer using sqlite3_free().
752 static int resetAndCollectError(sqlite3_stmt
*pStmt
, char **pzErrmsg
){
753 int rc
= sqlite3_reset(pStmt
);
755 *pzErrmsg
= sqlite3_mprintf("%s", sqlite3_errmsg(sqlite3_db_handle(pStmt
)));
761 ** Unless it is NULL, argument zSql points to a buffer allocated using
762 ** sqlite3_malloc containing an SQL statement. This function prepares the SQL
763 ** statement against database db and frees the buffer. If statement
764 ** compilation is successful, *ppStmt is set to point to the new statement
765 ** handle and SQLITE_OK is returned.
767 ** Otherwise, if an error occurs, *ppStmt is set to NULL and an error code
768 ** returned. In this case, *pzErrmsg may also be set to point to an error
769 ** message. It is the responsibility of the caller to free this error message
770 ** buffer using sqlite3_free().
772 ** If argument zSql is NULL, this function assumes that an OOM has occurred.
773 ** In this case SQLITE_NOMEM is returned and *ppStmt set to NULL.
775 static int prepareFreeAndCollectError(
777 sqlite3_stmt
**ppStmt
,
782 assert( *pzErrmsg
==0 );
787 rc
= prepareAndCollectError(db
, ppStmt
, pzErrmsg
, zSql
);
794 ** Free the RbuObjIter.azTblCol[] and RbuObjIter.abTblPk[] arrays allocated
795 ** by an earlier call to rbuObjIterCacheTableInfo().
797 static void rbuObjIterFreeCols(RbuObjIter
*pIter
){
799 for(i
=0; i
<pIter
->nTblCol
; i
++){
800 sqlite3_free(pIter
->azTblCol
[i
]);
801 sqlite3_free(pIter
->azTblType
[i
]);
803 sqlite3_free(pIter
->azTblCol
);
805 pIter
->azTblType
= 0;
806 pIter
->aiSrcOrder
= 0;
808 pIter
->abNotNull
= 0;
810 pIter
->eType
= 0; /* Invalid value */
814 ** Finalize all statements and free all allocations that are specific to
815 ** the current object (table/index pair).
817 static void rbuObjIterClearStatements(RbuObjIter
*pIter
){
820 sqlite3_finalize(pIter
->pSelect
);
821 sqlite3_finalize(pIter
->pInsert
);
822 sqlite3_finalize(pIter
->pDelete
);
823 sqlite3_finalize(pIter
->pTmpInsert
);
824 pUp
= pIter
->pRbuUpdate
;
826 RbuUpdateStmt
*pTmp
= pUp
->pNext
;
827 sqlite3_finalize(pUp
->pUpdate
);
831 sqlite3_free(pIter
->aIdxCol
);
832 sqlite3_free(pIter
->zIdxSql
);
837 pIter
->pRbuUpdate
= 0;
838 pIter
->pTmpInsert
= 0;
846 ** Clean up any resources allocated as part of the iterator object passed
847 ** as the only argument.
849 static void rbuObjIterFinalize(RbuObjIter
*pIter
){
850 rbuObjIterClearStatements(pIter
);
851 sqlite3_finalize(pIter
->pTblIter
);
852 sqlite3_finalize(pIter
->pIdxIter
);
853 rbuObjIterFreeCols(pIter
);
854 memset(pIter
, 0, sizeof(RbuObjIter
));
858 ** Advance the iterator to the next position.
860 ** If no error occurs, SQLITE_OK is returned and the iterator is left
861 ** pointing to the next entry. Otherwise, an error code and message is
862 ** left in the RBU handle passed as the first argument. A copy of the
863 ** error code is returned.
865 static int rbuObjIterNext(sqlite3rbu
*p
, RbuObjIter
*pIter
){
869 /* Free any SQLite statements used while processing the previous object */
870 rbuObjIterClearStatements(pIter
);
871 if( pIter
->zIdx
==0 ){
872 rc
= sqlite3_exec(p
->dbMain
,
873 "DROP TRIGGER IF EXISTS temp.rbu_insert_tr;"
874 "DROP TRIGGER IF EXISTS temp.rbu_update1_tr;"
875 "DROP TRIGGER IF EXISTS temp.rbu_update2_tr;"
876 "DROP TRIGGER IF EXISTS temp.rbu_delete_tr;"
882 if( pIter
->bCleanup
){
883 rbuObjIterFreeCols(pIter
);
885 rc
= sqlite3_step(pIter
->pTblIter
);
886 if( rc
!=SQLITE_ROW
){
887 rc
= resetAndCollectError(pIter
->pTblIter
, &p
->zErrmsg
);
891 pIter
->zTbl
= (const char*)sqlite3_column_text(pIter
->pTblIter
, 0);
892 pIter
->zDataTbl
= (const char*)sqlite3_column_text(pIter
->pTblIter
,1);
893 rc
= (pIter
->zDataTbl
&& pIter
->zTbl
) ? SQLITE_OK
: SQLITE_NOMEM
;
896 if( pIter
->zIdx
==0 ){
897 sqlite3_stmt
*pIdx
= pIter
->pIdxIter
;
898 rc
= sqlite3_bind_text(pIdx
, 1, pIter
->zTbl
, -1, SQLITE_STATIC
);
901 rc
= sqlite3_step(pIter
->pIdxIter
);
902 if( rc
!=SQLITE_ROW
){
903 rc
= resetAndCollectError(pIter
->pIdxIter
, &p
->zErrmsg
);
907 pIter
->zIdx
= (const char*)sqlite3_column_text(pIter
->pIdxIter
, 0);
908 pIter
->iTnum
= sqlite3_column_int(pIter
->pIdxIter
, 1);
909 pIter
->bUnique
= sqlite3_column_int(pIter
->pIdxIter
, 2);
910 rc
= pIter
->zIdx
? SQLITE_OK
: SQLITE_NOMEM
;
918 rbuObjIterFinalize(pIter
);
926 ** The implementation of the rbu_target_name() SQL function. This function
927 ** accepts one or two arguments. The first argument is the name of a table -
928 ** the name of a table in the RBU database. The second, if it is present, is 1
929 ** for a view or 0 for a table.
931 ** For a non-vacuum RBU handle, if the table name matches the pattern:
935 ** where <name> is any sequence of 1 or more characters, <name> is returned.
936 ** Otherwise, if the only argument does not match the above pattern, an SQL
940 ** "data0123_t2" -> "t2"
941 ** "dataAB_t3" -> NULL
943 ** For an rbu vacuum handle, a copy of the first argument is returned if
944 ** the second argument is either missing or 0 (not a view).
946 static void rbuTargetNameFunc(
947 sqlite3_context
*pCtx
,
951 sqlite3rbu
*p
= sqlite3_user_data(pCtx
);
953 assert( argc
==1 || argc
==2 );
955 zIn
= (const char*)sqlite3_value_text(argv
[0]);
957 if( rbuIsVacuum(p
) ){
958 assert( argc
==2 || argc
==1 );
959 if( argc
==1 || 0==sqlite3_value_int(argv
[1]) ){
960 sqlite3_result_text(pCtx
, zIn
, -1, SQLITE_STATIC
);
963 if( strlen(zIn
)>4 && memcmp("data", zIn
, 4)==0 ){
965 for(i
=4; zIn
[i
]>='0' && zIn
[i
]<='9'; i
++);
966 if( zIn
[i
]=='_' && zIn
[i
+1] ){
967 sqlite3_result_text(pCtx
, &zIn
[i
+1], -1, SQLITE_STATIC
);
975 ** Initialize the iterator structure passed as the second argument.
977 ** If no error occurs, SQLITE_OK is returned and the iterator is left
978 ** pointing to the first entry. Otherwise, an error code and message is
979 ** left in the RBU handle passed as the first argument. A copy of the
980 ** error code is returned.
982 static int rbuObjIterFirst(sqlite3rbu
*p
, RbuObjIter
*pIter
){
984 memset(pIter
, 0, sizeof(RbuObjIter
));
986 rc
= prepareFreeAndCollectError(p
->dbRbu
, &pIter
->pTblIter
, &p
->zErrmsg
,
988 "SELECT rbu_target_name(name, type='view') AS target, name "
989 "FROM sqlite_schema "
990 "WHERE type IN ('table', 'view') AND target IS NOT NULL "
993 , rbuIsVacuum(p
) ? "AND rootpage!=0 AND rootpage IS NOT NULL" : ""));
996 rc
= prepareAndCollectError(p
->dbMain
, &pIter
->pIdxIter
, &p
->zErrmsg
,
997 "SELECT name, rootpage, sql IS NULL OR substr(8, 6)=='UNIQUE' "
998 " FROM main.sqlite_schema "
999 " WHERE type='index' AND tbl_name = ?"
1003 pIter
->bCleanup
= 1;
1005 return rbuObjIterNext(p
, pIter
);
1009 ** This is a wrapper around "sqlite3_mprintf(zFmt, ...)". If an OOM occurs,
1010 ** an error code is stored in the RBU handle passed as the first argument.
1012 ** If an error has already occurred (p->rc is already set to something other
1013 ** than SQLITE_OK), then this function returns NULL without modifying the
1014 ** stored error code. In this case it still calls sqlite3_free() on any
1015 ** printf() parameters associated with %z conversions.
1017 static char *rbuMPrintf(sqlite3rbu
*p
, const char *zFmt
, ...){
1021 zSql
= sqlite3_vmprintf(zFmt
, ap
);
1022 if( p
->rc
==SQLITE_OK
){
1023 if( zSql
==0 ) p
->rc
= SQLITE_NOMEM
;
1033 ** Argument zFmt is a sqlite3_mprintf() style format string. The trailing
1034 ** arguments are the usual subsitution values. This function performs
1035 ** the printf() style substitutions and executes the result as an SQL
1036 ** statement on the RBU handles database.
1038 ** If an error occurs, an error code and error message is stored in the
1039 ** RBU handle. If an error has already occurred when this function is
1040 ** called, it is a no-op.
1042 static int rbuMPrintfExec(sqlite3rbu
*p
, sqlite3
*db
, const char *zFmt
, ...){
1046 zSql
= sqlite3_vmprintf(zFmt
, ap
);
1047 if( p
->rc
==SQLITE_OK
){
1049 p
->rc
= SQLITE_NOMEM
;
1051 p
->rc
= sqlite3_exec(db
, zSql
, 0, 0, &p
->zErrmsg
);
1060 ** Attempt to allocate and return a pointer to a zeroed block of nByte
1063 ** If an error (i.e. an OOM condition) occurs, return NULL and leave an
1064 ** error code in the rbu handle passed as the first argument. Or, if an
1065 ** error has already occurred when this function is called, return NULL
1066 ** immediately without attempting the allocation or modifying the stored
1069 static void *rbuMalloc(sqlite3rbu
*p
, sqlite3_int64 nByte
){
1071 if( p
->rc
==SQLITE_OK
){
1073 pRet
= sqlite3_malloc64(nByte
);
1075 p
->rc
= SQLITE_NOMEM
;
1077 memset(pRet
, 0, nByte
);
1085 ** Allocate and zero the pIter->azTblCol[] and abTblPk[] arrays so that
1086 ** there is room for at least nCol elements. If an OOM occurs, store an
1087 ** error code in the RBU handle passed as the first argument.
1089 static void rbuAllocateIterArrays(sqlite3rbu
*p
, RbuObjIter
*pIter
, int nCol
){
1090 sqlite3_int64 nByte
= (2*sizeof(char*) + sizeof(int) + 3*sizeof(u8
)) * nCol
;
1093 azNew
= (char**)rbuMalloc(p
, nByte
);
1095 pIter
->azTblCol
= azNew
;
1096 pIter
->azTblType
= &azNew
[nCol
];
1097 pIter
->aiSrcOrder
= (int*)&pIter
->azTblType
[nCol
];
1098 pIter
->abTblPk
= (u8
*)&pIter
->aiSrcOrder
[nCol
];
1099 pIter
->abNotNull
= (u8
*)&pIter
->abTblPk
[nCol
];
1100 pIter
->abIndexed
= (u8
*)&pIter
->abNotNull
[nCol
];
1105 ** The first argument must be a nul-terminated string. This function
1106 ** returns a copy of the string in memory obtained from sqlite3_malloc().
1107 ** It is the responsibility of the caller to eventually free this memory
1108 ** using sqlite3_free().
1110 ** If an OOM condition is encountered when attempting to allocate memory,
1111 ** output variable (*pRc) is set to SQLITE_NOMEM before returning. Otherwise,
1112 ** if the allocation succeeds, (*pRc) is left unchanged.
1114 static char *rbuStrndup(const char *zStr
, int *pRc
){
1117 if( *pRc
==SQLITE_OK
){
1119 size_t nCopy
= strlen(zStr
) + 1;
1120 zRet
= (char*)sqlite3_malloc64(nCopy
);
1122 memcpy(zRet
, zStr
, nCopy
);
1124 *pRc
= SQLITE_NOMEM
;
1133 ** Finalize the statement passed as the second argument.
1135 ** If the sqlite3_finalize() call indicates that an error occurs, and the
1136 ** rbu handle error code is not already set, set the error code and error
1137 ** message accordingly.
1139 static void rbuFinalize(sqlite3rbu
*p
, sqlite3_stmt
*pStmt
){
1140 sqlite3
*db
= sqlite3_db_handle(pStmt
);
1141 int rc
= sqlite3_finalize(pStmt
);
1142 if( p
->rc
==SQLITE_OK
&& rc
!=SQLITE_OK
){
1144 p
->zErrmsg
= sqlite3_mprintf("%s", sqlite3_errmsg(db
));
1148 /* Determine the type of a table.
1150 ** peType is of type (int*), a pointer to an output parameter of type
1151 ** (int). This call sets the output parameter as follows, depending
1152 ** on the type of the table specified by parameters dbName and zTbl.
1154 ** RBU_PK_NOTABLE: No such table.
1155 ** RBU_PK_NONE: Table has an implicit rowid.
1156 ** RBU_PK_IPK: Table has an explicit IPK column.
1157 ** RBU_PK_EXTERNAL: Table has an external PK index.
1158 ** RBU_PK_WITHOUT_ROWID: Table is WITHOUT ROWID.
1159 ** RBU_PK_VTAB: Table is a virtual table.
1161 ** Argument *piPk is also of type (int*), and also points to an output
1162 ** parameter. Unless the table has an external primary key index
1163 ** (i.e. unless *peType is set to 3), then *piPk is set to zero. Or,
1164 ** if the table does have an external primary key index, then *piPk
1165 ** is set to the root page number of the primary key index before
1170 ** if( no entry exists in sqlite_schema ){
1171 ** return RBU_PK_NOTABLE
1172 ** }else if( sql for the entry starts with "CREATE VIRTUAL" ){
1173 ** return RBU_PK_VTAB
1174 ** }else if( "PRAGMA index_list()" for the table contains a "pk" index ){
1175 ** if( the index that is the pk exists in sqlite_schema ){
1176 ** *piPK = rootpage of that index.
1177 ** return RBU_PK_EXTERNAL
1179 ** return RBU_PK_WITHOUT_ROWID
1181 ** }else if( "PRAGMA table_info()" lists one or more "pk" columns ){
1182 ** return RBU_PK_IPK
1184 ** return RBU_PK_NONE
1187 static void rbuTableType(
1195 ** 0) SELECT count(*) FROM sqlite_schema where name=%Q AND IsVirtual(%Q)
1196 ** 1) PRAGMA index_list = ?
1197 ** 2) SELECT count(*) FROM sqlite_schema where name=%Q
1198 ** 3) PRAGMA table_info = ?
1200 sqlite3_stmt
*aStmt
[4] = {0, 0, 0, 0};
1202 *peType
= RBU_PK_NOTABLE
;
1205 assert( p
->rc
==SQLITE_OK
);
1206 p
->rc
= prepareFreeAndCollectError(p
->dbMain
, &aStmt
[0], &p
->zErrmsg
,
1209 " (sql COLLATE nocase BETWEEN 'CREATE VIRTUAL' AND 'CREATE VIRTUAM'),"
1211 " FROM sqlite_schema"
1212 " WHERE name=%Q", zTab
1214 if( p
->rc
!=SQLITE_OK
|| sqlite3_step(aStmt
[0])!=SQLITE_ROW
){
1215 /* Either an error, or no such table. */
1216 goto rbuTableType_end
;
1218 if( sqlite3_column_int(aStmt
[0], 0) ){
1219 *peType
= RBU_PK_VTAB
; /* virtual table */
1220 goto rbuTableType_end
;
1222 *piTnum
= sqlite3_column_int(aStmt
[0], 1);
1224 p
->rc
= prepareFreeAndCollectError(p
->dbMain
, &aStmt
[1], &p
->zErrmsg
,
1225 sqlite3_mprintf("PRAGMA index_list=%Q",zTab
)
1227 if( p
->rc
) goto rbuTableType_end
;
1228 while( sqlite3_step(aStmt
[1])==SQLITE_ROW
){
1229 const u8
*zOrig
= sqlite3_column_text(aStmt
[1], 3);
1230 const u8
*zIdx
= sqlite3_column_text(aStmt
[1], 1);
1231 if( zOrig
&& zIdx
&& zOrig
[0]=='p' ){
1232 p
->rc
= prepareFreeAndCollectError(p
->dbMain
, &aStmt
[2], &p
->zErrmsg
,
1234 "SELECT rootpage FROM sqlite_schema WHERE name = %Q", zIdx
1236 if( p
->rc
==SQLITE_OK
){
1237 if( sqlite3_step(aStmt
[2])==SQLITE_ROW
){
1238 *piPk
= sqlite3_column_int(aStmt
[2], 0);
1239 *peType
= RBU_PK_EXTERNAL
;
1241 *peType
= RBU_PK_WITHOUT_ROWID
;
1244 goto rbuTableType_end
;
1248 p
->rc
= prepareFreeAndCollectError(p
->dbMain
, &aStmt
[3], &p
->zErrmsg
,
1249 sqlite3_mprintf("PRAGMA table_info=%Q",zTab
)
1251 if( p
->rc
==SQLITE_OK
){
1252 while( sqlite3_step(aStmt
[3])==SQLITE_ROW
){
1253 if( sqlite3_column_int(aStmt
[3],5)>0 ){
1254 *peType
= RBU_PK_IPK
; /* explicit IPK column */
1255 goto rbuTableType_end
;
1258 *peType
= RBU_PK_NONE
;
1263 for(i
=0; i
<sizeof(aStmt
)/sizeof(aStmt
[0]); i
++){
1264 rbuFinalize(p
, aStmt
[i
]);
1270 ** This is a helper function for rbuObjIterCacheTableInfo(). It populates
1271 ** the pIter->abIndexed[] array.
1273 static void rbuObjIterCacheIndexedCols(sqlite3rbu
*p
, RbuObjIter
*pIter
){
1274 sqlite3_stmt
*pList
= 0;
1277 if( p
->rc
==SQLITE_OK
){
1278 memcpy(pIter
->abIndexed
, pIter
->abTblPk
, sizeof(u8
)*pIter
->nTblCol
);
1279 p
->rc
= prepareFreeAndCollectError(p
->dbMain
, &pList
, &p
->zErrmsg
,
1280 sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter
->zTbl
)
1285 while( p
->rc
==SQLITE_OK
&& SQLITE_ROW
==sqlite3_step(pList
) ){
1286 const char *zIdx
= (const char*)sqlite3_column_text(pList
, 1);
1287 int bPartial
= sqlite3_column_int(pList
, 4);
1288 sqlite3_stmt
*pXInfo
= 0;
1289 if( zIdx
==0 ) break;
1291 memset(pIter
->abIndexed
, 0x01, sizeof(u8
)*pIter
->nTblCol
);
1293 p
->rc
= prepareFreeAndCollectError(p
->dbMain
, &pXInfo
, &p
->zErrmsg
,
1294 sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx
)
1296 while( p
->rc
==SQLITE_OK
&& SQLITE_ROW
==sqlite3_step(pXInfo
) ){
1297 int iCid
= sqlite3_column_int(pXInfo
, 1);
1298 if( iCid
>=0 ) pIter
->abIndexed
[iCid
] = 1;
1300 memset(pIter
->abIndexed
, 0x01, sizeof(u8
)*pIter
->nTblCol
);
1303 rbuFinalize(p
, pXInfo
);
1308 if( pIter
->eType
==RBU_PK_WITHOUT_ROWID
){
1309 /* "PRAGMA index_list" includes the main PK b-tree */
1313 rbuFinalize(p
, pList
);
1314 if( bIndex
==0 ) pIter
->abIndexed
= 0;
1319 ** If they are not already populated, populate the pIter->azTblCol[],
1320 ** pIter->abTblPk[], pIter->nTblCol and pIter->bRowid variables according to
1321 ** the table (not index) that the iterator currently points to.
1323 ** Return SQLITE_OK if successful, or an SQLite error code otherwise. If
1324 ** an error does occur, an error code and error message are also left in
1327 static int rbuObjIterCacheTableInfo(sqlite3rbu
*p
, RbuObjIter
*pIter
){
1328 if( pIter
->azTblCol
==0 ){
1329 sqlite3_stmt
*pStmt
= 0;
1331 int i
; /* for() loop iterator variable */
1332 int bRbuRowid
= 0; /* If input table has column "rbu_rowid" */
1336 /* Figure out the type of table this step will deal with. */
1337 assert( pIter
->eType
==0 );
1338 rbuTableType(p
, pIter
->zTbl
, &pIter
->eType
, &iTnum
, &pIter
->iPkTnum
);
1339 if( p
->rc
==SQLITE_OK
&& pIter
->eType
==RBU_PK_NOTABLE
){
1340 p
->rc
= SQLITE_ERROR
;
1341 p
->zErrmsg
= sqlite3_mprintf("no such table: %s", pIter
->zTbl
);
1343 if( p
->rc
) return p
->rc
;
1344 if( pIter
->zIdx
==0 ) pIter
->iTnum
= iTnum
;
1346 assert( pIter
->eType
==RBU_PK_NONE
|| pIter
->eType
==RBU_PK_IPK
1347 || pIter
->eType
==RBU_PK_EXTERNAL
|| pIter
->eType
==RBU_PK_WITHOUT_ROWID
1348 || pIter
->eType
==RBU_PK_VTAB
1351 /* Populate the azTblCol[] and nTblCol variables based on the columns
1352 ** of the input table. Ignore any input table columns that begin with
1354 p
->rc
= prepareFreeAndCollectError(p
->dbRbu
, &pStmt
, &p
->zErrmsg
,
1355 sqlite3_mprintf("SELECT * FROM '%q'", pIter
->zDataTbl
)
1357 if( p
->rc
==SQLITE_OK
){
1358 nCol
= sqlite3_column_count(pStmt
);
1359 rbuAllocateIterArrays(p
, pIter
, nCol
);
1361 for(i
=0; p
->rc
==SQLITE_OK
&& i
<nCol
; i
++){
1362 const char *zName
= (const char*)sqlite3_column_name(pStmt
, i
);
1363 if( sqlite3_strnicmp("rbu_", zName
, 4) ){
1364 char *zCopy
= rbuStrndup(zName
, &p
->rc
);
1365 pIter
->aiSrcOrder
[pIter
->nTblCol
] = pIter
->nTblCol
;
1366 pIter
->azTblCol
[pIter
->nTblCol
++] = zCopy
;
1368 else if( 0==sqlite3_stricmp("rbu_rowid", zName
) ){
1372 sqlite3_finalize(pStmt
);
1375 if( p
->rc
==SQLITE_OK
1376 && rbuIsVacuum(p
)==0
1377 && bRbuRowid
!=(pIter
->eType
==RBU_PK_VTAB
|| pIter
->eType
==RBU_PK_NONE
)
1379 p
->rc
= SQLITE_ERROR
;
1380 p
->zErrmsg
= sqlite3_mprintf(
1381 "table %q %s rbu_rowid column", pIter
->zDataTbl
,
1382 (bRbuRowid
? "may not have" : "requires")
1386 /* Check that all non-HIDDEN columns in the destination table are also
1387 ** present in the input table. Populate the abTblPk[], azTblType[] and
1388 ** aiTblOrder[] arrays at the same time. */
1389 if( p
->rc
==SQLITE_OK
){
1390 p
->rc
= prepareFreeAndCollectError(p
->dbMain
, &pStmt
, &p
->zErrmsg
,
1391 sqlite3_mprintf("PRAGMA table_info(%Q)", pIter
->zTbl
)
1394 while( p
->rc
==SQLITE_OK
&& SQLITE_ROW
==sqlite3_step(pStmt
) ){
1395 const char *zName
= (const char*)sqlite3_column_text(pStmt
, 1);
1396 if( zName
==0 ) break; /* An OOM - finalize() below returns S_NOMEM */
1397 for(i
=iOrder
; i
<pIter
->nTblCol
; i
++){
1398 if( 0==strcmp(zName
, pIter
->azTblCol
[i
]) ) break;
1400 if( i
==pIter
->nTblCol
){
1401 p
->rc
= SQLITE_ERROR
;
1402 p
->zErrmsg
= sqlite3_mprintf("column missing from %q: %s",
1403 pIter
->zDataTbl
, zName
1406 int iPk
= sqlite3_column_int(pStmt
, 5);
1407 int bNotNull
= sqlite3_column_int(pStmt
, 3);
1408 const char *zType
= (const char*)sqlite3_column_text(pStmt
, 2);
1411 SWAP(int, pIter
->aiSrcOrder
[i
], pIter
->aiSrcOrder
[iOrder
]);
1412 SWAP(char*, pIter
->azTblCol
[i
], pIter
->azTblCol
[iOrder
]);
1415 pIter
->azTblType
[iOrder
] = rbuStrndup(zType
, &p
->rc
);
1417 pIter
->abTblPk
[iOrder
] = (u8
)iPk
;
1418 pIter
->abNotNull
[iOrder
] = (u8
)bNotNull
|| (iPk
!=0);
1423 rbuFinalize(p
, pStmt
);
1424 rbuObjIterCacheIndexedCols(p
, pIter
);
1425 assert( pIter
->eType
!=RBU_PK_VTAB
|| pIter
->abIndexed
==0 );
1426 assert( pIter
->eType
!=RBU_PK_VTAB
|| pIter
->nIndex
==0 );
1433 ** This function constructs and returns a pointer to a nul-terminated
1434 ** string containing some SQL clause or list based on one or more of the
1435 ** column names currently stored in the pIter->azTblCol[] array.
1437 static char *rbuObjIterGetCollist(
1438 sqlite3rbu
*p
, /* RBU object */
1439 RbuObjIter
*pIter
/* Object iterator for column names */
1442 const char *zSep
= "";
1444 for(i
=0; i
<pIter
->nTblCol
; i
++){
1445 const char *z
= pIter
->azTblCol
[i
];
1446 zList
= rbuMPrintf(p
, "%z%s\"%w\"", zList
, zSep
, z
);
1453 ** Return a comma separated list of the quoted PRIMARY KEY column names,
1454 ** in order, for the current table. Before each column name, add the text
1455 ** zPre. After each column name, add the zPost text. Use zSeparator as
1456 ** the separator text (usually ", ").
1458 static char *rbuObjIterGetPkList(
1459 sqlite3rbu
*p
, /* RBU object */
1460 RbuObjIter
*pIter
, /* Object iterator for column names */
1461 const char *zPre
, /* Before each quoted column name */
1462 const char *zSeparator
, /* Separator to use between columns */
1463 const char *zPost
/* After each quoted column name */
1467 const char *zSep
= "";
1470 for(i
=0; i
<pIter
->nTblCol
; i
++){
1471 if( (int)pIter
->abTblPk
[i
]==iPk
){
1472 const char *zCol
= pIter
->azTblCol
[i
];
1473 zRet
= rbuMPrintf(p
, "%z%s%s\"%w\"%s", zRet
, zSep
, zPre
, zCol
, zPost
);
1478 if( i
==pIter
->nTblCol
) break;
1485 ** This function is called as part of restarting an RBU vacuum within
1486 ** stage 1 of the process (while the *-oal file is being built) while
1487 ** updating a table (not an index). The table may be a rowid table or
1488 ** a WITHOUT ROWID table. It queries the target database to find the
1489 ** largest key that has already been written to the target table and
1490 ** constructs a WHERE clause that can be used to extract the remaining
1491 ** rows from the source table. For a rowid table, the WHERE clause
1494 ** "WHERE _rowid_ > ?"
1496 ** and for WITHOUT ROWID tables:
1498 ** "WHERE (key1, key2) > (?, ?)"
1500 ** Instead of "?" placeholders, the actual WHERE clauses created by
1501 ** this function contain literal SQL values.
1503 static char *rbuVacuumTableStart(
1504 sqlite3rbu
*p
, /* RBU handle */
1505 RbuObjIter
*pIter
, /* RBU iterator object */
1506 int bRowid
, /* True for a rowid table */
1507 const char *zWrite
/* Target table name prefix */
1509 sqlite3_stmt
*pMax
= 0;
1512 p
->rc
= prepareFreeAndCollectError(p
->dbMain
, &pMax
, &p
->zErrmsg
,
1514 "SELECT max(_rowid_) FROM \"%s%w\"", zWrite
, pIter
->zTbl
1517 if( p
->rc
==SQLITE_OK
&& SQLITE_ROW
==sqlite3_step(pMax
) ){
1518 sqlite3_int64 iMax
= sqlite3_column_int64(pMax
, 0);
1519 zRet
= rbuMPrintf(p
, " WHERE _rowid_ > %lld ", iMax
);
1521 rbuFinalize(p
, pMax
);
1523 char *zOrder
= rbuObjIterGetPkList(p
, pIter
, "", ", ", " DESC");
1524 char *zSelect
= rbuObjIterGetPkList(p
, pIter
, "quote(", "||','||", ")");
1525 char *zList
= rbuObjIterGetPkList(p
, pIter
, "", ", ", "");
1527 if( p
->rc
==SQLITE_OK
){
1528 p
->rc
= prepareFreeAndCollectError(p
->dbMain
, &pMax
, &p
->zErrmsg
,
1530 "SELECT %s FROM \"%s%w\" ORDER BY %s LIMIT 1",
1531 zSelect
, zWrite
, pIter
->zTbl
, zOrder
1534 if( p
->rc
==SQLITE_OK
&& SQLITE_ROW
==sqlite3_step(pMax
) ){
1535 const char *zVal
= (const char*)sqlite3_column_text(pMax
, 0);
1536 zRet
= rbuMPrintf(p
, " WHERE (%s) > (%s) ", zList
, zVal
);
1538 rbuFinalize(p
, pMax
);
1541 sqlite3_free(zOrder
);
1542 sqlite3_free(zSelect
);
1543 sqlite3_free(zList
);
1549 ** This function is called as part of restating an RBU vacuum when the
1550 ** current operation is writing content to an index. If possible, it
1551 ** queries the target index b-tree for the largest key already written to
1552 ** it, then composes and returns an expression that can be used in a WHERE
1553 ** clause to select the remaining required rows from the source table.
1554 ** It is only possible to return such an expression if:
1556 ** * The index contains no DESC columns, and
1557 ** * The last key written to the index before the operation was
1558 ** suspended does not contain any NULL values.
1560 ** The expression is of the form:
1562 ** (index-field1, index-field2, ...) > (?, ?, ...)
1564 ** except that the "?" placeholders are replaced with literal values.
1566 ** If the expression cannot be created, NULL is returned. In this case,
1567 ** the caller has to use an OFFSET clause to extract only the required
1568 ** rows from the sourct table, just as it does for an RBU update operation.
1570 static char *rbuVacuumIndexStart(
1571 sqlite3rbu
*p
, /* RBU handle */
1572 RbuObjIter
*pIter
/* RBU iterator object */
1580 const char *zSep
= "";
1582 sqlite3_stmt
*pXInfo
= 0;
1584 p
->rc
= prepareFreeAndCollectError(p
->dbMain
, &pXInfo
, &p
->zErrmsg
,
1585 sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter
->zIdx
)
1587 while( p
->rc
==SQLITE_OK
&& SQLITE_ROW
==sqlite3_step(pXInfo
) ){
1588 int iCid
= sqlite3_column_int(pXInfo
, 1);
1589 const char *zCollate
= (const char*)sqlite3_column_text(pXInfo
, 4);
1591 if( sqlite3_column_int(pXInfo
, 3) ){
1597 if( pIter
->eType
==RBU_PK_IPK
){
1599 for(i
=0; pIter
->abTblPk
[i
]==0; i
++);
1600 assert( i
<pIter
->nTblCol
);
1601 zCol
= pIter
->azTblCol
[i
];
1606 zCol
= pIter
->azTblCol
[iCid
];
1609 zLhs
= rbuMPrintf(p
, "%z%s \"%w\" COLLATE %Q",
1610 zLhs
, zSep
, zCol
, zCollate
1612 zOrder
= rbuMPrintf(p
, "%z%s \"rbu_imp_%d%w\" COLLATE %Q DESC",
1613 zOrder
, zSep
, iCol
, zCol
, zCollate
1615 zSelect
= rbuMPrintf(p
, "%z%s quote(\"rbu_imp_%d%w\")",
1616 zSelect
, zSep
, iCol
, zCol
1621 rbuFinalize(p
, pXInfo
);
1622 if( bFailed
) goto index_start_out
;
1624 if( p
->rc
==SQLITE_OK
){
1625 sqlite3_stmt
*pSel
= 0;
1627 p
->rc
= prepareFreeAndCollectError(p
->dbMain
, &pSel
, &p
->zErrmsg
,
1628 sqlite3_mprintf("SELECT %s FROM \"rbu_imp_%w\" ORDER BY %s LIMIT 1",
1629 zSelect
, pIter
->zTbl
, zOrder
1632 if( p
->rc
==SQLITE_OK
&& SQLITE_ROW
==sqlite3_step(pSel
) ){
1634 for(iCol
=0; iCol
<pIter
->nCol
; iCol
++){
1635 const char *zQuoted
= (const char*)sqlite3_column_text(pSel
, iCol
);
1637 p
->rc
= SQLITE_NOMEM
;
1638 }else if( zQuoted
[0]=='N' ){
1642 zVector
= rbuMPrintf(p
, "%z%s%s", zVector
, zSep
, zQuoted
);
1647 zRet
= rbuMPrintf(p
, "(%s) > (%s)", zLhs
, zVector
);
1650 rbuFinalize(p
, pSel
);
1654 sqlite3_free(zOrder
);
1655 sqlite3_free(zSelect
);
1656 sqlite3_free(zVector
);
1662 ** This function is used to create a SELECT list (the list of SQL
1663 ** expressions that follows a SELECT keyword) for a SELECT statement
1664 ** used to read from an data_xxx or rbu_tmp_xxx table while updating the
1665 ** index object currently indicated by the iterator object passed as the
1666 ** second argument. A "PRAGMA index_xinfo = <idxname>" statement is used
1667 ** to obtain the required information.
1669 ** If the index is of the following form:
1671 ** CREATE INDEX i1 ON t1(c, b COLLATE nocase);
1673 ** and "t1" is a table with an explicit INTEGER PRIMARY KEY column
1674 ** "ipk", the returned string is:
1676 ** "`c` COLLATE 'BINARY', `b` COLLATE 'NOCASE', `ipk` COLLATE 'BINARY'"
1678 ** As well as the returned string, three other malloc'd strings are
1679 ** returned via output parameters. As follows:
1681 ** pzImposterCols: ...
1682 ** pzImposterPk: ...
1685 static char *rbuObjIterGetIndexCols(
1686 sqlite3rbu
*p
, /* RBU object */
1687 RbuObjIter
*pIter
, /* Object iterator for column names */
1688 char **pzImposterCols
, /* OUT: Columns for imposter table */
1689 char **pzImposterPk
, /* OUT: Imposter PK clause */
1690 char **pzWhere
, /* OUT: WHERE clause */
1691 int *pnBind
/* OUT: Trbul number of columns */
1693 int rc
= p
->rc
; /* Error code */
1694 int rc2
; /* sqlite3_finalize() return code */
1695 char *zRet
= 0; /* String to return */
1696 char *zImpCols
= 0; /* String to return via *pzImposterCols */
1697 char *zImpPK
= 0; /* String to return via *pzImposterPK */
1698 char *zWhere
= 0; /* String to return via *pzWhere */
1699 int nBind
= 0; /* Value to return via *pnBind */
1700 const char *zCom
= ""; /* Set to ", " later on */
1701 const char *zAnd
= ""; /* Set to " AND " later on */
1702 sqlite3_stmt
*pXInfo
= 0; /* PRAGMA index_xinfo = ? */
1704 if( rc
==SQLITE_OK
){
1705 assert( p
->zErrmsg
==0 );
1706 rc
= prepareFreeAndCollectError(p
->dbMain
, &pXInfo
, &p
->zErrmsg
,
1707 sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter
->zIdx
)
1711 while( rc
==SQLITE_OK
&& SQLITE_ROW
==sqlite3_step(pXInfo
) ){
1712 int iCid
= sqlite3_column_int(pXInfo
, 1);
1713 int bDesc
= sqlite3_column_int(pXInfo
, 3);
1714 const char *zCollate
= (const char*)sqlite3_column_text(pXInfo
, 4);
1715 const char *zCol
= 0;
1719 int iSeq
= sqlite3_column_int(pXInfo
, 0);
1720 zRet
= sqlite3_mprintf("%z%s(%.*s) COLLATE %Q", zRet
, zCom
,
1721 pIter
->aIdxCol
[iSeq
].nSpan
, pIter
->aIdxCol
[iSeq
].zSpan
, zCollate
1726 /* An integer primary key. If the table has an explicit IPK, use
1727 ** its name. Otherwise, use "rbu_rowid". */
1728 if( pIter
->eType
==RBU_PK_IPK
){
1730 for(i
=0; pIter
->abTblPk
[i
]==0; i
++);
1731 assert( i
<pIter
->nTblCol
);
1732 zCol
= pIter
->azTblCol
[i
];
1733 }else if( rbuIsVacuum(p
) ){
1740 zCol
= pIter
->azTblCol
[iCid
];
1741 zType
= pIter
->azTblType
[iCid
];
1743 zRet
= sqlite3_mprintf("%z%s\"%w\" COLLATE %Q", zRet
, zCom
,zCol
,zCollate
);
1746 if( pIter
->bUnique
==0 || sqlite3_column_int(pXInfo
, 5) ){
1747 const char *zOrder
= (bDesc
? " DESC" : "");
1748 zImpPK
= sqlite3_mprintf("%z%s\"rbu_imp_%d%w\"%s",
1749 zImpPK
, zCom
, nBind
, zCol
, zOrder
1752 zImpCols
= sqlite3_mprintf("%z%s\"rbu_imp_%d%w\" %s COLLATE %Q",
1753 zImpCols
, zCom
, nBind
, zCol
, zType
, zCollate
1755 zWhere
= sqlite3_mprintf(
1756 "%z%s\"rbu_imp_%d%w\" IS ?", zWhere
, zAnd
, nBind
, zCol
1758 if( zRet
==0 || zImpPK
==0 || zImpCols
==0 || zWhere
==0 ) rc
= SQLITE_NOMEM
;
1764 rc2
= sqlite3_finalize(pXInfo
);
1765 if( rc
==SQLITE_OK
) rc
= rc2
;
1767 if( rc
!=SQLITE_OK
){
1769 sqlite3_free(zImpCols
);
1770 sqlite3_free(zImpPK
);
1771 sqlite3_free(zWhere
);
1779 *pzImposterCols
= zImpCols
;
1780 *pzImposterPk
= zImpPK
;
1787 ** Assuming the current table columns are "a", "b" and "c", and the zObj
1788 ** paramter is passed "old", return a string of the form:
1790 ** "old.a, old.b, old.b"
1792 ** With the column names escaped.
1794 ** For tables with implicit rowids - RBU_PK_EXTERNAL and RBU_PK_NONE, append
1795 ** the text ", old._rowid_" to the returned value.
1797 static char *rbuObjIterGetOldlist(
1803 if( p
->rc
==SQLITE_OK
&& pIter
->abIndexed
){
1804 const char *zS
= "";
1806 for(i
=0; i
<pIter
->nTblCol
; i
++){
1807 if( pIter
->abIndexed
[i
] ){
1808 const char *zCol
= pIter
->azTblCol
[i
];
1809 zList
= sqlite3_mprintf("%z%s%s.\"%w\"", zList
, zS
, zObj
, zCol
);
1811 zList
= sqlite3_mprintf("%z%sNULL", zList
, zS
);
1815 p
->rc
= SQLITE_NOMEM
;
1820 /* For a table with implicit rowids, append "old._rowid_" to the list. */
1821 if( pIter
->eType
==RBU_PK_EXTERNAL
|| pIter
->eType
==RBU_PK_NONE
){
1822 zList
= rbuMPrintf(p
, "%z, %s._rowid_", zList
, zObj
);
1829 ** Return an expression that can be used in a WHERE clause to match the
1830 ** primary key of the current table. For example, if the table is:
1832 ** CREATE TABLE t1(a, b, c, PRIMARY KEY(b, c));
1834 ** Return the string:
1836 ** "b = ?1 AND c = ?2"
1838 static char *rbuObjIterGetWhere(
1843 if( pIter
->eType
==RBU_PK_VTAB
|| pIter
->eType
==RBU_PK_NONE
){
1844 zList
= rbuMPrintf(p
, "_rowid_ = ?%d", pIter
->nTblCol
+1);
1845 }else if( pIter
->eType
==RBU_PK_EXTERNAL
){
1846 const char *zSep
= "";
1848 for(i
=0; i
<pIter
->nTblCol
; i
++){
1849 if( pIter
->abTblPk
[i
] ){
1850 zList
= rbuMPrintf(p
, "%z%sc%d=?%d", zList
, zSep
, i
, i
+1);
1854 zList
= rbuMPrintf(p
,
1855 "_rowid_ = (SELECT id FROM rbu_imposter2 WHERE %z)", zList
1859 const char *zSep
= "";
1861 for(i
=0; i
<pIter
->nTblCol
; i
++){
1862 if( pIter
->abTblPk
[i
] ){
1863 const char *zCol
= pIter
->azTblCol
[i
];
1864 zList
= rbuMPrintf(p
, "%z%s\"%w\"=?%d", zList
, zSep
, zCol
, i
+1);
1873 ** The SELECT statement iterating through the keys for the current object
1874 ** (p->objiter.pSelect) currently points to a valid row. However, there
1875 ** is something wrong with the rbu_control value in the rbu_control value
1876 ** stored in the (p->nCol+1)'th column. Set the error code and error message
1877 ** of the RBU handle to something reflecting this.
1879 static void rbuBadControlError(sqlite3rbu
*p
){
1880 p
->rc
= SQLITE_ERROR
;
1881 p
->zErrmsg
= sqlite3_mprintf("invalid rbu_control value");
1886 ** Return a nul-terminated string containing the comma separated list of
1887 ** assignments that should be included following the "SET" keyword of
1888 ** an UPDATE statement used to update the table object that the iterator
1889 ** passed as the second argument currently points to if the rbu_control
1890 ** column of the data_xxx table entry is set to zMask.
1892 ** The memory for the returned string is obtained from sqlite3_malloc().
1893 ** It is the responsibility of the caller to eventually free it using
1896 ** If an OOM error is encountered when allocating space for the new
1897 ** string, an error code is left in the rbu handle passed as the first
1898 ** argument and NULL is returned. Or, if an error has already occurred
1899 ** when this function is called, NULL is returned immediately, without
1900 ** attempting the allocation or modifying the stored error code.
1902 static char *rbuObjIterGetSetlist(
1908 if( p
->rc
==SQLITE_OK
){
1911 if( (int)strlen(zMask
)!=pIter
->nTblCol
){
1912 rbuBadControlError(p
);
1914 const char *zSep
= "";
1915 for(i
=0; i
<pIter
->nTblCol
; i
++){
1916 char c
= zMask
[pIter
->aiSrcOrder
[i
]];
1918 zList
= rbuMPrintf(p
, "%z%s\"%w\"=?%d",
1919 zList
, zSep
, pIter
->azTblCol
[i
], i
+1
1924 zList
= rbuMPrintf(p
, "%z%s\"%w\"=rbu_delta(\"%w\", ?%d)",
1925 zList
, zSep
, pIter
->azTblCol
[i
], pIter
->azTblCol
[i
], i
+1
1930 zList
= rbuMPrintf(p
, "%z%s\"%w\"=rbu_fossil_delta(\"%w\", ?%d)",
1931 zList
, zSep
, pIter
->azTblCol
[i
], pIter
->azTblCol
[i
], i
+1
1942 ** Return a nul-terminated string consisting of nByte comma separated
1943 ** "?" expressions. For example, if nByte is 3, return a pointer to
1944 ** a buffer containing the string "?,?,?".
1946 ** The memory for the returned string is obtained from sqlite3_malloc().
1947 ** It is the responsibility of the caller to eventually free it using
1950 ** If an OOM error is encountered when allocating space for the new
1951 ** string, an error code is left in the rbu handle passed as the first
1952 ** argument and NULL is returned. Or, if an error has already occurred
1953 ** when this function is called, NULL is returned immediately, without
1954 ** attempting the allocation or modifying the stored error code.
1956 static char *rbuObjIterGetBindlist(sqlite3rbu
*p
, int nBind
){
1958 sqlite3_int64 nByte
= 2*(sqlite3_int64
)nBind
+ 1;
1960 zRet
= (char*)rbuMalloc(p
, nByte
);
1963 for(i
=0; i
<nBind
; i
++){
1965 zRet
[i
*2+1] = (i
+1==nBind
) ? '\0' : ',';
1972 ** The iterator currently points to a table (not index) of type
1973 ** RBU_PK_WITHOUT_ROWID. This function creates the PRIMARY KEY
1974 ** declaration for the corresponding imposter table. For example,
1975 ** if the iterator points to a table created as:
1977 ** CREATE TABLE t1(a, b, c, PRIMARY KEY(b, a DESC)) WITHOUT ROWID
1979 ** this function returns:
1981 ** PRIMARY KEY("b", "a" DESC)
1983 static char *rbuWithoutRowidPK(sqlite3rbu
*p
, RbuObjIter
*pIter
){
1985 assert( pIter
->zIdx
==0 );
1986 if( p
->rc
==SQLITE_OK
){
1987 const char *zSep
= "PRIMARY KEY(";
1988 sqlite3_stmt
*pXList
= 0; /* PRAGMA index_list = (pIter->zTbl) */
1989 sqlite3_stmt
*pXInfo
= 0; /* PRAGMA index_xinfo = <pk-index> */
1991 p
->rc
= prepareFreeAndCollectError(p
->dbMain
, &pXList
, &p
->zErrmsg
,
1992 sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter
->zTbl
)
1994 while( p
->rc
==SQLITE_OK
&& SQLITE_ROW
==sqlite3_step(pXList
) ){
1995 const char *zOrig
= (const char*)sqlite3_column_text(pXList
,3);
1996 if( zOrig
&& strcmp(zOrig
, "pk")==0 ){
1997 const char *zIdx
= (const char*)sqlite3_column_text(pXList
,1);
1999 p
->rc
= prepareFreeAndCollectError(p
->dbMain
, &pXInfo
, &p
->zErrmsg
,
2000 sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx
)
2006 rbuFinalize(p
, pXList
);
2008 while( p
->rc
==SQLITE_OK
&& SQLITE_ROW
==sqlite3_step(pXInfo
) ){
2009 if( sqlite3_column_int(pXInfo
, 5) ){
2010 /* int iCid = sqlite3_column_int(pXInfo, 0); */
2011 const char *zCol
= (const char*)sqlite3_column_text(pXInfo
, 2);
2012 const char *zDesc
= sqlite3_column_int(pXInfo
, 3) ? " DESC" : "";
2013 z
= rbuMPrintf(p
, "%z%s\"%w\"%s", z
, zSep
, zCol
, zDesc
);
2017 z
= rbuMPrintf(p
, "%z)", z
);
2018 rbuFinalize(p
, pXInfo
);
2024 ** This function creates the second imposter table used when writing to
2025 ** a table b-tree where the table has an external primary key. If the
2026 ** iterator passed as the second argument does not currently point to
2027 ** a table (not index) with an external primary key, this function is a
2030 ** Assuming the iterator does point to a table with an external PK, this
2031 ** function creates a WITHOUT ROWID imposter table named "rbu_imposter2"
2032 ** used to access that PK index. For example, if the target table is
2033 ** declared as follows:
2035 ** CREATE TABLE t1(a, b TEXT, c REAL, PRIMARY KEY(b, c));
2037 ** then the imposter table schema is:
2039 ** CREATE TABLE rbu_imposter2(c1 TEXT, c2 REAL, id INTEGER) WITHOUT ROWID;
2042 static void rbuCreateImposterTable2(sqlite3rbu
*p
, RbuObjIter
*pIter
){
2043 if( p
->rc
==SQLITE_OK
&& pIter
->eType
==RBU_PK_EXTERNAL
){
2044 int tnum
= pIter
->iPkTnum
; /* Root page of PK index */
2045 sqlite3_stmt
*pQuery
= 0; /* SELECT name ... WHERE rootpage = $tnum */
2046 const char *zIdx
= 0; /* Name of PK index */
2047 sqlite3_stmt
*pXInfo
= 0; /* PRAGMA main.index_xinfo = $zIdx */
2048 const char *zComma
= "";
2049 char *zCols
= 0; /* Used to build up list of table cols */
2050 char *zPk
= 0; /* Used to build up table PK declaration */
2052 /* Figure out the name of the primary key index for the current table.
2053 ** This is needed for the argument to "PRAGMA index_xinfo". Set
2054 ** zIdx to point to a nul-terminated string containing this name. */
2055 p
->rc
= prepareAndCollectError(p
->dbMain
, &pQuery
, &p
->zErrmsg
,
2056 "SELECT name FROM sqlite_schema WHERE rootpage = ?"
2058 if( p
->rc
==SQLITE_OK
){
2059 sqlite3_bind_int(pQuery
, 1, tnum
);
2060 if( SQLITE_ROW
==sqlite3_step(pQuery
) ){
2061 zIdx
= (const char*)sqlite3_column_text(pQuery
, 0);
2065 p
->rc
= prepareFreeAndCollectError(p
->dbMain
, &pXInfo
, &p
->zErrmsg
,
2066 sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx
)
2069 rbuFinalize(p
, pQuery
);
2071 while( p
->rc
==SQLITE_OK
&& SQLITE_ROW
==sqlite3_step(pXInfo
) ){
2072 int bKey
= sqlite3_column_int(pXInfo
, 5);
2074 int iCid
= sqlite3_column_int(pXInfo
, 1);
2075 int bDesc
= sqlite3_column_int(pXInfo
, 3);
2076 const char *zCollate
= (const char*)sqlite3_column_text(pXInfo
, 4);
2077 zCols
= rbuMPrintf(p
, "%z%sc%d %s COLLATE %Q", zCols
, zComma
,
2078 iCid
, pIter
->azTblType
[iCid
], zCollate
2080 zPk
= rbuMPrintf(p
, "%z%sc%d%s", zPk
, zComma
, iCid
, bDesc
?" DESC":"");
2084 zCols
= rbuMPrintf(p
, "%z, id INTEGER", zCols
);
2085 rbuFinalize(p
, pXInfo
);
2087 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER
, p
->dbMain
, "main", 1, tnum
);
2088 rbuMPrintfExec(p
, p
->dbMain
,
2089 "CREATE TABLE rbu_imposter2(%z, PRIMARY KEY(%z)) WITHOUT ROWID",
2092 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER
, p
->dbMain
, "main", 0, 0);
2097 ** If an error has already occurred when this function is called, it
2098 ** immediately returns zero (without doing any work). Or, if an error
2099 ** occurs during the execution of this function, it sets the error code
2100 ** in the sqlite3rbu object indicated by the first argument and returns
2103 ** The iterator passed as the second argument is guaranteed to point to
2104 ** a table (not an index) when this function is called. This function
2105 ** attempts to create any imposter table required to write to the main
2106 ** table b-tree of the table before returning. Non-zero is returned if
2107 ** an imposter table are created, or zero otherwise.
2109 ** An imposter table is required in all cases except RBU_PK_VTAB. Only
2110 ** virtual tables are written to directly. The imposter table has the
2111 ** same schema as the actual target table (less any UNIQUE constraints).
2112 ** More precisely, the "same schema" means the same columns, types,
2113 ** collation sequences. For tables that do not have an external PRIMARY
2114 ** KEY, it also means the same PRIMARY KEY declaration.
2116 static void rbuCreateImposterTable(sqlite3rbu
*p
, RbuObjIter
*pIter
){
2117 if( p
->rc
==SQLITE_OK
&& pIter
->eType
!=RBU_PK_VTAB
){
2118 int tnum
= pIter
->iTnum
;
2119 const char *zComma
= "";
2122 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER
, p
->dbMain
, "main", 0, 1);
2124 for(iCol
=0; p
->rc
==SQLITE_OK
&& iCol
<pIter
->nTblCol
; iCol
++){
2125 const char *zPk
= "";
2126 const char *zCol
= pIter
->azTblCol
[iCol
];
2127 const char *zColl
= 0;
2129 p
->rc
= sqlite3_table_column_metadata(
2130 p
->dbMain
, "main", pIter
->zTbl
, zCol
, 0, &zColl
, 0, 0, 0
2133 if( pIter
->eType
==RBU_PK_IPK
&& pIter
->abTblPk
[iCol
] ){
2134 /* If the target table column is an "INTEGER PRIMARY KEY", add
2135 ** "PRIMARY KEY" to the imposter table column declaration. */
2136 zPk
= "PRIMARY KEY ";
2138 zSql
= rbuMPrintf(p
, "%z%s\"%w\" %s %sCOLLATE %Q%s",
2139 zSql
, zComma
, zCol
, pIter
->azTblType
[iCol
], zPk
, zColl
,
2140 (pIter
->abNotNull
[iCol
] ? " NOT NULL" : "")
2145 if( pIter
->eType
==RBU_PK_WITHOUT_ROWID
){
2146 char *zPk
= rbuWithoutRowidPK(p
, pIter
);
2148 zSql
= rbuMPrintf(p
, "%z, %z", zSql
, zPk
);
2152 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER
, p
->dbMain
, "main", 1, tnum
);
2153 rbuMPrintfExec(p
, p
->dbMain
, "CREATE TABLE \"rbu_imp_%w\"(%z)%s",
2155 (pIter
->eType
==RBU_PK_WITHOUT_ROWID
? " WITHOUT ROWID" : "")
2157 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER
, p
->dbMain
, "main", 0, 0);
2162 ** Prepare a statement used to insert rows into the "rbu_tmp_xxx" table.
2163 ** Specifically a statement of the form:
2165 ** INSERT INTO rbu_tmp_xxx VALUES(?, ?, ? ...);
2167 ** The number of bound variables is equal to the number of columns in
2168 ** the target table, plus one (for the rbu_control column), plus one more
2169 ** (for the rbu_rowid column) if the target table is an implicit IPK or
2172 static void rbuObjIterPrepareTmpInsert(
2175 const char *zCollist
,
2176 const char *zRbuRowid
2178 int bRbuRowid
= (pIter
->eType
==RBU_PK_EXTERNAL
|| pIter
->eType
==RBU_PK_NONE
);
2179 char *zBind
= rbuObjIterGetBindlist(p
, pIter
->nTblCol
+ 1 + bRbuRowid
);
2181 assert( pIter
->pTmpInsert
==0 );
2182 p
->rc
= prepareFreeAndCollectError(
2183 p
->dbRbu
, &pIter
->pTmpInsert
, &p
->zErrmsg
, sqlite3_mprintf(
2184 "INSERT INTO %s.'rbu_tmp_%q'(rbu_control,%s%s) VALUES(%z)",
2185 p
->zStateDb
, pIter
->zDataTbl
, zCollist
, zRbuRowid
, zBind
2190 static void rbuTmpInsertFunc(
2191 sqlite3_context
*pCtx
,
2193 sqlite3_value
**apVal
2195 sqlite3rbu
*p
= sqlite3_user_data(pCtx
);
2199 assert( sqlite3_value_int(apVal
[0])!=0
2200 || p
->objiter
.eType
==RBU_PK_EXTERNAL
2201 || p
->objiter
.eType
==RBU_PK_NONE
2203 if( sqlite3_value_int(apVal
[0])!=0 ){
2204 p
->nPhaseOneStep
+= p
->objiter
.nIndex
;
2207 for(i
=0; rc
==SQLITE_OK
&& i
<nVal
; i
++){
2208 rc
= sqlite3_bind_value(p
->objiter
.pTmpInsert
, i
+1, apVal
[i
]);
2210 if( rc
==SQLITE_OK
){
2211 sqlite3_step(p
->objiter
.pTmpInsert
);
2212 rc
= sqlite3_reset(p
->objiter
.pTmpInsert
);
2215 if( rc
!=SQLITE_OK
){
2216 sqlite3_result_error_code(pCtx
, rc
);
2220 static char *rbuObjIterGetIndexWhere(sqlite3rbu
*p
, RbuObjIter
*pIter
){
2221 sqlite3_stmt
*pStmt
= 0;
2225 assert( pIter
->zIdxSql
==0 && pIter
->nIdxCol
==0 && pIter
->aIdxCol
==0 );
2227 if( rc
==SQLITE_OK
){
2228 rc
= prepareAndCollectError(p
->dbMain
, &pStmt
, &p
->zErrmsg
,
2229 "SELECT trim(sql) FROM sqlite_schema WHERE type='index' AND name=?"
2232 if( rc
==SQLITE_OK
){
2234 rc
= sqlite3_bind_text(pStmt
, 1, pIter
->zIdx
, -1, SQLITE_STATIC
);
2235 if( rc
==SQLITE_OK
&& SQLITE_ROW
==sqlite3_step(pStmt
) ){
2236 char *zSql
= (char*)sqlite3_column_text(pStmt
, 0);
2238 pIter
->zIdxSql
= zSql
= rbuStrndup(zSql
, &rc
);
2241 int nParen
= 0; /* Number of open parenthesis */
2245 for(i
=0; zSql
[i
]; i
++){
2248 /* If necessary, grow the pIter->aIdxCol[] array */
2249 if( iIdxCol
==nIdxAlloc
){
2250 RbuSpan
*aIdxCol
= (RbuSpan
*)sqlite3_realloc(
2251 pIter
->aIdxCol
, (nIdxAlloc
+16)*sizeof(RbuSpan
)
2257 pIter
->aIdxCol
= aIdxCol
;
2263 assert( iIdxCol
==0 );
2264 pIter
->aIdxCol
[0].zSpan
= &zSql
[i
+1];
2271 int nSpan
= &zSql
[i
] - pIter
->aIdxCol
[iIdxCol
].zSpan
;
2272 pIter
->aIdxCol
[iIdxCol
++].nSpan
= nSpan
;
2276 }else if( c
==',' && nParen
==1 ){
2277 int nSpan
= &zSql
[i
] - pIter
->aIdxCol
[iIdxCol
].zSpan
;
2278 pIter
->aIdxCol
[iIdxCol
++].nSpan
= nSpan
;
2279 pIter
->aIdxCol
[iIdxCol
].zSpan
= &zSql
[i
+1];
2280 }else if( c
=='"' || c
=='\'' || c
=='`' ){
2283 if( zSql
[i
+1]!=c
) break;
2289 if( zSql
[i
]==']' ) break;
2291 }else if( c
=='-' && zSql
[i
+1]=='-' ){
2292 for(i
=i
+2; zSql
[i
] && zSql
[i
]!='\n'; i
++);
2293 if( zSql
[i
]=='\0' ) break;
2294 }else if( c
=='/' && zSql
[i
+1]=='*' ){
2295 for(i
=i
+2; zSql
[i
] && (zSql
[i
]!='*' || zSql
[i
+1]!='/'); i
++);
2296 if( zSql
[i
]=='\0' ) break;
2301 zRet
= rbuStrndup(&zSql
[i
], &rc
);
2303 pIter
->nIdxCol
= iIdxCol
;
2307 rc2
= sqlite3_finalize(pStmt
);
2308 if( rc
==SQLITE_OK
) rc
= rc2
;
2316 ** Ensure that the SQLite statement handles required to update the
2317 ** target database object currently indicated by the iterator passed
2318 ** as the second argument are available.
2320 static int rbuObjIterPrepareAll(
2323 int nOffset
/* Add "LIMIT -1 OFFSET $nOffset" to SELECT */
2325 assert( pIter
->bCleanup
==0 );
2326 if( pIter
->pSelect
==0 && rbuObjIterCacheTableInfo(p
, pIter
)==SQLITE_OK
){
2327 const int tnum
= pIter
->iTnum
;
2328 char *zCollist
= 0; /* List of indexed columns */
2329 char **pz
= &p
->zErrmsg
;
2330 const char *zIdx
= pIter
->zIdx
;
2334 zLimit
= sqlite3_mprintf(" LIMIT -1 OFFSET %d", nOffset
);
2335 if( !zLimit
) p
->rc
= SQLITE_NOMEM
;
2339 const char *zTbl
= pIter
->zTbl
;
2340 char *zImposterCols
= 0; /* Columns for imposter table */
2341 char *zImposterPK
= 0; /* Primary key declaration for imposter */
2342 char *zWhere
= 0; /* WHERE clause on PK columns */
2347 assert( pIter
->eType
!=RBU_PK_VTAB
);
2348 zPart
= rbuObjIterGetIndexWhere(p
, pIter
);
2349 zCollist
= rbuObjIterGetIndexCols(
2350 p
, pIter
, &zImposterCols
, &zImposterPK
, &zWhere
, &nBind
2352 zBind
= rbuObjIterGetBindlist(p
, nBind
);
2354 /* Create the imposter table used to write to this index. */
2355 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER
, p
->dbMain
, "main", 0, 1);
2356 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER
, p
->dbMain
, "main", 1,tnum
);
2357 rbuMPrintfExec(p
, p
->dbMain
,
2358 "CREATE TABLE \"rbu_imp_%w\"( %s, PRIMARY KEY( %s ) ) WITHOUT ROWID",
2359 zTbl
, zImposterCols
, zImposterPK
2361 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER
, p
->dbMain
, "main", 0, 0);
2363 /* Create the statement to insert index entries */
2364 pIter
->nCol
= nBind
;
2365 if( p
->rc
==SQLITE_OK
){
2366 p
->rc
= prepareFreeAndCollectError(
2367 p
->dbMain
, &pIter
->pInsert
, &p
->zErrmsg
,
2368 sqlite3_mprintf("INSERT INTO \"rbu_imp_%w\" VALUES(%s)", zTbl
, zBind
)
2372 /* And to delete index entries */
2373 if( rbuIsVacuum(p
)==0 && p
->rc
==SQLITE_OK
){
2374 p
->rc
= prepareFreeAndCollectError(
2375 p
->dbMain
, &pIter
->pDelete
, &p
->zErrmsg
,
2376 sqlite3_mprintf("DELETE FROM \"rbu_imp_%w\" WHERE %s", zTbl
, zWhere
)
2380 /* Create the SELECT statement to read keys in sorted order */
2381 if( p
->rc
==SQLITE_OK
){
2383 if( rbuIsVacuum(p
) ){
2386 zStart
= rbuVacuumIndexStart(p
, pIter
);
2388 sqlite3_free(zLimit
);
2393 zSql
= sqlite3_mprintf(
2394 "SELECT %s, 0 AS rbu_control FROM '%q' %s %s %s ORDER BY %s%s",
2398 (zStart
? (zPart
? "AND" : "WHERE") : ""), zStart
,
2401 sqlite3_free(zStart
);
2404 if( pIter
->eType
==RBU_PK_EXTERNAL
|| pIter
->eType
==RBU_PK_NONE
){
2405 zSql
= sqlite3_mprintf(
2406 "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' %s ORDER BY %s%s",
2407 zCollist
, p
->zStateDb
, pIter
->zDataTbl
,
2408 zPart
, zCollist
, zLimit
2411 zSql
= sqlite3_mprintf(
2412 "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' %s "
2414 "SELECT %s, rbu_control FROM '%q' "
2415 "%s %s typeof(rbu_control)='integer' AND rbu_control!=1 "
2417 zCollist
, p
->zStateDb
, pIter
->zDataTbl
, zPart
,
2418 zCollist
, pIter
->zDataTbl
,
2420 (zPart
? "AND" : "WHERE"),
2424 if( p
->rc
==SQLITE_OK
){
2425 p
->rc
= prepareFreeAndCollectError(p
->dbRbu
,&pIter
->pSelect
,pz
,zSql
);
2431 sqlite3_free(zImposterCols
);
2432 sqlite3_free(zImposterPK
);
2433 sqlite3_free(zWhere
);
2434 sqlite3_free(zBind
);
2435 sqlite3_free(zPart
);
2437 int bRbuRowid
= (pIter
->eType
==RBU_PK_VTAB
)
2438 ||(pIter
->eType
==RBU_PK_NONE
)
2439 ||(pIter
->eType
==RBU_PK_EXTERNAL
&& rbuIsVacuum(p
));
2440 const char *zTbl
= pIter
->zTbl
; /* Table this step applies to */
2441 const char *zWrite
; /* Imposter table name */
2443 char *zBindings
= rbuObjIterGetBindlist(p
, pIter
->nTblCol
+ bRbuRowid
);
2444 char *zWhere
= rbuObjIterGetWhere(p
, pIter
);
2445 char *zOldlist
= rbuObjIterGetOldlist(p
, pIter
, "old");
2446 char *zNewlist
= rbuObjIterGetOldlist(p
, pIter
, "new");
2448 zCollist
= rbuObjIterGetCollist(p
, pIter
);
2449 pIter
->nCol
= pIter
->nTblCol
;
2451 /* Create the imposter table or tables (if required). */
2452 rbuCreateImposterTable(p
, pIter
);
2453 rbuCreateImposterTable2(p
, pIter
);
2454 zWrite
= (pIter
->eType
==RBU_PK_VTAB
? "" : "rbu_imp_");
2456 /* Create the INSERT statement to write to the target PK b-tree */
2457 if( p
->rc
==SQLITE_OK
){
2458 p
->rc
= prepareFreeAndCollectError(p
->dbMain
, &pIter
->pInsert
, pz
,
2460 "INSERT INTO \"%s%w\"(%s%s) VALUES(%s)",
2461 zWrite
, zTbl
, zCollist
, (bRbuRowid
? ", _rowid_" : ""), zBindings
2466 /* Create the DELETE statement to write to the target PK b-tree.
2467 ** Because it only performs INSERT operations, this is not required for
2468 ** an rbu vacuum handle. */
2469 if( rbuIsVacuum(p
)==0 && p
->rc
==SQLITE_OK
){
2470 p
->rc
= prepareFreeAndCollectError(p
->dbMain
, &pIter
->pDelete
, pz
,
2472 "DELETE FROM \"%s%w\" WHERE %s", zWrite
, zTbl
, zWhere
2477 if( rbuIsVacuum(p
)==0 && pIter
->abIndexed
){
2478 const char *zRbuRowid
= "";
2479 if( pIter
->eType
==RBU_PK_EXTERNAL
|| pIter
->eType
==RBU_PK_NONE
){
2480 zRbuRowid
= ", rbu_rowid";
2483 /* Create the rbu_tmp_xxx table and the triggers to populate it. */
2484 rbuMPrintfExec(p
, p
->dbRbu
,
2485 "CREATE TABLE IF NOT EXISTS %s.'rbu_tmp_%q' AS "
2486 "SELECT *%s FROM '%q' WHERE 0;"
2487 , p
->zStateDb
, pIter
->zDataTbl
2488 , (pIter
->eType
==RBU_PK_EXTERNAL
? ", 0 AS rbu_rowid" : "")
2492 rbuMPrintfExec(p
, p
->dbMain
,
2493 "CREATE TEMP TRIGGER rbu_delete_tr BEFORE DELETE ON \"%s%w\" "
2495 " SELECT rbu_tmp_insert(3, %s);"
2498 "CREATE TEMP TRIGGER rbu_update1_tr BEFORE UPDATE ON \"%s%w\" "
2500 " SELECT rbu_tmp_insert(3, %s);"
2503 "CREATE TEMP TRIGGER rbu_update2_tr AFTER UPDATE ON \"%s%w\" "
2505 " SELECT rbu_tmp_insert(4, %s);"
2507 zWrite
, zTbl
, zOldlist
,
2508 zWrite
, zTbl
, zOldlist
,
2509 zWrite
, zTbl
, zNewlist
2512 if( pIter
->eType
==RBU_PK_EXTERNAL
|| pIter
->eType
==RBU_PK_NONE
){
2513 rbuMPrintfExec(p
, p
->dbMain
,
2514 "CREATE TEMP TRIGGER rbu_insert_tr AFTER INSERT ON \"%s%w\" "
2516 " SELECT rbu_tmp_insert(0, %s);"
2518 zWrite
, zTbl
, zNewlist
2522 rbuObjIterPrepareTmpInsert(p
, pIter
, zCollist
, zRbuRowid
);
2525 /* Create the SELECT statement to read keys from data_xxx */
2526 if( p
->rc
==SQLITE_OK
){
2527 const char *zRbuRowid
= "";
2531 zRbuRowid
= rbuIsVacuum(p
) ? ",_rowid_ " : ",rbu_rowid";
2534 if( rbuIsVacuum(p
) ){
2536 zStart
= rbuVacuumTableStart(p
, pIter
, bRbuRowid
, zWrite
);
2538 sqlite3_free(zLimit
);
2543 zOrder
= rbuMPrintf(p
, "_rowid_");
2545 zOrder
= rbuObjIterGetPkList(p
, pIter
, "", ", ", "");
2549 if( p
->rc
==SQLITE_OK
){
2550 p
->rc
= prepareFreeAndCollectError(p
->dbRbu
, &pIter
->pSelect
, pz
,
2552 "SELECT %s,%s rbu_control%s FROM '%q'%s %s %s %s",
2554 (rbuIsVacuum(p
) ? "0 AS " : ""),
2556 pIter
->zDataTbl
, (zStart
? zStart
: ""),
2557 (zOrder
? "ORDER BY" : ""), zOrder
,
2562 sqlite3_free(zStart
);
2563 sqlite3_free(zOrder
);
2566 sqlite3_free(zWhere
);
2567 sqlite3_free(zOldlist
);
2568 sqlite3_free(zNewlist
);
2569 sqlite3_free(zBindings
);
2571 sqlite3_free(zCollist
);
2572 sqlite3_free(zLimit
);
2579 ** Set output variable *ppStmt to point to an UPDATE statement that may
2580 ** be used to update the imposter table for the main table b-tree of the
2581 ** table object that pIter currently points to, assuming that the
2582 ** rbu_control column of the data_xyz table contains zMask.
2584 ** If the zMask string does not specify any columns to update, then this
2585 ** is not an error. Output variable *ppStmt is set to NULL in this case.
2587 static int rbuGetUpdateStmt(
2588 sqlite3rbu
*p
, /* RBU handle */
2589 RbuObjIter
*pIter
, /* Object iterator */
2590 const char *zMask
, /* rbu_control value ('x.x.') */
2591 sqlite3_stmt
**ppStmt
/* OUT: UPDATE statement handle */
2594 RbuUpdateStmt
*pUp
= 0;
2597 /* In case an error occurs */
2600 /* Search for an existing statement. If one is found, shift it to the front
2601 ** of the LRU queue and return immediately. Otherwise, leave nUp pointing
2602 ** to the number of statements currently in the cache and pUp to the
2603 ** last object in the list. */
2604 for(pp
=&pIter
->pRbuUpdate
; *pp
; pp
=&((*pp
)->pNext
)){
2606 if( strcmp(pUp
->zMask
, zMask
)==0 ){
2608 pUp
->pNext
= pIter
->pRbuUpdate
;
2609 pIter
->pRbuUpdate
= pUp
;
2610 *ppStmt
= pUp
->pUpdate
;
2615 assert( pUp
==0 || pUp
->pNext
==0 );
2617 if( nUp
>=SQLITE_RBU_UPDATE_CACHESIZE
){
2618 for(pp
=&pIter
->pRbuUpdate
; *pp
!=pUp
; pp
=&((*pp
)->pNext
));
2620 sqlite3_finalize(pUp
->pUpdate
);
2623 pUp
= (RbuUpdateStmt
*)rbuMalloc(p
, sizeof(RbuUpdateStmt
)+pIter
->nTblCol
+1);
2627 char *zWhere
= rbuObjIterGetWhere(p
, pIter
);
2628 char *zSet
= rbuObjIterGetSetlist(p
, pIter
, zMask
);
2631 pUp
->zMask
= (char*)&pUp
[1];
2632 memcpy(pUp
->zMask
, zMask
, pIter
->nTblCol
);
2633 pUp
->pNext
= pIter
->pRbuUpdate
;
2634 pIter
->pRbuUpdate
= pUp
;
2637 const char *zPrefix
= "";
2639 if( pIter
->eType
!=RBU_PK_VTAB
) zPrefix
= "rbu_imp_";
2640 zUpdate
= sqlite3_mprintf("UPDATE \"%s%w\" SET %s WHERE %s",
2641 zPrefix
, pIter
->zTbl
, zSet
, zWhere
2643 p
->rc
= prepareFreeAndCollectError(
2644 p
->dbMain
, &pUp
->pUpdate
, &p
->zErrmsg
, zUpdate
2646 *ppStmt
= pUp
->pUpdate
;
2648 sqlite3_free(zWhere
);
2655 static sqlite3
*rbuOpenDbhandle(
2661 if( p
->rc
==SQLITE_OK
){
2662 const int flags
= SQLITE_OPEN_READWRITE
|SQLITE_OPEN_CREATE
|SQLITE_OPEN_URI
;
2663 p
->rc
= sqlite3_open_v2(zName
, &db
, flags
, bUseVfs
? p
->zVfsName
: 0);
2665 p
->zErrmsg
= sqlite3_mprintf("%s", sqlite3_errmsg(db
));
2674 ** Free an RbuState object allocated by rbuLoadState().
2676 static void rbuFreeState(RbuState
*p
){
2678 sqlite3_free(p
->zTbl
);
2679 sqlite3_free(p
->zDataTbl
);
2680 sqlite3_free(p
->zIdx
);
2686 ** Allocate an RbuState object and load the contents of the rbu_state
2687 ** table into it. Return a pointer to the new object. It is the
2688 ** responsibility of the caller to eventually free the object using
2691 ** If an error occurs, leave an error code and message in the rbu handle
2694 static RbuState
*rbuLoadState(sqlite3rbu
*p
){
2696 sqlite3_stmt
*pStmt
= 0;
2700 pRet
= (RbuState
*)rbuMalloc(p
, sizeof(RbuState
));
2701 if( pRet
==0 ) return 0;
2703 rc
= prepareFreeAndCollectError(p
->dbRbu
, &pStmt
, &p
->zErrmsg
,
2704 sqlite3_mprintf("SELECT k, v FROM %s.rbu_state", p
->zStateDb
)
2706 while( rc
==SQLITE_OK
&& SQLITE_ROW
==sqlite3_step(pStmt
) ){
2707 switch( sqlite3_column_int(pStmt
, 0) ){
2708 case RBU_STATE_STAGE
:
2709 pRet
->eStage
= sqlite3_column_int(pStmt
, 1);
2710 if( pRet
->eStage
!=RBU_STAGE_OAL
2711 && pRet
->eStage
!=RBU_STAGE_MOVE
2712 && pRet
->eStage
!=RBU_STAGE_CKPT
2714 p
->rc
= SQLITE_CORRUPT
;
2719 pRet
->zTbl
= rbuStrndup((char*)sqlite3_column_text(pStmt
, 1), &rc
);
2723 pRet
->zIdx
= rbuStrndup((char*)sqlite3_column_text(pStmt
, 1), &rc
);
2727 pRet
->nRow
= sqlite3_column_int(pStmt
, 1);
2730 case RBU_STATE_PROGRESS
:
2731 pRet
->nProgress
= sqlite3_column_int64(pStmt
, 1);
2734 case RBU_STATE_CKPT
:
2735 pRet
->iWalCksum
= sqlite3_column_int64(pStmt
, 1);
2738 case RBU_STATE_COOKIE
:
2739 pRet
->iCookie
= (u32
)sqlite3_column_int64(pStmt
, 1);
2742 case RBU_STATE_OALSZ
:
2743 pRet
->iOalSz
= sqlite3_column_int64(pStmt
, 1);
2746 case RBU_STATE_PHASEONESTEP
:
2747 pRet
->nPhaseOneStep
= sqlite3_column_int64(pStmt
, 1);
2750 case RBU_STATE_DATATBL
:
2751 pRet
->zDataTbl
= rbuStrndup((char*)sqlite3_column_text(pStmt
, 1), &rc
);
2755 rc
= SQLITE_CORRUPT
;
2759 rc2
= sqlite3_finalize(pStmt
);
2760 if( rc
==SQLITE_OK
) rc
= rc2
;
2768 ** Open the database handle and attach the RBU database as "rbu". If an
2769 ** error occurs, leave an error code and message in the RBU handle.
2771 ** If argument dbMain is not NULL, then it is a database handle already
2772 ** open on the target database. Use this handle instead of opening a new
2775 static void rbuOpenDatabase(sqlite3rbu
*p
, sqlite3
*dbMain
, int *pbRetry
){
2776 assert( p
->rc
|| (p
->dbMain
==0 && p
->dbRbu
==0) );
2777 assert( p
->rc
|| rbuIsVacuum(p
) || p
->zTarget
!=0 );
2778 assert( dbMain
==0 || rbuIsVacuum(p
)==0 );
2780 /* Open the RBU database */
2781 p
->dbRbu
= rbuOpenDbhandle(p
, p
->zRbu
, 1);
2784 if( p
->rc
==SQLITE_OK
&& rbuIsVacuum(p
) ){
2785 sqlite3_file_control(p
->dbRbu
, "main", SQLITE_FCNTL_RBUCNT
, (void*)p
);
2787 const char *zFile
= sqlite3_db_filename(p
->dbRbu
, "main");
2788 p
->zState
= rbuMPrintf(p
, "file:///%s-vacuum?modeof=%s", zFile
, zFile
);
2792 /* If using separate RBU and state databases, attach the state database to
2793 ** the RBU db handle now. */
2795 rbuMPrintfExec(p
, p
->dbRbu
, "ATTACH %Q AS stat", p
->zState
);
2796 memcpy(p
->zStateDb
, "stat", 4);
2798 memcpy(p
->zStateDb
, "main", 4);
2802 if( p
->rc
==SQLITE_OK
&& rbuIsVacuum(p
) ){
2803 p
->rc
= sqlite3_exec(p
->dbRbu
, "BEGIN", 0, 0, 0);
2807 /* If it has not already been created, create the rbu_state table */
2808 rbuMPrintfExec(p
, p
->dbRbu
, RBU_CREATE_STATE
, p
->zStateDb
);
2811 if( rbuIsVacuum(p
) ){
2812 if( p
->rc
==SQLITE_OK
){
2815 sqlite3_stmt
*pCnt
= 0;
2816 p
->rc
= prepareAndCollectError(p
->dbRbu
, &pCnt
, &p
->zErrmsg
,
2817 "SELECT count(*) FROM stat.sqlite_schema"
2819 if( p
->rc
==SQLITE_OK
2820 && sqlite3_step(pCnt
)==SQLITE_ROW
2821 && 1==sqlite3_column_int(pCnt
, 0)
2825 rc2
= sqlite3_finalize(pCnt
);
2826 if( p
->rc
==SQLITE_OK
) p
->rc
= rc2
;
2828 if( p
->rc
==SQLITE_OK
&& bOk
==0 ){
2829 p
->rc
= SQLITE_ERROR
;
2830 p
->zErrmsg
= sqlite3_mprintf("invalid state database");
2833 if( p
->rc
==SQLITE_OK
){
2834 p
->rc
= sqlite3_exec(p
->dbRbu
, "COMMIT", 0, 0, 0);
2840 if( p
->rc
==SQLITE_OK
&& rbuIsVacuum(p
) ){
2845 rc
= sqlite3_file_control(p
->dbRbu
, "main", SQLITE_FCNTL_RBUCNT
, (void*)p
);
2846 if( rc
!=SQLITE_NOTFOUND
) p
->rc
= rc
;
2847 if( p
->eStage
>=RBU_STAGE_MOVE
){
2850 RbuState
*pState
= rbuLoadState(p
);
2852 bOpen
= (pState
->eStage
>=RBU_STAGE_MOVE
);
2853 rbuFreeState(pState
);
2856 if( bOpen
) p
->dbMain
= rbuOpenDbhandle(p
, p
->zRbu
, p
->nRbu
<=1);
2860 if( p
->rc
==SQLITE_OK
&& p
->dbMain
==0 ){
2861 if( !rbuIsVacuum(p
) ){
2862 p
->dbMain
= rbuOpenDbhandle(p
, p
->zTarget
, 1);
2863 }else if( p
->pRbuFd
->pWalFd
){
2865 p
->pRbuFd
->bNolock
= 0;
2866 sqlite3_close(p
->dbRbu
);
2867 sqlite3_close(p
->dbMain
);
2873 p
->rc
= SQLITE_ERROR
;
2874 p
->zErrmsg
= sqlite3_mprintf("cannot vacuum wal mode database");
2878 if( strlen(p
->zRbu
)>=5 && 0==memcmp("file:", p
->zRbu
, 5) ){
2879 zExtra
= &p
->zRbu
[5];
2881 if( *zExtra
++=='?' ) break;
2883 if( *zExtra
=='\0' ) zExtra
= 0;
2886 zTarget
= sqlite3_mprintf("file:%s-vactmp?rbu_memory=1%s%s",
2887 sqlite3_db_filename(p
->dbRbu
, "main"),
2888 (zExtra
==0 ? "" : "&"), (zExtra
==0 ? "" : zExtra
)
2892 p
->rc
= SQLITE_NOMEM
;
2895 p
->dbMain
= rbuOpenDbhandle(p
, zTarget
, p
->nRbu
<=1);
2896 sqlite3_free(zTarget
);
2900 if( p
->rc
==SQLITE_OK
){
2901 p
->rc
= sqlite3_create_function(p
->dbMain
,
2902 "rbu_tmp_insert", -1, SQLITE_UTF8
, (void*)p
, rbuTmpInsertFunc
, 0, 0
2906 if( p
->rc
==SQLITE_OK
){
2907 p
->rc
= sqlite3_create_function(p
->dbMain
,
2908 "rbu_fossil_delta", 2, SQLITE_UTF8
, 0, rbuFossilDeltaFunc
, 0, 0
2912 if( p
->rc
==SQLITE_OK
){
2913 p
->rc
= sqlite3_create_function(p
->dbRbu
,
2914 "rbu_target_name", -1, SQLITE_UTF8
, (void*)p
, rbuTargetNameFunc
, 0, 0
2918 if( p
->rc
==SQLITE_OK
){
2919 p
->rc
= sqlite3_file_control(p
->dbMain
, "main", SQLITE_FCNTL_RBU
, (void*)p
);
2921 rbuMPrintfExec(p
, p
->dbMain
, "SELECT * FROM sqlite_schema");
2923 /* Mark the database file just opened as an RBU target database. If
2924 ** this call returns SQLITE_NOTFOUND, then the RBU vfs is not in use.
2925 ** This is an error. */
2926 if( p
->rc
==SQLITE_OK
){
2927 p
->rc
= sqlite3_file_control(p
->dbMain
, "main", SQLITE_FCNTL_RBU
, (void*)p
);
2930 if( p
->rc
==SQLITE_NOTFOUND
){
2931 p
->rc
= SQLITE_ERROR
;
2932 p
->zErrmsg
= sqlite3_mprintf("rbu vfs not found");
2937 ** This routine is a copy of the sqlite3FileSuffix3() routine from the core.
2938 ** It is a no-op unless SQLITE_ENABLE_8_3_NAMES is defined.
2940 ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
2941 ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
2942 ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
2943 ** three characters, then shorten the suffix on z[] to be the last three
2944 ** characters of the original suffix.
2946 ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
2947 ** do the suffix shortening regardless of URI parameter.
2951 ** test.db-journal => test.nal
2952 ** test.db-wal => test.wal
2953 ** test.db-shm => test.shm
2954 ** test.db-mj7f3319fa => test.9fa
2956 static void rbuFileSuffix3(const char *zBase
, char *z
){
2957 #ifdef SQLITE_ENABLE_8_3_NAMES
2958 #if SQLITE_ENABLE_8_3_NAMES<2
2959 if( sqlite3_uri_boolean(zBase
, "8_3_names", 0) )
2963 sz
= (int)strlen(z
)&0xffffff;
2964 for(i
=sz
-1; i
>0 && z
[i
]!='/' && z
[i
]!='.'; i
--){}
2965 if( z
[i
]=='.' && sz
>i
+4 ) memmove(&z
[i
+1], &z
[sz
-3], 4);
2971 ** Return the current wal-index header checksum for the target database
2972 ** as a 64-bit integer.
2974 ** The checksum is store in the first page of xShmMap memory as an 8-byte
2975 ** blob starting at byte offset 40.
2977 static i64
rbuShmChecksum(sqlite3rbu
*p
){
2979 if( p
->rc
==SQLITE_OK
){
2980 sqlite3_file
*pDb
= p
->pTargetFd
->pReal
;
2982 p
->rc
= pDb
->pMethods
->xShmMap(pDb
, 0, 32*1024, 0, (void volatile**)&ptr
);
2983 if( p
->rc
==SQLITE_OK
){
2984 iRet
= (i64
)(((u64
)ptr
[10] << 32) + ptr
[11]);
2991 ** This function is called as part of initializing or reinitializing an
2992 ** incremental checkpoint.
2994 ** It populates the sqlite3rbu.aFrame[] array with the set of
2995 ** (wal frame -> db page) copy operations required to checkpoint the
2996 ** current wal file, and obtains the set of shm locks required to safely
2997 ** perform the copy operations directly on the file-system.
2999 ** If argument pState is not NULL, then the incremental checkpoint is
3000 ** being resumed. In this case, if the checksum of the wal-index-header
3001 ** following recovery is not the same as the checksum saved in the RbuState
3002 ** object, then the rbu handle is set to DONE state. This occurs if some
3003 ** other client appends a transaction to the wal file in the middle of
3004 ** an incremental checkpoint.
3006 static void rbuSetupCheckpoint(sqlite3rbu
*p
, RbuState
*pState
){
3008 /* If pState is NULL, then the wal file may not have been opened and
3009 ** recovered. Running a read-statement here to ensure that doing so
3010 ** does not interfere with the "capture" process below. */
3013 if( p
->rc
==SQLITE_OK
){
3014 p
->rc
= sqlite3_exec(p
->dbMain
, "SELECT * FROM sqlite_schema", 0, 0, 0);
3018 /* Assuming no error has occurred, run a "restart" checkpoint with the
3019 ** sqlite3rbu.eStage variable set to CAPTURE. This turns on the following
3020 ** special behaviour in the rbu VFS:
3022 ** * If the exclusive shm WRITER or READ0 lock cannot be obtained,
3023 ** the checkpoint fails with SQLITE_BUSY (normally SQLite would
3024 ** proceed with running a passive checkpoint instead of failing).
3026 ** * Attempts to read from the *-wal file or write to the database file
3027 ** do not perform any IO. Instead, the frame/page combinations that
3028 ** would be read/written are recorded in the sqlite3rbu.aFrame[]
3031 ** * Calls to xShmLock(UNLOCK) to release the exclusive shm WRITER,
3032 ** READ0 and CHECKPOINT locks taken as part of the checkpoint are
3033 ** no-ops. These locks will not be released until the connection
3036 ** * Attempting to xSync() the database file causes an SQLITE_NOTICE
3039 ** As a result, unless an error (i.e. OOM or SQLITE_BUSY) occurs, the
3040 ** checkpoint below fails with SQLITE_NOTICE, and leaves the aFrame[]
3041 ** array populated with a set of (frame -> page) mappings. Because the
3042 ** WRITER, CHECKPOINT and READ0 locks are still held, it is safe to copy
3043 ** data from the wal file into the database file according to the
3044 ** contents of aFrame[].
3046 if( p
->rc
==SQLITE_OK
){
3048 p
->eStage
= RBU_STAGE_CAPTURE
;
3049 rc2
= sqlite3_exec(p
->dbMain
, "PRAGMA main.wal_checkpoint=restart", 0, 0,0);
3050 if( rc2
!=SQLITE_NOTICE
) p
->rc
= rc2
;
3053 if( p
->rc
==SQLITE_OK
&& p
->nFrame
>0 ){
3054 p
->eStage
= RBU_STAGE_CKPT
;
3055 p
->nStep
= (pState
? pState
->nRow
: 0);
3056 p
->aBuf
= rbuMalloc(p
, p
->pgsz
);
3057 p
->iWalCksum
= rbuShmChecksum(p
);
3060 if( p
->rc
==SQLITE_OK
){
3061 if( p
->nFrame
==0 || (pState
&& pState
->iWalCksum
!=p
->iWalCksum
) ){
3062 p
->rc
= SQLITE_DONE
;
3063 p
->eStage
= RBU_STAGE_DONE
;
3066 sqlite3_file
*pDb
= p
->pTargetFd
->pReal
;
3067 sqlite3_file
*pWal
= p
->pTargetFd
->pWalFd
->pReal
;
3068 assert( p
->nPagePerSector
==0 );
3069 nSectorSize
= pDb
->pMethods
->xSectorSize(pDb
);
3070 if( nSectorSize
>p
->pgsz
){
3071 p
->nPagePerSector
= nSectorSize
/ p
->pgsz
;
3073 p
->nPagePerSector
= 1;
3076 /* Call xSync() on the wal file. This causes SQLite to sync the
3077 ** directory in which the target database and the wal file reside, in
3078 ** case it has not been synced since the rename() call in
3079 ** rbuMoveOalFile(). */
3080 p
->rc
= pWal
->pMethods
->xSync(pWal
, SQLITE_SYNC_NORMAL
);
3086 ** Called when iAmt bytes are read from offset iOff of the wal file while
3087 ** the rbu object is in capture mode. Record the frame number of the frame
3088 ** being read in the aFrame[] array.
3090 static int rbuCaptureWalRead(sqlite3rbu
*pRbu
, i64 iOff
, int iAmt
){
3091 const u32 mReq
= (1<<WAL_LOCK_WRITE
)|(1<<WAL_LOCK_CKPT
)|(1<<WAL_LOCK_READ0
);
3094 if( pRbu
->mLock
!=mReq
){
3095 pRbu
->rc
= SQLITE_BUSY
;
3096 return SQLITE_NOTICE_RBU
;
3100 if( pRbu
->nFrame
==pRbu
->nFrameAlloc
){
3101 int nNew
= (pRbu
->nFrameAlloc
? pRbu
->nFrameAlloc
: 64) * 2;
3103 aNew
= (RbuFrame
*)sqlite3_realloc64(pRbu
->aFrame
, nNew
* sizeof(RbuFrame
));
3104 if( aNew
==0 ) return SQLITE_NOMEM
;
3105 pRbu
->aFrame
= aNew
;
3106 pRbu
->nFrameAlloc
= nNew
;
3109 iFrame
= (u32
)((iOff
-32) / (i64
)(iAmt
+24)) + 1;
3110 if( pRbu
->iMaxFrame
<iFrame
) pRbu
->iMaxFrame
= iFrame
;
3111 pRbu
->aFrame
[pRbu
->nFrame
].iWalFrame
= iFrame
;
3112 pRbu
->aFrame
[pRbu
->nFrame
].iDbPage
= 0;
3118 ** Called when a page of data is written to offset iOff of the database
3119 ** file while the rbu handle is in capture mode. Record the page number
3120 ** of the page being written in the aFrame[] array.
3122 static int rbuCaptureDbWrite(sqlite3rbu
*pRbu
, i64 iOff
){
3123 pRbu
->aFrame
[pRbu
->nFrame
-1].iDbPage
= (u32
)(iOff
/ pRbu
->pgsz
) + 1;
3128 ** This is called as part of an incremental checkpoint operation. Copy
3129 ** a single frame of data from the wal file into the database file, as
3130 ** indicated by the RbuFrame object.
3132 static void rbuCheckpointFrame(sqlite3rbu
*p
, RbuFrame
*pFrame
){
3133 sqlite3_file
*pWal
= p
->pTargetFd
->pWalFd
->pReal
;
3134 sqlite3_file
*pDb
= p
->pTargetFd
->pReal
;
3137 assert( p
->rc
==SQLITE_OK
);
3138 iOff
= (i64
)(pFrame
->iWalFrame
-1) * (p
->pgsz
+ 24) + 32 + 24;
3139 p
->rc
= pWal
->pMethods
->xRead(pWal
, p
->aBuf
, p
->pgsz
, iOff
);
3142 iOff
= (i64
)(pFrame
->iDbPage
-1) * p
->pgsz
;
3143 p
->rc
= pDb
->pMethods
->xWrite(pDb
, p
->aBuf
, p
->pgsz
, iOff
);
3147 ** This value is copied from the definition of ZIPVFS_CTRL_FILE_POINTER
3150 #define RBU_ZIPVFS_CTRL_FILE_POINTER 230439
3153 ** Take an EXCLUSIVE lock on the database file. Return SQLITE_OK if
3154 ** successful, or an SQLite error code otherwise.
3156 static int rbuLockDatabase(sqlite3
*db
){
3158 sqlite3_file
*fd
= 0;
3160 sqlite3_file_control(db
, "main", RBU_ZIPVFS_CTRL_FILE_POINTER
, &fd
);
3162 sqlite3_file_control(db
, "main", SQLITE_FCNTL_FILE_POINTER
, &fd
);
3163 rc
= fd
->pMethods
->xLock(fd
, SQLITE_LOCK_SHARED
);
3164 if( rc
==SQLITE_OK
){
3165 rc
= fd
->pMethods
->xUnlock(fd
, SQLITE_LOCK_NONE
);
3167 sqlite3_file_control(db
, "main", RBU_ZIPVFS_CTRL_FILE_POINTER
, &fd
);
3169 sqlite3_file_control(db
, "main", SQLITE_FCNTL_FILE_POINTER
, &fd
);
3172 if( rc
==SQLITE_OK
&& fd
->pMethods
){
3173 rc
= fd
->pMethods
->xLock(fd
, SQLITE_LOCK_SHARED
);
3174 if( rc
==SQLITE_OK
){
3175 rc
= fd
->pMethods
->xLock(fd
, SQLITE_LOCK_EXCLUSIVE
);
3182 ** Return true if the database handle passed as the only argument
3183 ** was opened with the rbu_exclusive_checkpoint=1 URI parameter
3184 ** specified. Or false otherwise.
3186 static int rbuExclusiveCheckpoint(sqlite3
*db
){
3187 const char *zUri
= sqlite3_db_filename(db
, 0);
3188 return sqlite3_uri_boolean(zUri
, RBU_EXCLUSIVE_CHECKPOINT
, 0);
3191 #if defined(_WIN32_WCE)
3192 static LPWSTR
rbuWinUtf8ToUnicode(const char *zFilename
){
3194 LPWSTR zWideFilename
;
3196 nChar
= MultiByteToWideChar(CP_UTF8
, 0, zFilename
, -1, NULL
, 0);
3200 zWideFilename
= sqlite3_malloc64( nChar
*sizeof(zWideFilename
[0]) );
3201 if( zWideFilename
==0 ){
3204 memset(zWideFilename
, 0, nChar
*sizeof(zWideFilename
[0]));
3205 nChar
= MultiByteToWideChar(CP_UTF8
, 0, zFilename
, -1, zWideFilename
,
3208 sqlite3_free(zWideFilename
);
3211 return zWideFilename
;
3216 ** The RBU handle is currently in RBU_STAGE_OAL state, with a SHARED lock
3217 ** on the database file. This proc moves the *-oal file to the *-wal path,
3218 ** then reopens the database file (this time in vanilla, non-oal, WAL mode).
3219 ** If an error occurs, leave an error code and error message in the rbu
3222 static void rbuMoveOalFile(sqlite3rbu
*p
){
3223 const char *zBase
= sqlite3_db_filename(p
->dbMain
, "main");
3224 const char *zMove
= zBase
;
3228 if( rbuIsVacuum(p
) ){
3229 zMove
= sqlite3_db_filename(p
->dbRbu
, "main");
3231 zOal
= sqlite3_mprintf("%s-oal", zMove
);
3232 zWal
= sqlite3_mprintf("%s-wal", zMove
);
3234 assert( p
->eStage
==RBU_STAGE_MOVE
);
3235 assert( p
->rc
==SQLITE_OK
&& p
->zErrmsg
==0 );
3236 if( zWal
==0 || zOal
==0 ){
3237 p
->rc
= SQLITE_NOMEM
;
3239 /* Move the *-oal file to *-wal. At this point connection p->db is
3240 ** holding a SHARED lock on the target database file (because it is
3241 ** in WAL mode). So no other connection may be writing the db.
3243 ** In order to ensure that there are no database readers, an EXCLUSIVE
3244 ** lock is obtained here before the *-oal is moved to *-wal.
3246 sqlite3
*dbMain
= 0;
3247 rbuFileSuffix3(zBase
, zWal
);
3248 rbuFileSuffix3(zBase
, zOal
);
3250 /* Re-open the databases. */
3251 rbuObjIterFinalize(&p
->objiter
);
3252 sqlite3_close(p
->dbRbu
);
3253 sqlite3_close(p
->dbMain
);
3257 dbMain
= rbuOpenDbhandle(p
, p
->zTarget
, 1);
3259 assert( p
->rc
==SQLITE_OK
);
3260 p
->rc
= rbuLockDatabase(dbMain
);
3263 if( p
->rc
==SQLITE_OK
){
3264 p
->rc
= p
->xRename(p
->pRenameArg
, zOal
, zWal
);
3267 if( p
->rc
!=SQLITE_OK
3269 || rbuExclusiveCheckpoint(dbMain
)==0
3271 sqlite3_close(dbMain
);
3275 if( p
->rc
==SQLITE_OK
){
3276 rbuOpenDatabase(p
, dbMain
, 0);
3277 rbuSetupCheckpoint(p
, 0);
3286 ** The SELECT statement iterating through the keys for the current object
3287 ** (p->objiter.pSelect) currently points to a valid row. This function
3288 ** determines the type of operation requested by this row and returns
3289 ** one of the following values to indicate the result:
3296 ** If RBU_UPDATE is returned, then output variable *pzMask is set to
3297 ** point to the text value indicating the columns to update.
3299 ** If the rbu_control field contains an invalid value, an error code and
3300 ** message are left in the RBU handle and zero returned.
3302 static int rbuStepType(sqlite3rbu
*p
, const char **pzMask
){
3303 int iCol
= p
->objiter
.nCol
; /* Index of rbu_control column */
3304 int res
= 0; /* Return value */
3306 switch( sqlite3_column_type(p
->objiter
.pSelect
, iCol
) ){
3307 case SQLITE_INTEGER
: {
3308 int iVal
= sqlite3_column_int(p
->objiter
.pSelect
, iCol
);
3310 case 0: res
= RBU_INSERT
; break;
3311 case 1: res
= RBU_DELETE
; break;
3312 case 2: res
= RBU_REPLACE
; break;
3313 case 3: res
= RBU_IDX_DELETE
; break;
3314 case 4: res
= RBU_IDX_INSERT
; break;
3320 const unsigned char *z
= sqlite3_column_text(p
->objiter
.pSelect
, iCol
);
3322 p
->rc
= SQLITE_NOMEM
;
3324 *pzMask
= (const char*)z
;
3336 rbuBadControlError(p
);
3343 ** Assert that column iCol of statement pStmt is named zName.
3345 static void assertColumnName(sqlite3_stmt
*pStmt
, int iCol
, const char *zName
){
3346 const char *zCol
= sqlite3_column_name(pStmt
, iCol
);
3347 assert( 0==sqlite3_stricmp(zName
, zCol
) );
3350 # define assertColumnName(x,y,z)
3354 ** Argument eType must be one of RBU_INSERT, RBU_DELETE, RBU_IDX_INSERT or
3355 ** RBU_IDX_DELETE. This function performs the work of a single
3356 ** sqlite3rbu_step() call for the type of operation specified by eType.
3358 static void rbuStepOneOp(sqlite3rbu
*p
, int eType
){
3359 RbuObjIter
*pIter
= &p
->objiter
;
3360 sqlite3_value
*pVal
;
3361 sqlite3_stmt
*pWriter
;
3364 assert( p
->rc
==SQLITE_OK
);
3365 assert( eType
!=RBU_DELETE
|| pIter
->zIdx
==0 );
3366 assert( eType
==RBU_DELETE
|| eType
==RBU_IDX_DELETE
3367 || eType
==RBU_INSERT
|| eType
==RBU_IDX_INSERT
3370 /* If this is a delete, decrement nPhaseOneStep by nIndex. If the DELETE
3371 ** statement below does actually delete a row, nPhaseOneStep will be
3372 ** incremented by the same amount when SQL function rbu_tmp_insert()
3373 ** is invoked by the trigger. */
3374 if( eType
==RBU_DELETE
){
3375 p
->nPhaseOneStep
-= p
->objiter
.nIndex
;
3378 if( eType
==RBU_IDX_DELETE
|| eType
==RBU_DELETE
){
3379 pWriter
= pIter
->pDelete
;
3381 pWriter
= pIter
->pInsert
;
3384 for(i
=0; i
<pIter
->nCol
; i
++){
3385 /* If this is an INSERT into a table b-tree and the table has an
3386 ** explicit INTEGER PRIMARY KEY, check that this is not an attempt
3387 ** to write a NULL into the IPK column. That is not permitted. */
3388 if( eType
==RBU_INSERT
3389 && pIter
->zIdx
==0 && pIter
->eType
==RBU_PK_IPK
&& pIter
->abTblPk
[i
]
3390 && sqlite3_column_type(pIter
->pSelect
, i
)==SQLITE_NULL
3392 p
->rc
= SQLITE_MISMATCH
;
3393 p
->zErrmsg
= sqlite3_mprintf("datatype mismatch");
3397 if( eType
==RBU_DELETE
&& pIter
->abTblPk
[i
]==0 ){
3401 pVal
= sqlite3_column_value(pIter
->pSelect
, i
);
3402 p
->rc
= sqlite3_bind_value(pWriter
, i
+1, pVal
);
3405 if( pIter
->zIdx
==0 ){
3406 if( pIter
->eType
==RBU_PK_VTAB
3407 || pIter
->eType
==RBU_PK_NONE
3408 || (pIter
->eType
==RBU_PK_EXTERNAL
&& rbuIsVacuum(p
))
3410 /* For a virtual table, or a table with no primary key, the
3411 ** SELECT statement is:
3413 ** SELECT <cols>, rbu_control, rbu_rowid FROM ....
3415 ** Hence column_value(pIter->nCol+1).
3417 assertColumnName(pIter
->pSelect
, pIter
->nCol
+1,
3418 rbuIsVacuum(p
) ? "rowid" : "rbu_rowid"
3420 pVal
= sqlite3_column_value(pIter
->pSelect
, pIter
->nCol
+1);
3421 p
->rc
= sqlite3_bind_value(pWriter
, pIter
->nCol
+1, pVal
);
3424 if( p
->rc
==SQLITE_OK
){
3425 sqlite3_step(pWriter
);
3426 p
->rc
= resetAndCollectError(pWriter
, &p
->zErrmsg
);
3431 ** This function does the work for an sqlite3rbu_step() call.
3433 ** The object-iterator (p->objiter) currently points to a valid object,
3434 ** and the input cursor (p->objiter.pSelect) currently points to a valid
3435 ** input row. Perform whatever processing is required and return.
3437 ** If no error occurs, SQLITE_OK is returned. Otherwise, an error code
3438 ** and message is left in the RBU handle and a copy of the error code
3441 static int rbuStep(sqlite3rbu
*p
){
3442 RbuObjIter
*pIter
= &p
->objiter
;
3443 const char *zMask
= 0;
3444 int eType
= rbuStepType(p
, &zMask
);
3447 assert( eType
==RBU_INSERT
|| eType
==RBU_DELETE
3448 || eType
==RBU_REPLACE
|| eType
==RBU_IDX_DELETE
3449 || eType
==RBU_IDX_INSERT
|| eType
==RBU_UPDATE
3451 assert( eType
!=RBU_UPDATE
|| pIter
->zIdx
==0 );
3453 if( pIter
->zIdx
==0 && (eType
==RBU_IDX_DELETE
|| eType
==RBU_IDX_INSERT
) ){
3454 rbuBadControlError(p
);
3456 else if( eType
==RBU_REPLACE
){
3457 if( pIter
->zIdx
==0 ){
3458 p
->nPhaseOneStep
+= p
->objiter
.nIndex
;
3459 rbuStepOneOp(p
, RBU_DELETE
);
3461 if( p
->rc
==SQLITE_OK
) rbuStepOneOp(p
, RBU_INSERT
);
3463 else if( eType
!=RBU_UPDATE
){
3464 rbuStepOneOp(p
, eType
);
3467 sqlite3_value
*pVal
;
3468 sqlite3_stmt
*pUpdate
= 0;
3469 assert( eType
==RBU_UPDATE
);
3470 p
->nPhaseOneStep
-= p
->objiter
.nIndex
;
3471 rbuGetUpdateStmt(p
, pIter
, zMask
, &pUpdate
);
3474 for(i
=0; p
->rc
==SQLITE_OK
&& i
<pIter
->nCol
; i
++){
3475 char c
= zMask
[pIter
->aiSrcOrder
[i
]];
3476 pVal
= sqlite3_column_value(pIter
->pSelect
, i
);
3477 if( pIter
->abTblPk
[i
] || c
!='.' ){
3478 p
->rc
= sqlite3_bind_value(pUpdate
, i
+1, pVal
);
3481 if( p
->rc
==SQLITE_OK
3482 && (pIter
->eType
==RBU_PK_VTAB
|| pIter
->eType
==RBU_PK_NONE
)
3484 /* Bind the rbu_rowid value to column _rowid_ */
3485 assertColumnName(pIter
->pSelect
, pIter
->nCol
+1, "rbu_rowid");
3486 pVal
= sqlite3_column_value(pIter
->pSelect
, pIter
->nCol
+1);
3487 p
->rc
= sqlite3_bind_value(pUpdate
, pIter
->nCol
+1, pVal
);
3489 if( p
->rc
==SQLITE_OK
){
3490 sqlite3_step(pUpdate
);
3491 p
->rc
= resetAndCollectError(pUpdate
, &p
->zErrmsg
);
3500 ** Increment the schema cookie of the main database opened by p->dbMain.
3502 ** Or, if this is an RBU vacuum, set the schema cookie of the main db
3503 ** opened by p->dbMain to one more than the schema cookie of the main
3504 ** db opened by p->dbRbu.
3506 static void rbuIncrSchemaCookie(sqlite3rbu
*p
){
3507 if( p
->rc
==SQLITE_OK
){
3508 sqlite3
*dbread
= (rbuIsVacuum(p
) ? p
->dbRbu
: p
->dbMain
);
3509 int iCookie
= 1000000;
3510 sqlite3_stmt
*pStmt
;
3512 p
->rc
= prepareAndCollectError(dbread
, &pStmt
, &p
->zErrmsg
,
3513 "PRAGMA schema_version"
3515 if( p
->rc
==SQLITE_OK
){
3516 /* Coverage: it may be that this sqlite3_step() cannot fail. There
3517 ** is already a transaction open, so the prepared statement cannot
3518 ** throw an SQLITE_SCHEMA exception. The only database page the
3519 ** statement reads is page 1, which is guaranteed to be in the cache.
3520 ** And no memory allocations are required. */
3521 if( SQLITE_ROW
==sqlite3_step(pStmt
) ){
3522 iCookie
= sqlite3_column_int(pStmt
, 0);
3524 rbuFinalize(p
, pStmt
);
3526 if( p
->rc
==SQLITE_OK
){
3527 rbuMPrintfExec(p
, p
->dbMain
, "PRAGMA schema_version = %d", iCookie
+1);
3533 ** Update the contents of the rbu_state table within the rbu database. The
3534 ** value stored in the RBU_STATE_STAGE column is eStage. All other values
3535 ** are determined by inspecting the rbu handle passed as the first argument.
3537 static void rbuSaveState(sqlite3rbu
*p
, int eStage
){
3538 if( p
->rc
==SQLITE_OK
|| p
->rc
==SQLITE_DONE
){
3539 sqlite3_stmt
*pInsert
= 0;
3540 rbu_file
*pFd
= (rbuIsVacuum(p
) ? p
->pRbuFd
: p
->pTargetFd
);
3543 assert( p
->zErrmsg
==0 );
3544 rc
= prepareFreeAndCollectError(p
->dbRbu
, &pInsert
, &p
->zErrmsg
,
3546 "INSERT OR REPLACE INTO %s.rbu_state(k, v) VALUES "
3558 RBU_STATE_STAGE
, eStage
,
3559 RBU_STATE_TBL
, p
->objiter
.zTbl
,
3560 RBU_STATE_IDX
, p
->objiter
.zIdx
,
3561 RBU_STATE_ROW
, p
->nStep
,
3562 RBU_STATE_PROGRESS
, p
->nProgress
,
3563 RBU_STATE_CKPT
, p
->iWalCksum
,
3564 RBU_STATE_COOKIE
, (i64
)pFd
->iCookie
,
3565 RBU_STATE_OALSZ
, p
->iOalSz
,
3566 RBU_STATE_PHASEONESTEP
, p
->nPhaseOneStep
,
3567 RBU_STATE_DATATBL
, p
->objiter
.zDataTbl
3570 assert( pInsert
==0 || rc
==SQLITE_OK
);
3572 if( rc
==SQLITE_OK
){
3573 sqlite3_step(pInsert
);
3574 rc
= sqlite3_finalize(pInsert
);
3576 if( rc
!=SQLITE_OK
) p
->rc
= rc
;
3582 ** The second argument passed to this function is the name of a PRAGMA
3583 ** setting - "page_size", "auto_vacuum", "user_version" or "application_id".
3584 ** This function executes the following on sqlite3rbu.dbRbu:
3586 ** "PRAGMA main.$zPragma"
3588 ** where $zPragma is the string passed as the second argument, then
3589 ** on sqlite3rbu.dbMain:
3591 ** "PRAGMA main.$zPragma = $val"
3593 ** where $val is the value returned by the first PRAGMA invocation.
3595 ** In short, it copies the value of the specified PRAGMA setting from
3598 static void rbuCopyPragma(sqlite3rbu
*p
, const char *zPragma
){
3599 if( p
->rc
==SQLITE_OK
){
3600 sqlite3_stmt
*pPragma
= 0;
3601 p
->rc
= prepareFreeAndCollectError(p
->dbRbu
, &pPragma
, &p
->zErrmsg
,
3602 sqlite3_mprintf("PRAGMA main.%s", zPragma
)
3604 if( p
->rc
==SQLITE_OK
&& SQLITE_ROW
==sqlite3_step(pPragma
) ){
3605 p
->rc
= rbuMPrintfExec(p
, p
->dbMain
, "PRAGMA main.%s = %d",
3606 zPragma
, sqlite3_column_int(pPragma
, 0)
3609 rbuFinalize(p
, pPragma
);
3614 ** The RBU handle passed as the only argument has just been opened and
3615 ** the state database is empty. If this RBU handle was opened for an
3616 ** RBU vacuum operation, create the schema in the target db.
3618 static void rbuCreateTargetSchema(sqlite3rbu
*p
){
3619 sqlite3_stmt
*pSql
= 0;
3620 sqlite3_stmt
*pInsert
= 0;
3622 assert( rbuIsVacuum(p
) );
3623 p
->rc
= sqlite3_exec(p
->dbMain
, "PRAGMA writable_schema=1", 0,0, &p
->zErrmsg
);
3624 if( p
->rc
==SQLITE_OK
){
3625 p
->rc
= prepareAndCollectError(p
->dbRbu
, &pSql
, &p
->zErrmsg
,
3626 "SELECT sql FROM sqlite_schema WHERE sql!='' AND rootpage!=0"
3627 " AND name!='sqlite_sequence' "
3628 " ORDER BY type DESC"
3632 while( p
->rc
==SQLITE_OK
&& sqlite3_step(pSql
)==SQLITE_ROW
){
3633 const char *zSql
= (const char*)sqlite3_column_text(pSql
, 0);
3634 p
->rc
= sqlite3_exec(p
->dbMain
, zSql
, 0, 0, &p
->zErrmsg
);
3636 rbuFinalize(p
, pSql
);
3637 if( p
->rc
!=SQLITE_OK
) return;
3639 if( p
->rc
==SQLITE_OK
){
3640 p
->rc
= prepareAndCollectError(p
->dbRbu
, &pSql
, &p
->zErrmsg
,
3641 "SELECT * FROM sqlite_schema WHERE rootpage=0 OR rootpage IS NULL"
3645 if( p
->rc
==SQLITE_OK
){
3646 p
->rc
= prepareAndCollectError(p
->dbMain
, &pInsert
, &p
->zErrmsg
,
3647 "INSERT INTO sqlite_schema VALUES(?,?,?,?,?)"
3651 while( p
->rc
==SQLITE_OK
&& sqlite3_step(pSql
)==SQLITE_ROW
){
3654 sqlite3_bind_value(pInsert
, i
+1, sqlite3_column_value(pSql
, i
));
3656 sqlite3_step(pInsert
);
3657 p
->rc
= sqlite3_reset(pInsert
);
3659 if( p
->rc
==SQLITE_OK
){
3660 p
->rc
= sqlite3_exec(p
->dbMain
, "PRAGMA writable_schema=0",0,0,&p
->zErrmsg
);
3663 rbuFinalize(p
, pSql
);
3664 rbuFinalize(p
, pInsert
);
3668 ** Step the RBU object.
3670 int sqlite3rbu_step(sqlite3rbu
*p
){
3672 switch( p
->eStage
){
3673 case RBU_STAGE_OAL
: {
3674 RbuObjIter
*pIter
= &p
->objiter
;
3676 /* If this is an RBU vacuum operation and the state table was empty
3677 ** when this handle was opened, create the target database schema. */
3678 if( rbuIsVacuum(p
) && p
->nProgress
==0 && p
->rc
==SQLITE_OK
){
3679 rbuCreateTargetSchema(p
);
3680 rbuCopyPragma(p
, "user_version");
3681 rbuCopyPragma(p
, "application_id");
3684 while( p
->rc
==SQLITE_OK
&& pIter
->zTbl
){
3686 if( pIter
->bCleanup
){
3687 /* Clean up the rbu_tmp_xxx table for the previous table. It
3688 ** cannot be dropped as there are currently active SQL statements.
3689 ** But the contents can be deleted. */
3690 if( rbuIsVacuum(p
)==0 && pIter
->abIndexed
){
3691 rbuMPrintfExec(p
, p
->dbRbu
,
3692 "DELETE FROM %s.'rbu_tmp_%q'", p
->zStateDb
, pIter
->zDataTbl
3696 rbuObjIterPrepareAll(p
, pIter
, 0);
3698 /* Advance to the next row to process. */
3699 if( p
->rc
==SQLITE_OK
){
3700 int rc
= sqlite3_step(pIter
->pSelect
);
3701 if( rc
==SQLITE_ROW
){
3706 p
->rc
= sqlite3_reset(pIter
->pSelect
);
3711 rbuObjIterNext(p
, pIter
);
3714 if( p
->rc
==SQLITE_OK
){
3715 assert( pIter
->zTbl
==0 );
3716 rbuSaveState(p
, RBU_STAGE_MOVE
);
3717 rbuIncrSchemaCookie(p
);
3718 if( p
->rc
==SQLITE_OK
){
3719 p
->rc
= sqlite3_exec(p
->dbMain
, "COMMIT", 0, 0, &p
->zErrmsg
);
3721 if( p
->rc
==SQLITE_OK
){
3722 p
->rc
= sqlite3_exec(p
->dbRbu
, "COMMIT", 0, 0, &p
->zErrmsg
);
3724 p
->eStage
= RBU_STAGE_MOVE
;
3729 case RBU_STAGE_MOVE
: {
3730 if( p
->rc
==SQLITE_OK
){
3737 case RBU_STAGE_CKPT
: {
3738 if( p
->rc
==SQLITE_OK
){
3739 if( p
->nStep
>=p
->nFrame
){
3740 sqlite3_file
*pDb
= p
->pTargetFd
->pReal
;
3742 /* Sync the db file */
3743 p
->rc
= pDb
->pMethods
->xSync(pDb
, SQLITE_SYNC_NORMAL
);
3745 /* Update nBackfill */
3746 if( p
->rc
==SQLITE_OK
){
3748 p
->rc
= pDb
->pMethods
->xShmMap(pDb
, 0, 32*1024, 0, &ptr
);
3749 if( p
->rc
==SQLITE_OK
){
3750 ((u32
volatile*)ptr
)[24] = p
->iMaxFrame
;
3754 if( p
->rc
==SQLITE_OK
){
3755 p
->eStage
= RBU_STAGE_DONE
;
3756 p
->rc
= SQLITE_DONE
;
3759 /* At one point the following block copied a single frame from the
3760 ** wal file to the database file. So that one call to sqlite3rbu_step()
3761 ** checkpointed a single frame.
3763 ** However, if the sector-size is larger than the page-size, and the
3764 ** application calls sqlite3rbu_savestate() or close() immediately
3765 ** after this step, then rbu_step() again, then a power failure occurs,
3766 ** then the database page written here may be damaged. Work around
3767 ** this by checkpointing frames until the next page in the aFrame[]
3768 ** lies on a different disk sector to the current one. */
3771 RbuFrame
*pFrame
= &p
->aFrame
[p
->nStep
];
3772 iSector
= (pFrame
->iDbPage
-1) / p
->nPagePerSector
;
3773 rbuCheckpointFrame(p
, pFrame
);
3775 }while( p
->nStep
<p
->nFrame
3776 && iSector
==((p
->aFrame
[p
->nStep
].iDbPage
-1) / p
->nPagePerSector
)
3790 return SQLITE_NOMEM
;
3795 ** Compare strings z1 and z2, returning 0 if they are identical, or non-zero
3796 ** otherwise. Either or both argument may be NULL. Two NULL values are
3797 ** considered equal, and NULL is considered distinct from all other values.
3799 static int rbuStrCompare(const char *z1
, const char *z2
){
3800 if( z1
==0 && z2
==0 ) return 0;
3801 if( z1
==0 || z2
==0 ) return 1;
3802 return (sqlite3_stricmp(z1
, z2
)!=0);
3806 ** This function is called as part of sqlite3rbu_open() when initializing
3807 ** an rbu handle in OAL stage. If the rbu update has not started (i.e.
3808 ** the rbu_state table was empty) it is a no-op. Otherwise, it arranges
3809 ** things so that the next call to sqlite3rbu_step() continues on from
3810 ** where the previous rbu handle left off.
3812 ** If an error occurs, an error code and error message are left in the
3813 ** rbu handle passed as the first argument.
3815 static void rbuSetupOal(sqlite3rbu
*p
, RbuState
*pState
){
3816 assert( p
->rc
==SQLITE_OK
);
3818 RbuObjIter
*pIter
= &p
->objiter
;
3821 while( rc
==SQLITE_OK
&& pIter
->zTbl
&& (pIter
->bCleanup
3822 || rbuStrCompare(pIter
->zIdx
, pState
->zIdx
)
3823 || (pState
->zDataTbl
==0 && rbuStrCompare(pIter
->zTbl
, pState
->zTbl
))
3824 || (pState
->zDataTbl
&& rbuStrCompare(pIter
->zDataTbl
, pState
->zDataTbl
))
3826 rc
= rbuObjIterNext(p
, pIter
);
3829 if( rc
==SQLITE_OK
&& !pIter
->zTbl
){
3831 p
->zErrmsg
= sqlite3_mprintf("rbu_state mismatch error");
3834 if( rc
==SQLITE_OK
){
3835 p
->nStep
= pState
->nRow
;
3836 rc
= rbuObjIterPrepareAll(p
, &p
->objiter
, p
->nStep
);
3844 ** If there is a "*-oal" file in the file-system corresponding to the
3845 ** target database in the file-system, delete it. If an error occurs,
3846 ** leave an error code and error message in the rbu handle.
3848 static void rbuDeleteOalFile(sqlite3rbu
*p
){
3849 char *zOal
= rbuMPrintf(p
, "%s-oal", p
->zTarget
);
3851 sqlite3_vfs
*pVfs
= 0;
3852 sqlite3_file_control(p
->dbMain
, "main", SQLITE_FCNTL_VFS_POINTER
, &pVfs
);
3853 assert( pVfs
&& p
->rc
==SQLITE_OK
&& p
->zErrmsg
==0 );
3854 pVfs
->xDelete(pVfs
, zOal
, 0);
3860 ** Allocate a private rbu VFS for the rbu handle passed as the only
3861 ** argument. This VFS will be used unless the call to sqlite3rbu_open()
3862 ** specified a URI with a vfs=? option in place of a target database
3865 static void rbuCreateVfs(sqlite3rbu
*p
){
3869 assert( p
->rc
==SQLITE_OK
);
3870 sqlite3_randomness(sizeof(int), (void*)&rnd
);
3871 sqlite3_snprintf(sizeof(zRnd
), zRnd
, "rbu_vfs_%d", rnd
);
3872 p
->rc
= sqlite3rbu_create_vfs(zRnd
, 0);
3873 if( p
->rc
==SQLITE_OK
){
3874 sqlite3_vfs
*pVfs
= sqlite3_vfs_find(zRnd
);
3876 p
->zVfsName
= pVfs
->zName
;
3877 ((rbu_vfs
*)pVfs
)->pRbu
= p
;
3882 ** Destroy the private VFS created for the rbu handle passed as the only
3883 ** argument by an earlier call to rbuCreateVfs().
3885 static void rbuDeleteVfs(sqlite3rbu
*p
){
3887 sqlite3rbu_destroy_vfs(p
->zVfsName
);
3893 ** This user-defined SQL function is invoked with a single argument - the
3894 ** name of a table expected to appear in the target database. It returns
3895 ** the number of auxilliary indexes on the table.
3897 static void rbuIndexCntFunc(
3898 sqlite3_context
*pCtx
,
3900 sqlite3_value
**apVal
3902 sqlite3rbu
*p
= (sqlite3rbu
*)sqlite3_user_data(pCtx
);
3903 sqlite3_stmt
*pStmt
= 0;
3906 sqlite3
*db
= (rbuIsVacuum(p
) ? p
->dbRbu
: p
->dbMain
);
3910 rc
= prepareFreeAndCollectError(db
, &pStmt
, &zErrmsg
,
3911 sqlite3_mprintf("SELECT count(*) FROM sqlite_schema "
3912 "WHERE type='index' AND tbl_name = %Q", sqlite3_value_text(apVal
[0]))
3914 if( rc
!=SQLITE_OK
){
3915 sqlite3_result_error(pCtx
, zErrmsg
, -1);
3918 if( SQLITE_ROW
==sqlite3_step(pStmt
) ){
3919 nIndex
= sqlite3_column_int(pStmt
, 0);
3921 rc
= sqlite3_finalize(pStmt
);
3922 if( rc
==SQLITE_OK
){
3923 sqlite3_result_int(pCtx
, nIndex
);
3925 sqlite3_result_error(pCtx
, sqlite3_errmsg(db
), -1);
3929 sqlite3_free(zErrmsg
);
3933 ** If the RBU database contains the rbu_count table, use it to initialize
3934 ** the sqlite3rbu.nPhaseOneStep variable. The schema of the rbu_count table
3935 ** is assumed to contain the same columns as:
3937 ** CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
3939 ** There should be one row in the table for each data_xxx table in the
3940 ** database. The 'tbl' column should contain the name of a data_xxx table,
3941 ** and the cnt column the number of rows it contains.
3943 ** sqlite3rbu.nPhaseOneStep is initialized to the sum of (1 + nIndex) * cnt
3944 ** for all rows in the rbu_count table, where nIndex is the number of
3945 ** indexes on the corresponding target database table.
3947 static void rbuInitPhaseOneSteps(sqlite3rbu
*p
){
3948 if( p
->rc
==SQLITE_OK
){
3949 sqlite3_stmt
*pStmt
= 0;
3950 int bExists
= 0; /* True if rbu_count exists */
3952 p
->nPhaseOneStep
= -1;
3954 p
->rc
= sqlite3_create_function(p
->dbRbu
,
3955 "rbu_index_cnt", 1, SQLITE_UTF8
, (void*)p
, rbuIndexCntFunc
, 0, 0
3958 /* Check for the rbu_count table. If it does not exist, or if an error
3959 ** occurs, nPhaseOneStep will be left set to -1. */
3960 if( p
->rc
==SQLITE_OK
){
3961 p
->rc
= prepareAndCollectError(p
->dbRbu
, &pStmt
, &p
->zErrmsg
,
3962 "SELECT 1 FROM sqlite_schema WHERE tbl_name = 'rbu_count'"
3965 if( p
->rc
==SQLITE_OK
){
3966 if( SQLITE_ROW
==sqlite3_step(pStmt
) ){
3969 p
->rc
= sqlite3_finalize(pStmt
);
3972 if( p
->rc
==SQLITE_OK
&& bExists
){
3973 p
->rc
= prepareAndCollectError(p
->dbRbu
, &pStmt
, &p
->zErrmsg
,
3974 "SELECT sum(cnt * (1 + rbu_index_cnt(rbu_target_name(tbl))))"
3977 if( p
->rc
==SQLITE_OK
){
3978 if( SQLITE_ROW
==sqlite3_step(pStmt
) ){
3979 p
->nPhaseOneStep
= sqlite3_column_int64(pStmt
, 0);
3981 p
->rc
= sqlite3_finalize(pStmt
);
3988 static sqlite3rbu
*openRbuHandle(
3989 const char *zTarget
,
3994 size_t nTarget
= zTarget
? strlen(zTarget
) : 0;
3995 size_t nRbu
= strlen(zRbu
);
3996 size_t nByte
= sizeof(sqlite3rbu
) + nTarget
+1 + nRbu
+1;
3998 p
= (sqlite3rbu
*)sqlite3_malloc64(nByte
);
4000 RbuState
*pState
= 0;
4002 /* Create the custom VFS. */
4003 memset(p
, 0, sizeof(sqlite3rbu
));
4004 sqlite3rbu_rename_handler(p
, 0, 0);
4007 /* Open the target, RBU and state databases */
4008 if( p
->rc
==SQLITE_OK
){
4009 char *pCsr
= (char*)&p
[1];
4013 memcpy(p
->zTarget
, zTarget
, nTarget
+1);
4017 memcpy(p
->zRbu
, zRbu
, nRbu
+1);
4020 p
->zState
= rbuMPrintf(p
, "%s", zState
);
4023 /* If the first attempt to open the database file fails and the bRetry
4024 ** flag it set, this means that the db was not opened because it seemed
4025 ** to be a wal-mode db. But, this may have happened due to an earlier
4026 ** RBU vacuum operation leaving an old wal file in the directory.
4027 ** If this is the case, it will have been checkpointed and deleted
4028 ** when the handle was closed and a second attempt to open the
4029 ** database may succeed. */
4030 rbuOpenDatabase(p
, 0, &bRetry
);
4032 rbuOpenDatabase(p
, 0, 0);
4036 if( p
->rc
==SQLITE_OK
){
4037 pState
= rbuLoadState(p
);
4038 assert( pState
|| p
->rc
!=SQLITE_OK
);
4039 if( p
->rc
==SQLITE_OK
){
4041 if( pState
->eStage
==0 ){
4042 rbuDeleteOalFile(p
);
4043 rbuInitPhaseOneSteps(p
);
4044 p
->eStage
= RBU_STAGE_OAL
;
4046 p
->eStage
= pState
->eStage
;
4047 p
->nPhaseOneStep
= pState
->nPhaseOneStep
;
4049 p
->nProgress
= pState
->nProgress
;
4050 p
->iOalSz
= pState
->iOalSz
;
4053 assert( p
->rc
!=SQLITE_OK
|| p
->eStage
!=0 );
4055 if( p
->rc
==SQLITE_OK
&& p
->pTargetFd
->pWalFd
){
4056 if( p
->eStage
==RBU_STAGE_OAL
){
4057 p
->rc
= SQLITE_ERROR
;
4058 p
->zErrmsg
= sqlite3_mprintf("cannot update wal mode database");
4059 }else if( p
->eStage
==RBU_STAGE_MOVE
){
4060 p
->eStage
= RBU_STAGE_CKPT
;
4065 if( p
->rc
==SQLITE_OK
4066 && (p
->eStage
==RBU_STAGE_OAL
|| p
->eStage
==RBU_STAGE_MOVE
)
4067 && pState
->eStage
!=0
4069 rbu_file
*pFd
= (rbuIsVacuum(p
) ? p
->pRbuFd
: p
->pTargetFd
);
4070 if( pFd
->iCookie
!=pState
->iCookie
){
4071 /* At this point (pTargetFd->iCookie) contains the value of the
4072 ** change-counter cookie (the thing that gets incremented when a
4073 ** transaction is committed in rollback mode) currently stored on
4074 ** page 1 of the database file. */
4075 p
->rc
= SQLITE_BUSY
;
4076 p
->zErrmsg
= sqlite3_mprintf("database modified during rbu %s",
4077 (rbuIsVacuum(p
) ? "vacuum" : "update")
4082 if( p
->rc
==SQLITE_OK
){
4083 if( p
->eStage
==RBU_STAGE_OAL
){
4084 sqlite3
*db
= p
->dbMain
;
4085 p
->rc
= sqlite3_exec(p
->dbRbu
, "BEGIN", 0, 0, &p
->zErrmsg
);
4087 /* Point the object iterator at the first object */
4088 if( p
->rc
==SQLITE_OK
){
4089 p
->rc
= rbuObjIterFirst(p
, &p
->objiter
);
4092 /* If the RBU database contains no data_xxx tables, declare the RBU
4093 ** update finished. */
4094 if( p
->rc
==SQLITE_OK
&& p
->objiter
.zTbl
==0 ){
4095 p
->rc
= SQLITE_DONE
;
4096 p
->eStage
= RBU_STAGE_DONE
;
4098 if( p
->rc
==SQLITE_OK
&& pState
->eStage
==0 && rbuIsVacuum(p
) ){
4099 rbuCopyPragma(p
, "page_size");
4100 rbuCopyPragma(p
, "auto_vacuum");
4103 /* Open transactions both databases. The *-oal file is opened or
4104 ** created at this point. */
4105 if( p
->rc
==SQLITE_OK
){
4106 p
->rc
= sqlite3_exec(db
, "BEGIN IMMEDIATE", 0, 0, &p
->zErrmsg
);
4109 /* Check if the main database is a zipvfs db. If it is, set the upper
4110 ** level pager to use "journal_mode=off". This prevents it from
4111 ** generating a large journal using a temp file. */
4112 if( p
->rc
==SQLITE_OK
){
4113 int frc
= sqlite3_file_control(db
, "main", SQLITE_FCNTL_ZIPVFS
, 0);
4114 if( frc
==SQLITE_OK
){
4115 p
->rc
= sqlite3_exec(
4116 db
, "PRAGMA journal_mode=off",0,0,&p
->zErrmsg
);
4120 if( p
->rc
==SQLITE_OK
){
4121 rbuSetupOal(p
, pState
);
4124 }else if( p
->eStage
==RBU_STAGE_MOVE
){
4126 }else if( p
->eStage
==RBU_STAGE_CKPT
){
4127 if( !rbuIsVacuum(p
) && rbuExclusiveCheckpoint(p
->dbMain
) ){
4128 /* If the rbu_exclusive_checkpoint=1 URI parameter was specified
4129 ** and an incremental checkpoint is being resumed, attempt an
4130 ** exclusive lock on the db file. If this fails, so be it. */
4131 p
->eStage
= RBU_STAGE_DONE
;
4132 rbuLockDatabase(p
->dbMain
);
4133 p
->eStage
= RBU_STAGE_CKPT
;
4135 rbuSetupCheckpoint(p
, pState
);
4136 }else if( p
->eStage
==RBU_STAGE_DONE
){
4137 p
->rc
= SQLITE_DONE
;
4139 p
->rc
= SQLITE_CORRUPT
;
4143 rbuFreeState(pState
);
4150 ** Allocate and return an RBU handle with all fields zeroed except for the
4151 ** error code, which is set to SQLITE_MISUSE.
4153 static sqlite3rbu
*rbuMisuseError(void){
4155 pRet
= sqlite3_malloc64(sizeof(sqlite3rbu
));
4157 memset(pRet
, 0, sizeof(sqlite3rbu
));
4158 pRet
->rc
= SQLITE_MISUSE
;
4164 ** Open and return a new RBU handle.
4166 sqlite3rbu
*sqlite3rbu_open(
4167 const char *zTarget
,
4171 if( zTarget
==0 || zRbu
==0 ){ return rbuMisuseError(); }
4172 return openRbuHandle(zTarget
, zRbu
, zState
);
4176 ** Open a handle to begin or resume an RBU VACUUM operation.
4178 sqlite3rbu
*sqlite3rbu_vacuum(
4179 const char *zTarget
,
4182 if( zTarget
==0 ){ return rbuMisuseError(); }
4184 int n
= strlen(zState
);
4185 if( n
>=7 && 0==memcmp("-vactmp", &zState
[n
-7], 7) ){
4186 return rbuMisuseError();
4189 /* TODO: Check that both arguments are non-NULL */
4190 return openRbuHandle(0, zTarget
, zState
);
4194 ** Return the database handle used by pRbu.
4196 sqlite3
*sqlite3rbu_db(sqlite3rbu
*pRbu
, int bRbu
){
4199 db
= (bRbu
? pRbu
->dbRbu
: pRbu
->dbMain
);
4206 ** If the error code currently stored in the RBU handle is SQLITE_CONSTRAINT,
4207 ** then edit any error message string so as to remove all occurrences of
4208 ** the pattern "rbu_imp_[0-9]*".
4210 static void rbuEditErrmsg(sqlite3rbu
*p
){
4211 if( p
->rc
==SQLITE_CONSTRAINT
&& p
->zErrmsg
){
4213 size_t nErrmsg
= strlen(p
->zErrmsg
);
4214 for(i
=0; i
<(nErrmsg
-8); i
++){
4215 if( memcmp(&p
->zErrmsg
[i
], "rbu_imp_", 8)==0 ){
4217 while( p
->zErrmsg
[i
+nDel
]>='0' && p
->zErrmsg
[i
+nDel
]<='9' ) nDel
++;
4218 memmove(&p
->zErrmsg
[i
], &p
->zErrmsg
[i
+nDel
], nErrmsg
+ 1 - i
- nDel
);
4226 ** Close the RBU handle.
4228 int sqlite3rbu_close(sqlite3rbu
*p
, char **pzErrmsg
){
4232 /* Commit the transaction to the *-oal file. */
4233 if( p
->rc
==SQLITE_OK
&& p
->eStage
==RBU_STAGE_OAL
){
4234 p
->rc
= sqlite3_exec(p
->dbMain
, "COMMIT", 0, 0, &p
->zErrmsg
);
4237 /* Sync the db file if currently doing an incremental checkpoint */
4238 if( p
->rc
==SQLITE_OK
&& p
->eStage
==RBU_STAGE_CKPT
){
4239 sqlite3_file
*pDb
= p
->pTargetFd
->pReal
;
4240 p
->rc
= pDb
->pMethods
->xSync(pDb
, SQLITE_SYNC_NORMAL
);
4243 rbuSaveState(p
, p
->eStage
);
4245 if( p
->rc
==SQLITE_OK
&& p
->eStage
==RBU_STAGE_OAL
){
4246 p
->rc
= sqlite3_exec(p
->dbRbu
, "COMMIT", 0, 0, &p
->zErrmsg
);
4249 /* Close any open statement handles. */
4250 rbuObjIterFinalize(&p
->objiter
);
4252 /* If this is an RBU vacuum handle and the vacuum has either finished
4253 ** successfully or encountered an error, delete the contents of the
4254 ** state table. This causes the next call to sqlite3rbu_vacuum()
4255 ** specifying the current target and state databases to start a new
4256 ** vacuum from scratch. */
4257 if( rbuIsVacuum(p
) && p
->rc
!=SQLITE_OK
&& p
->dbRbu
){
4258 int rc2
= sqlite3_exec(p
->dbRbu
, "DELETE FROM stat.rbu_state", 0, 0, 0);
4259 if( p
->rc
==SQLITE_DONE
&& rc2
!=SQLITE_OK
) p
->rc
= rc2
;
4262 /* Close the open database handle and VFS object. */
4263 sqlite3_close(p
->dbRbu
);
4264 sqlite3_close(p
->dbMain
);
4265 assert( p
->szTemp
==0 );
4267 sqlite3_free(p
->aBuf
);
4268 sqlite3_free(p
->aFrame
);
4273 *pzErrmsg
= p
->zErrmsg
;
4275 sqlite3_free(p
->zErrmsg
);
4277 sqlite3_free(p
->zState
);
4287 ** Return the total number of key-value operations (inserts, deletes or
4288 ** updates) that have been performed on the target database since the
4289 ** current RBU update was started.
4291 sqlite3_int64
sqlite3rbu_progress(sqlite3rbu
*pRbu
){
4292 return pRbu
->nProgress
;
4296 ** Return permyriadage progress indications for the two main stages of
4299 void sqlite3rbu_bp_progress(sqlite3rbu
*p
, int *pnOne
, int *pnTwo
){
4300 const int MAX_PROGRESS
= 10000;
4301 switch( p
->eStage
){
4303 if( p
->nPhaseOneStep
>0 ){
4304 *pnOne
= (int)(MAX_PROGRESS
* (i64
)p
->nProgress
/(i64
)p
->nPhaseOneStep
);
4311 case RBU_STAGE_MOVE
:
4312 *pnOne
= MAX_PROGRESS
;
4316 case RBU_STAGE_CKPT
:
4317 *pnOne
= MAX_PROGRESS
;
4318 *pnTwo
= (int)(MAX_PROGRESS
* (i64
)p
->nStep
/ (i64
)p
->nFrame
);
4321 case RBU_STAGE_DONE
:
4322 *pnOne
= MAX_PROGRESS
;
4323 *pnTwo
= MAX_PROGRESS
;
4332 ** Return the current state of the RBU vacuum or update operation.
4334 int sqlite3rbu_state(sqlite3rbu
*p
){
4336 0, SQLITE_RBU_STATE_OAL
, SQLITE_RBU_STATE_MOVE
,
4337 0, SQLITE_RBU_STATE_CHECKPOINT
, SQLITE_RBU_STATE_DONE
4340 assert( RBU_STAGE_OAL
==1 );
4341 assert( RBU_STAGE_MOVE
==2 );
4342 assert( RBU_STAGE_CKPT
==4 );
4343 assert( RBU_STAGE_DONE
==5 );
4344 assert( aRes
[RBU_STAGE_OAL
]==SQLITE_RBU_STATE_OAL
);
4345 assert( aRes
[RBU_STAGE_MOVE
]==SQLITE_RBU_STATE_MOVE
);
4346 assert( aRes
[RBU_STAGE_CKPT
]==SQLITE_RBU_STATE_CHECKPOINT
);
4347 assert( aRes
[RBU_STAGE_DONE
]==SQLITE_RBU_STATE_DONE
);
4349 if( p
->rc
!=SQLITE_OK
&& p
->rc
!=SQLITE_DONE
){
4350 return SQLITE_RBU_STATE_ERROR
;
4352 assert( p
->rc
!=SQLITE_DONE
|| p
->eStage
==RBU_STAGE_DONE
);
4353 assert( p
->eStage
==RBU_STAGE_OAL
4354 || p
->eStage
==RBU_STAGE_MOVE
4355 || p
->eStage
==RBU_STAGE_CKPT
4356 || p
->eStage
==RBU_STAGE_DONE
4358 return aRes
[p
->eStage
];
4362 int sqlite3rbu_savestate(sqlite3rbu
*p
){
4364 if( rc
==SQLITE_DONE
) return SQLITE_OK
;
4366 assert( p
->eStage
>=RBU_STAGE_OAL
&& p
->eStage
<=RBU_STAGE_DONE
);
4367 if( p
->eStage
==RBU_STAGE_OAL
){
4368 assert( rc
!=SQLITE_DONE
);
4369 if( rc
==SQLITE_OK
) rc
= sqlite3_exec(p
->dbMain
, "COMMIT", 0, 0, 0);
4372 /* Sync the db file */
4373 if( rc
==SQLITE_OK
&& p
->eStage
==RBU_STAGE_CKPT
){
4374 sqlite3_file
*pDb
= p
->pTargetFd
->pReal
;
4375 rc
= pDb
->pMethods
->xSync(pDb
, SQLITE_SYNC_NORMAL
);
4379 rbuSaveState(p
, p
->eStage
);
4382 if( p
->eStage
==RBU_STAGE_OAL
){
4383 assert( rc
!=SQLITE_DONE
);
4384 if( rc
==SQLITE_OK
) rc
= sqlite3_exec(p
->dbRbu
, "COMMIT", 0, 0, 0);
4385 if( rc
==SQLITE_OK
){
4386 const char *zBegin
= rbuIsVacuum(p
) ? "BEGIN" : "BEGIN IMMEDIATE";
4387 rc
= sqlite3_exec(p
->dbRbu
, zBegin
, 0, 0, 0);
4389 if( rc
==SQLITE_OK
) rc
= sqlite3_exec(p
->dbMain
, "BEGIN IMMEDIATE", 0, 0,0);
4397 ** Default xRename callback for RBU.
4399 static int xDefaultRename(void *pArg
, const char *zOld
, const char *zNew
){
4401 #if defined(_WIN32_WCE)
4406 zWideOld
= rbuWinUtf8ToUnicode(zOld
);
4408 zWideNew
= rbuWinUtf8ToUnicode(zNew
);
4410 if( MoveFileW(zWideOld
, zWideNew
) ){
4415 sqlite3_free(zWideNew
);
4417 rc
= SQLITE_IOERR_NOMEM
;
4419 sqlite3_free(zWideOld
);
4421 rc
= SQLITE_IOERR_NOMEM
;
4425 rc
= rename(zOld
, zNew
) ? SQLITE_IOERR
: SQLITE_OK
;
4430 void sqlite3rbu_rename_handler(
4433 int (*xRename
)(void *pArg
, const char *zOld
, const char *zNew
)
4436 pRbu
->xRename
= xRename
;
4437 pRbu
->pRenameArg
= pArg
;
4439 pRbu
->xRename
= xDefaultRename
;
4440 pRbu
->pRenameArg
= 0;
4444 /**************************************************************************
4445 ** Beginning of RBU VFS shim methods. The VFS shim modifies the behaviour
4446 ** of a standard VFS in the following ways:
4448 ** 1. Whenever the first page of a main database file is read or
4449 ** written, the value of the change-counter cookie is stored in
4450 ** rbu_file.iCookie. Similarly, the value of the "write-version"
4451 ** database header field is stored in rbu_file.iWriteVer. This ensures
4452 ** that the values are always trustworthy within an open transaction.
4454 ** 2. Whenever an SQLITE_OPEN_WAL file is opened, the (rbu_file.pWalFd)
4455 ** member variable of the associated database file descriptor is set
4456 ** to point to the new file. A mutex protected linked list of all main
4457 ** db fds opened using a particular RBU VFS is maintained at
4458 ** rbu_vfs.pMain to facilitate this.
4460 ** 3. Using a new file-control "SQLITE_FCNTL_RBU", a main db rbu_file
4461 ** object can be marked as the target database of an RBU update. This
4462 ** turns on the following extra special behaviour:
4464 ** 3a. If xAccess() is called to check if there exists a *-wal file
4465 ** associated with an RBU target database currently in RBU_STAGE_OAL
4466 ** stage (preparing the *-oal file), the following special handling
4469 ** * if the *-wal file does exist, return SQLITE_CANTOPEN. An RBU
4470 ** target database may not be in wal mode already.
4472 ** * if the *-wal file does not exist, set the output parameter to
4473 ** non-zero (to tell SQLite that it does exist) anyway.
4475 ** Then, when xOpen() is called to open the *-wal file associated with
4476 ** the RBU target in RBU_STAGE_OAL stage, instead of opening the *-wal
4477 ** file, the rbu vfs opens the corresponding *-oal file instead.
4479 ** 3b. The *-shm pages returned by xShmMap() for a target db file in
4480 ** RBU_STAGE_OAL mode are actually stored in heap memory. This is to
4481 ** avoid creating a *-shm file on disk. Additionally, xShmLock() calls
4482 ** are no-ops on target database files in RBU_STAGE_OAL mode. This is
4483 ** because assert() statements in some VFS implementations fail if
4484 ** xShmLock() is called before xShmMap().
4486 ** 3c. If an EXCLUSIVE lock is attempted on a target database file in any
4487 ** mode except RBU_STAGE_DONE (all work completed and checkpointed), it
4488 ** fails with an SQLITE_BUSY error. This is to stop RBU connections
4489 ** from automatically checkpointing a *-wal (or *-oal) file from within
4492 ** 3d. In RBU_STAGE_CAPTURE mode, all xRead() calls on the wal file, and
4493 ** all xWrite() calls on the target database file perform no IO.
4494 ** Instead the frame and page numbers that would be read and written
4495 ** are recorded. Additionally, successful attempts to obtain exclusive
4496 ** xShmLock() WRITER, CHECKPOINTER and READ0 locks on the target
4497 ** database file are recorded. xShmLock() calls to unlock the same
4498 ** locks are no-ops (so that once obtained, these locks are never
4499 ** relinquished). Finally, calls to xSync() on the target database
4500 ** file fail with SQLITE_NOTICE errors.
4503 static void rbuUnlockShm(rbu_file
*p
){
4504 assert( p
->openFlags
& SQLITE_OPEN_MAIN_DB
);
4506 int (*xShmLock
)(sqlite3_file
*,int,int,int) = p
->pReal
->pMethods
->xShmLock
;
4508 for(i
=0; i
<SQLITE_SHM_NLOCK
;i
++){
4509 if( (1<<i
) & p
->pRbu
->mLock
){
4510 xShmLock(p
->pReal
, i
, 1, SQLITE_SHM_UNLOCK
|SQLITE_SHM_EXCLUSIVE
);
4519 static int rbuUpdateTempSize(rbu_file
*pFd
, sqlite3_int64 nNew
){
4520 sqlite3rbu
*pRbu
= pFd
->pRbu
;
4521 i64 nDiff
= nNew
- pFd
->sz
;
4522 pRbu
->szTemp
+= nDiff
;
4524 assert( pRbu
->szTemp
>=0 );
4525 if( pRbu
->szTempLimit
&& pRbu
->szTemp
>pRbu
->szTempLimit
) return SQLITE_FULL
;
4530 ** Add an item to the main-db lists, if it is not already present.
4532 ** There are two main-db lists. One for all file descriptors, and one
4533 ** for all file descriptors with rbu_file.pDb!=0. If the argument has
4534 ** rbu_file.pDb!=0, then it is assumed to already be present on the
4535 ** main list and is only added to the pDb!=0 list.
4537 static void rbuMainlistAdd(rbu_file
*p
){
4538 rbu_vfs
*pRbuVfs
= p
->pRbuVfs
;
4540 assert( (p
->openFlags
& SQLITE_OPEN_MAIN_DB
) );
4541 sqlite3_mutex_enter(pRbuVfs
->mutex
);
4543 for(pIter
=pRbuVfs
->pMain
; pIter
; pIter
=pIter
->pMainNext
);
4544 p
->pMainNext
= pRbuVfs
->pMain
;
4547 for(pIter
=pRbuVfs
->pMainRbu
; pIter
&& pIter
!=p
; pIter
=pIter
->pMainRbuNext
){}
4549 p
->pMainRbuNext
= pRbuVfs
->pMainRbu
;
4550 pRbuVfs
->pMainRbu
= p
;
4553 sqlite3_mutex_leave(pRbuVfs
->mutex
);
4557 ** Remove an item from the main-db lists.
4559 static void rbuMainlistRemove(rbu_file
*p
){
4561 sqlite3_mutex_enter(p
->pRbuVfs
->mutex
);
4562 for(pp
=&p
->pRbuVfs
->pMain
; *pp
&& *pp
!=p
; pp
=&((*pp
)->pMainNext
)){}
4563 if( *pp
) *pp
= p
->pMainNext
;
4565 for(pp
=&p
->pRbuVfs
->pMainRbu
; *pp
&& *pp
!=p
; pp
=&((*pp
)->pMainRbuNext
)){}
4566 if( *pp
) *pp
= p
->pMainRbuNext
;
4567 p
->pMainRbuNext
= 0;
4568 sqlite3_mutex_leave(p
->pRbuVfs
->mutex
);
4572 ** Given that zWal points to a buffer containing a wal file name passed to
4573 ** either the xOpen() or xAccess() VFS method, search the main-db list for
4574 ** a file-handle opened by the same database connection on the corresponding
4577 ** If parameter bRbu is true, only search for file-descriptors with
4580 static rbu_file
*rbuFindMaindb(rbu_vfs
*pRbuVfs
, const char *zWal
, int bRbu
){
4582 sqlite3_mutex_enter(pRbuVfs
->mutex
);
4584 for(pDb
=pRbuVfs
->pMainRbu
; pDb
&& pDb
->zWal
!=zWal
; pDb
=pDb
->pMainRbuNext
){}
4586 for(pDb
=pRbuVfs
->pMain
; pDb
&& pDb
->zWal
!=zWal
; pDb
=pDb
->pMainNext
){}
4588 sqlite3_mutex_leave(pRbuVfs
->mutex
);
4593 ** Close an rbu file.
4595 static int rbuVfsClose(sqlite3_file
*pFile
){
4596 rbu_file
*p
= (rbu_file
*)pFile
;
4600 /* Free the contents of the apShm[] array. And the array itself. */
4601 for(i
=0; i
<p
->nShm
; i
++){
4602 sqlite3_free(p
->apShm
[i
]);
4604 sqlite3_free(p
->apShm
);
4606 sqlite3_free(p
->zDel
);
4608 if( p
->openFlags
& SQLITE_OPEN_MAIN_DB
){
4609 const sqlite3_io_methods
*pMeth
= p
->pReal
->pMethods
;
4610 rbuMainlistRemove(p
);
4612 if( pMeth
->iVersion
>1 && pMeth
->xShmUnmap
){
4613 pMeth
->xShmUnmap(p
->pReal
, 0);
4616 else if( (p
->openFlags
& SQLITE_OPEN_DELETEONCLOSE
) && p
->pRbu
){
4617 rbuUpdateTempSize(p
, 0);
4619 assert( p
->pMainNext
==0 && p
->pRbuVfs
->pMain
!=p
);
4621 /* Close the underlying file handle */
4622 rc
= p
->pReal
->pMethods
->xClose(p
->pReal
);
4628 ** Read and return an unsigned 32-bit big-endian integer from the buffer
4629 ** passed as the only argument.
4631 static u32
rbuGetU32(u8
*aBuf
){
4632 return ((u32
)aBuf
[0] << 24)
4633 + ((u32
)aBuf
[1] << 16)
4634 + ((u32
)aBuf
[2] << 8)
4639 ** Write an unsigned 32-bit value in big-endian format to the supplied
4642 static void rbuPutU32(u8
*aBuf
, u32 iVal
){
4643 aBuf
[0] = (iVal
>> 24) & 0xFF;
4644 aBuf
[1] = (iVal
>> 16) & 0xFF;
4645 aBuf
[2] = (iVal
>> 8) & 0xFF;
4646 aBuf
[3] = (iVal
>> 0) & 0xFF;
4649 static void rbuPutU16(u8
*aBuf
, u16 iVal
){
4650 aBuf
[0] = (iVal
>> 8) & 0xFF;
4651 aBuf
[1] = (iVal
>> 0) & 0xFF;
4655 ** Read data from an rbuVfs-file.
4657 static int rbuVfsRead(
4658 sqlite3_file
*pFile
,
4663 rbu_file
*p
= (rbu_file
*)pFile
;
4664 sqlite3rbu
*pRbu
= p
->pRbu
;
4667 if( pRbu
&& pRbu
->eStage
==RBU_STAGE_CAPTURE
){
4668 assert( p
->openFlags
& SQLITE_OPEN_WAL
);
4669 rc
= rbuCaptureWalRead(p
->pRbu
, iOfst
, iAmt
);
4671 if( pRbu
&& pRbu
->eStage
==RBU_STAGE_OAL
4672 && (p
->openFlags
& SQLITE_OPEN_WAL
)
4673 && iOfst
>=pRbu
->iOalSz
4676 memset(zBuf
, 0, iAmt
);
4678 rc
= p
->pReal
->pMethods
->xRead(p
->pReal
, zBuf
, iAmt
, iOfst
);
4680 /* If this is being called to read the first page of the target
4681 ** database as part of an rbu vacuum operation, synthesize the
4682 ** contents of the first page if it does not yet exist. Otherwise,
4683 ** SQLite will not check for a *-wal file. */
4684 if( pRbu
&& rbuIsVacuum(pRbu
)
4685 && rc
==SQLITE_IOERR_SHORT_READ
&& iOfst
==0
4686 && (p
->openFlags
& SQLITE_OPEN_MAIN_DB
)
4687 && pRbu
->rc
==SQLITE_OK
4689 sqlite3_file
*pFd
= (sqlite3_file
*)pRbu
->pRbuFd
;
4690 rc
= pFd
->pMethods
->xRead(pFd
, zBuf
, iAmt
, iOfst
);
4691 if( rc
==SQLITE_OK
){
4692 u8
*aBuf
= (u8
*)zBuf
;
4693 u32 iRoot
= rbuGetU32(&aBuf
[52]) ? 1 : 0;
4694 rbuPutU32(&aBuf
[52], iRoot
); /* largest root page number */
4695 rbuPutU32(&aBuf
[36], 0); /* number of free pages */
4696 rbuPutU32(&aBuf
[32], 0); /* first page on free list trunk */
4697 rbuPutU32(&aBuf
[28], 1); /* size of db file in pages */
4698 rbuPutU32(&aBuf
[24], pRbu
->pRbuFd
->iCookie
+1); /* Change counter */
4701 memset(&aBuf
[100], 0, iAmt
-100);
4702 rbuPutU16(&aBuf
[105], iAmt
& 0xFFFF);
4709 if( rc
==SQLITE_OK
&& iOfst
==0 && (p
->openFlags
& SQLITE_OPEN_MAIN_DB
) ){
4710 /* These look like magic numbers. But they are stable, as they are part
4711 ** of the definition of the SQLite file format, which may not change. */
4712 u8
*pBuf
= (u8
*)zBuf
;
4713 p
->iCookie
= rbuGetU32(&pBuf
[24]);
4714 p
->iWriteVer
= pBuf
[19];
4721 ** Write data to an rbuVfs-file.
4723 static int rbuVfsWrite(
4724 sqlite3_file
*pFile
,
4729 rbu_file
*p
= (rbu_file
*)pFile
;
4730 sqlite3rbu
*pRbu
= p
->pRbu
;
4733 if( pRbu
&& pRbu
->eStage
==RBU_STAGE_CAPTURE
){
4734 assert( p
->openFlags
& SQLITE_OPEN_MAIN_DB
);
4735 rc
= rbuCaptureDbWrite(p
->pRbu
, iOfst
);
4738 if( pRbu
->eStage
==RBU_STAGE_OAL
4739 && (p
->openFlags
& SQLITE_OPEN_WAL
)
4740 && iOfst
>=pRbu
->iOalSz
4742 pRbu
->iOalSz
= iAmt
+ iOfst
;
4743 }else if( p
->openFlags
& SQLITE_OPEN_DELETEONCLOSE
){
4744 i64 szNew
= iAmt
+iOfst
;
4746 rc
= rbuUpdateTempSize(p
, szNew
);
4747 if( rc
!=SQLITE_OK
) return rc
;
4751 rc
= p
->pReal
->pMethods
->xWrite(p
->pReal
, zBuf
, iAmt
, iOfst
);
4752 if( rc
==SQLITE_OK
&& iOfst
==0 && (p
->openFlags
& SQLITE_OPEN_MAIN_DB
) ){
4753 /* These look like magic numbers. But they are stable, as they are part
4754 ** of the definition of the SQLite file format, which may not change. */
4755 u8
*pBuf
= (u8
*)zBuf
;
4756 p
->iCookie
= rbuGetU32(&pBuf
[24]);
4757 p
->iWriteVer
= pBuf
[19];
4764 ** Truncate an rbuVfs-file.
4766 static int rbuVfsTruncate(sqlite3_file
*pFile
, sqlite_int64 size
){
4767 rbu_file
*p
= (rbu_file
*)pFile
;
4768 if( (p
->openFlags
& SQLITE_OPEN_DELETEONCLOSE
) && p
->pRbu
){
4769 int rc
= rbuUpdateTempSize(p
, size
);
4770 if( rc
!=SQLITE_OK
) return rc
;
4772 return p
->pReal
->pMethods
->xTruncate(p
->pReal
, size
);
4776 ** Sync an rbuVfs-file.
4778 static int rbuVfsSync(sqlite3_file
*pFile
, int flags
){
4779 rbu_file
*p
= (rbu_file
*)pFile
;
4780 if( p
->pRbu
&& p
->pRbu
->eStage
==RBU_STAGE_CAPTURE
){
4781 if( p
->openFlags
& SQLITE_OPEN_MAIN_DB
){
4782 return SQLITE_NOTICE_RBU
;
4786 return p
->pReal
->pMethods
->xSync(p
->pReal
, flags
);
4790 ** Return the current file-size of an rbuVfs-file.
4792 static int rbuVfsFileSize(sqlite3_file
*pFile
, sqlite_int64
*pSize
){
4793 rbu_file
*p
= (rbu_file
*)pFile
;
4795 rc
= p
->pReal
->pMethods
->xFileSize(p
->pReal
, pSize
);
4797 /* If this is an RBU vacuum operation and this is the target database,
4798 ** pretend that it has at least one page. Otherwise, SQLite will not
4799 ** check for the existance of a *-wal file. rbuVfsRead() contains
4800 ** similar logic. */
4801 if( rc
==SQLITE_OK
&& *pSize
==0
4802 && p
->pRbu
&& rbuIsVacuum(p
->pRbu
)
4803 && (p
->openFlags
& SQLITE_OPEN_MAIN_DB
)
4811 ** Lock an rbuVfs-file.
4813 static int rbuVfsLock(sqlite3_file
*pFile
, int eLock
){
4814 rbu_file
*p
= (rbu_file
*)pFile
;
4815 sqlite3rbu
*pRbu
= p
->pRbu
;
4818 assert( p
->openFlags
& (SQLITE_OPEN_MAIN_DB
|SQLITE_OPEN_TEMP_DB
) );
4819 if( eLock
==SQLITE_LOCK_EXCLUSIVE
4820 && (p
->bNolock
|| (pRbu
&& pRbu
->eStage
!=RBU_STAGE_DONE
))
4822 /* Do not allow EXCLUSIVE locks. Preventing SQLite from taking this
4823 ** prevents it from checkpointing the database from sqlite3_close(). */
4826 rc
= p
->pReal
->pMethods
->xLock(p
->pReal
, eLock
);
4833 ** Unlock an rbuVfs-file.
4835 static int rbuVfsUnlock(sqlite3_file
*pFile
, int eLock
){
4836 rbu_file
*p
= (rbu_file
*)pFile
;
4837 return p
->pReal
->pMethods
->xUnlock(p
->pReal
, eLock
);
4841 ** Check if another file-handle holds a RESERVED lock on an rbuVfs-file.
4843 static int rbuVfsCheckReservedLock(sqlite3_file
*pFile
, int *pResOut
){
4844 rbu_file
*p
= (rbu_file
*)pFile
;
4845 return p
->pReal
->pMethods
->xCheckReservedLock(p
->pReal
, pResOut
);
4849 ** File control method. For custom operations on an rbuVfs-file.
4851 static int rbuVfsFileControl(sqlite3_file
*pFile
, int op
, void *pArg
){
4852 rbu_file
*p
= (rbu_file
*)pFile
;
4853 int (*xControl
)(sqlite3_file
*,int,void*) = p
->pReal
->pMethods
->xFileControl
;
4856 assert( p
->openFlags
& (SQLITE_OPEN_MAIN_DB
|SQLITE_OPEN_TEMP_DB
)
4857 || p
->openFlags
& (SQLITE_OPEN_TRANSIENT_DB
|SQLITE_OPEN_TEMP_JOURNAL
)
4859 if( op
==SQLITE_FCNTL_RBU
){
4860 sqlite3rbu
*pRbu
= (sqlite3rbu
*)pArg
;
4862 /* First try to find another RBU vfs lower down in the vfs stack. If
4863 ** one is found, this vfs will operate in pass-through mode. The lower
4864 ** level vfs will do the special RBU handling. */
4865 rc
= xControl(p
->pReal
, op
, pArg
);
4867 if( rc
==SQLITE_NOTFOUND
){
4868 /* Now search for a zipvfs instance lower down in the VFS stack. If
4869 ** one is found, this is an error. */
4871 rc
= xControl(p
->pReal
, SQLITE_FCNTL_ZIPVFS
, &dummy
);
4872 if( rc
==SQLITE_OK
){
4874 pRbu
->zErrmsg
= sqlite3_mprintf("rbu/zipvfs setup error");
4875 }else if( rc
==SQLITE_NOTFOUND
){
4876 pRbu
->pTargetFd
= p
;
4879 if( p
->pWalFd
) p
->pWalFd
->pRbu
= pRbu
;
4885 else if( op
==SQLITE_FCNTL_RBUCNT
){
4886 sqlite3rbu
*pRbu
= (sqlite3rbu
*)pArg
;
4892 rc
= xControl(p
->pReal
, op
, pArg
);
4893 if( rc
==SQLITE_OK
&& op
==SQLITE_FCNTL_VFSNAME
){
4894 rbu_vfs
*pRbuVfs
= p
->pRbuVfs
;
4895 char *zIn
= *(char**)pArg
;
4896 char *zOut
= sqlite3_mprintf("rbu(%s)/%z", pRbuVfs
->base
.zName
, zIn
);
4897 *(char**)pArg
= zOut
;
4898 if( zOut
==0 ) rc
= SQLITE_NOMEM
;
4905 ** Return the sector-size in bytes for an rbuVfs-file.
4907 static int rbuVfsSectorSize(sqlite3_file
*pFile
){
4908 rbu_file
*p
= (rbu_file
*)pFile
;
4909 return p
->pReal
->pMethods
->xSectorSize(p
->pReal
);
4913 ** Return the device characteristic flags supported by an rbuVfs-file.
4915 static int rbuVfsDeviceCharacteristics(sqlite3_file
*pFile
){
4916 rbu_file
*p
= (rbu_file
*)pFile
;
4917 return p
->pReal
->pMethods
->xDeviceCharacteristics(p
->pReal
);
4921 ** Take or release a shared-memory lock.
4923 static int rbuVfsShmLock(sqlite3_file
*pFile
, int ofst
, int n
, int flags
){
4924 rbu_file
*p
= (rbu_file
*)pFile
;
4925 sqlite3rbu
*pRbu
= p
->pRbu
;
4928 #ifdef SQLITE_AMALGAMATION
4929 assert( WAL_CKPT_LOCK
==1 );
4932 assert( p
->openFlags
& (SQLITE_OPEN_MAIN_DB
|SQLITE_OPEN_TEMP_DB
) );
4934 pRbu
->eStage
==RBU_STAGE_OAL
4935 || pRbu
->eStage
==RBU_STAGE_MOVE
4936 || pRbu
->eStage
==RBU_STAGE_DONE
4938 /* Prevent SQLite from taking a shm-lock on the target file when it
4939 ** is supplying heap memory to the upper layer in place of *-shm
4941 if( ofst
==WAL_LOCK_CKPT
&& n
==1 ) rc
= SQLITE_BUSY
;
4944 if( pRbu
&& pRbu
->eStage
==RBU_STAGE_CAPTURE
){
4947 if( bCapture
==0 || 0==(flags
& SQLITE_SHM_UNLOCK
) ){
4948 rc
= p
->pReal
->pMethods
->xShmLock(p
->pReal
, ofst
, n
, flags
);
4949 if( bCapture
&& rc
==SQLITE_OK
){
4950 pRbu
->mLock
|= ((1<<n
) - 1) << ofst
;
4959 ** Obtain a pointer to a mapping of a single 32KiB page of the *-shm file.
4961 static int rbuVfsShmMap(
4962 sqlite3_file
*pFile
,
4968 rbu_file
*p
= (rbu_file
*)pFile
;
4970 int eStage
= (p
->pRbu
? p
->pRbu
->eStage
: 0);
4972 /* If not in RBU_STAGE_OAL, allow this call to pass through. Or, if this
4973 ** rbu is in the RBU_STAGE_OAL state, use heap memory for *-shm space
4974 ** instead of a file on disk. */
4975 assert( p
->openFlags
& (SQLITE_OPEN_MAIN_DB
|SQLITE_OPEN_TEMP_DB
) );
4976 if( eStage
==RBU_STAGE_OAL
){
4977 sqlite3_int64 nByte
= (iRegion
+1) * sizeof(char*);
4978 char **apNew
= (char**)sqlite3_realloc64(p
->apShm
, nByte
);
4980 /* This is an RBU connection that uses its own heap memory for the
4981 ** pages of the *-shm file. Since no other process can have run
4982 ** recovery, the connection must request *-shm pages in order
4983 ** from start to finish. */
4984 assert( iRegion
==p
->nShm
);
4988 memset(&apNew
[p
->nShm
], 0, sizeof(char*) * (1 + iRegion
- p
->nShm
));
4990 p
->nShm
= iRegion
+1;
4993 if( rc
==SQLITE_OK
){
4994 char *pNew
= (char*)sqlite3_malloc64(szRegion
);
4998 memset(pNew
, 0, szRegion
);
4999 p
->apShm
[iRegion
] = pNew
;
5003 if( rc
==SQLITE_OK
){
5004 *pp
= p
->apShm
[iRegion
];
5009 assert( p
->apShm
==0 );
5010 rc
= p
->pReal
->pMethods
->xShmMap(p
->pReal
, iRegion
, szRegion
, isWrite
, pp
);
5019 static void rbuVfsShmBarrier(sqlite3_file
*pFile
){
5020 rbu_file
*p
= (rbu_file
*)pFile
;
5021 p
->pReal
->pMethods
->xShmBarrier(p
->pReal
);
5025 ** The xShmUnmap method.
5027 static int rbuVfsShmUnmap(sqlite3_file
*pFile
, int delFlag
){
5028 rbu_file
*p
= (rbu_file
*)pFile
;
5030 int eStage
= (p
->pRbu
? p
->pRbu
->eStage
: 0);
5032 assert( p
->openFlags
& (SQLITE_OPEN_MAIN_DB
|SQLITE_OPEN_TEMP_DB
) );
5033 if( eStage
==RBU_STAGE_OAL
|| eStage
==RBU_STAGE_MOVE
){
5036 /* Release the checkpointer and writer locks */
5038 rc
= p
->pReal
->pMethods
->xShmUnmap(p
->pReal
, delFlag
);
5044 ** Open an rbu file handle.
5046 static int rbuVfsOpen(
5049 sqlite3_file
*pFile
,
5053 static sqlite3_io_methods rbuvfs_io_methods
= {
5055 rbuVfsClose
, /* xClose */
5056 rbuVfsRead
, /* xRead */
5057 rbuVfsWrite
, /* xWrite */
5058 rbuVfsTruncate
, /* xTruncate */
5059 rbuVfsSync
, /* xSync */
5060 rbuVfsFileSize
, /* xFileSize */
5061 rbuVfsLock
, /* xLock */
5062 rbuVfsUnlock
, /* xUnlock */
5063 rbuVfsCheckReservedLock
, /* xCheckReservedLock */
5064 rbuVfsFileControl
, /* xFileControl */
5065 rbuVfsSectorSize
, /* xSectorSize */
5066 rbuVfsDeviceCharacteristics
, /* xDeviceCharacteristics */
5067 rbuVfsShmMap
, /* xShmMap */
5068 rbuVfsShmLock
, /* xShmLock */
5069 rbuVfsShmBarrier
, /* xShmBarrier */
5070 rbuVfsShmUnmap
, /* xShmUnmap */
5071 0, 0 /* xFetch, xUnfetch */
5073 static sqlite3_io_methods rbuvfs_io_methods1
= {
5075 rbuVfsClose
, /* xClose */
5076 rbuVfsRead
, /* xRead */
5077 rbuVfsWrite
, /* xWrite */
5078 rbuVfsTruncate
, /* xTruncate */
5079 rbuVfsSync
, /* xSync */
5080 rbuVfsFileSize
, /* xFileSize */
5081 rbuVfsLock
, /* xLock */
5082 rbuVfsUnlock
, /* xUnlock */
5083 rbuVfsCheckReservedLock
, /* xCheckReservedLock */
5084 rbuVfsFileControl
, /* xFileControl */
5085 rbuVfsSectorSize
, /* xSectorSize */
5086 rbuVfsDeviceCharacteristics
, /* xDeviceCharacteristics */
5092 rbu_vfs
*pRbuVfs
= (rbu_vfs
*)pVfs
;
5093 sqlite3_vfs
*pRealVfs
= pRbuVfs
->pRealVfs
;
5094 rbu_file
*pFd
= (rbu_file
*)pFile
;
5096 const char *zOpen
= zName
;
5099 memset(pFd
, 0, sizeof(rbu_file
));
5100 pFd
->pReal
= (sqlite3_file
*)&pFd
[1];
5101 pFd
->pRbuVfs
= pRbuVfs
;
5102 pFd
->openFlags
= flags
;
5104 if( flags
& SQLITE_OPEN_MAIN_DB
){
5105 /* A main database has just been opened. The following block sets
5106 ** (pFd->zWal) to point to a buffer owned by SQLite that contains
5107 ** the name of the *-wal file this db connection will use. SQLite
5108 ** happens to pass a pointer to this buffer when using xAccess()
5109 ** or xOpen() to operate on the *-wal file. */
5110 pFd
->zWal
= sqlite3_filename_wal(zName
);
5112 else if( flags
& SQLITE_OPEN_WAL
){
5113 rbu_file
*pDb
= rbuFindMaindb(pRbuVfs
, zName
, 0);
5115 if( pDb
->pRbu
&& pDb
->pRbu
->eStage
==RBU_STAGE_OAL
){
5116 /* This call is to open a *-wal file. Intead, open the *-oal. */
5118 if( rbuIsVacuum(pDb
->pRbu
) ){
5119 zOpen
= sqlite3_db_filename(pDb
->pRbu
->dbRbu
, "main");
5120 zOpen
= sqlite3_filename_wal(zOpen
);
5122 nOpen
= strlen(zOpen
);
5123 ((char*)zOpen
)[nOpen
-3] = 'o';
5124 pFd
->pRbu
= pDb
->pRbu
;
5130 pFd
->pRbu
= pRbuVfs
->pRbu
;
5133 if( oflags
& SQLITE_OPEN_MAIN_DB
5134 && sqlite3_uri_boolean(zName
, "rbu_memory", 0)
5136 assert( oflags
& SQLITE_OPEN_MAIN_DB
);
5137 oflags
= SQLITE_OPEN_TEMP_DB
| SQLITE_OPEN_READWRITE
| SQLITE_OPEN_CREATE
|
5138 SQLITE_OPEN_EXCLUSIVE
| SQLITE_OPEN_DELETEONCLOSE
;
5142 if( rc
==SQLITE_OK
){
5143 rc
= pRealVfs
->xOpen(pRealVfs
, zOpen
, pFd
->pReal
, oflags
, pOutFlags
);
5145 if( pFd
->pReal
->pMethods
){
5146 const sqlite3_io_methods
*pMeth
= pFd
->pReal
->pMethods
;
5147 /* The xOpen() operation has succeeded. Set the sqlite3_file.pMethods
5148 ** pointer and, if the file is a main database file, link it into the
5149 ** mutex protected linked list of all such files. */
5150 if( pMeth
->iVersion
<2 || pMeth
->xShmLock
==0 ){
5151 pFile
->pMethods
= &rbuvfs_io_methods1
;
5153 pFile
->pMethods
= &rbuvfs_io_methods
;
5155 if( flags
& SQLITE_OPEN_MAIN_DB
){
5156 rbuMainlistAdd(pFd
);
5159 sqlite3_free(pFd
->zDel
);
5166 ** Delete the file located at zPath.
5168 static int rbuVfsDelete(sqlite3_vfs
*pVfs
, const char *zPath
, int dirSync
){
5169 sqlite3_vfs
*pRealVfs
= ((rbu_vfs
*)pVfs
)->pRealVfs
;
5170 return pRealVfs
->xDelete(pRealVfs
, zPath
, dirSync
);
5174 ** Test for access permissions. Return true if the requested permission
5175 ** is available, or false otherwise.
5177 static int rbuVfsAccess(
5183 rbu_vfs
*pRbuVfs
= (rbu_vfs
*)pVfs
;
5184 sqlite3_vfs
*pRealVfs
= pRbuVfs
->pRealVfs
;
5187 rc
= pRealVfs
->xAccess(pRealVfs
, zPath
, flags
, pResOut
);
5189 /* If this call is to check if a *-wal file associated with an RBU target
5190 ** database connection exists, and the RBU update is in RBU_STAGE_OAL,
5191 ** the following special handling is activated:
5193 ** a) if the *-wal file does exist, return SQLITE_CANTOPEN. This
5194 ** ensures that the RBU extension never tries to update a database
5195 ** in wal mode, even if the first page of the database file has
5198 ** b) if the *-wal file does not exist, claim that it does anyway,
5199 ** causing SQLite to call xOpen() to open it. This call will also
5200 ** be intercepted (see the rbuVfsOpen() function) and the *-oal
5201 ** file opened instead.
5203 if( rc
==SQLITE_OK
&& flags
==SQLITE_ACCESS_EXISTS
){
5204 rbu_file
*pDb
= rbuFindMaindb(pRbuVfs
, zPath
, 1);
5205 if( pDb
&& pDb
->pRbu
->eStage
==RBU_STAGE_OAL
){
5206 assert( pDb
->pRbu
);
5208 rc
= SQLITE_CANTOPEN
;
5210 sqlite3_int64 sz
= 0;
5211 rc
= rbuVfsFileSize(&pDb
->base
, &sz
);
5221 ** Populate buffer zOut with the full canonical pathname corresponding
5222 ** to the pathname in zPath. zOut is guaranteed to point to a buffer
5223 ** of at least (DEVSYM_MAX_PATHNAME+1) bytes.
5225 static int rbuVfsFullPathname(
5231 sqlite3_vfs
*pRealVfs
= ((rbu_vfs
*)pVfs
)->pRealVfs
;
5232 return pRealVfs
->xFullPathname(pRealVfs
, zPath
, nOut
, zOut
);
5235 #ifndef SQLITE_OMIT_LOAD_EXTENSION
5237 ** Open the dynamic library located at zPath and return a handle.
5239 static void *rbuVfsDlOpen(sqlite3_vfs
*pVfs
, const char *zPath
){
5240 sqlite3_vfs
*pRealVfs
= ((rbu_vfs
*)pVfs
)->pRealVfs
;
5241 return pRealVfs
->xDlOpen(pRealVfs
, zPath
);
5245 ** Populate the buffer zErrMsg (size nByte bytes) with a human readable
5246 ** utf-8 string describing the most recent error encountered associated
5247 ** with dynamic libraries.
5249 static void rbuVfsDlError(sqlite3_vfs
*pVfs
, int nByte
, char *zErrMsg
){
5250 sqlite3_vfs
*pRealVfs
= ((rbu_vfs
*)pVfs
)->pRealVfs
;
5251 pRealVfs
->xDlError(pRealVfs
, nByte
, zErrMsg
);
5255 ** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
5257 static void (*rbuVfsDlSym(
5262 sqlite3_vfs
*pRealVfs
= ((rbu_vfs
*)pVfs
)->pRealVfs
;
5263 return pRealVfs
->xDlSym(pRealVfs
, pArg
, zSym
);
5267 ** Close the dynamic library handle pHandle.
5269 static void rbuVfsDlClose(sqlite3_vfs
*pVfs
, void *pHandle
){
5270 sqlite3_vfs
*pRealVfs
= ((rbu_vfs
*)pVfs
)->pRealVfs
;
5271 pRealVfs
->xDlClose(pRealVfs
, pHandle
);
5273 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
5276 ** Populate the buffer pointed to by zBufOut with nByte bytes of
5279 static int rbuVfsRandomness(sqlite3_vfs
*pVfs
, int nByte
, char *zBufOut
){
5280 sqlite3_vfs
*pRealVfs
= ((rbu_vfs
*)pVfs
)->pRealVfs
;
5281 return pRealVfs
->xRandomness(pRealVfs
, nByte
, zBufOut
);
5285 ** Sleep for nMicro microseconds. Return the number of microseconds
5288 static int rbuVfsSleep(sqlite3_vfs
*pVfs
, int nMicro
){
5289 sqlite3_vfs
*pRealVfs
= ((rbu_vfs
*)pVfs
)->pRealVfs
;
5290 return pRealVfs
->xSleep(pRealVfs
, nMicro
);
5294 ** Return the current time as a Julian Day number in *pTimeOut.
5296 static int rbuVfsCurrentTime(sqlite3_vfs
*pVfs
, double *pTimeOut
){
5297 sqlite3_vfs
*pRealVfs
= ((rbu_vfs
*)pVfs
)->pRealVfs
;
5298 return pRealVfs
->xCurrentTime(pRealVfs
, pTimeOut
);
5304 static int rbuVfsGetLastError(sqlite3_vfs
*pVfs
, int a
, char *b
){
5309 ** Deregister and destroy an RBU vfs created by an earlier call to
5310 ** sqlite3rbu_create_vfs().
5312 void sqlite3rbu_destroy_vfs(const char *zName
){
5313 sqlite3_vfs
*pVfs
= sqlite3_vfs_find(zName
);
5314 if( pVfs
&& pVfs
->xOpen
==rbuVfsOpen
){
5315 sqlite3_mutex_free(((rbu_vfs
*)pVfs
)->mutex
);
5316 sqlite3_vfs_unregister(pVfs
);
5322 ** Create an RBU VFS named zName that accesses the underlying file-system
5323 ** via existing VFS zParent. The new object is registered as a non-default
5324 ** VFS with SQLite before returning.
5326 int sqlite3rbu_create_vfs(const char *zName
, const char *zParent
){
5328 /* Template for VFS */
5329 static sqlite3_vfs vfs_template
= {
5336 rbuVfsOpen
, /* xOpen */
5337 rbuVfsDelete
, /* xDelete */
5338 rbuVfsAccess
, /* xAccess */
5339 rbuVfsFullPathname
, /* xFullPathname */
5341 #ifndef SQLITE_OMIT_LOAD_EXTENSION
5342 rbuVfsDlOpen
, /* xDlOpen */
5343 rbuVfsDlError
, /* xDlError */
5344 rbuVfsDlSym
, /* xDlSym */
5345 rbuVfsDlClose
, /* xDlClose */
5350 rbuVfsRandomness
, /* xRandomness */
5351 rbuVfsSleep
, /* xSleep */
5352 rbuVfsCurrentTime
, /* xCurrentTime */
5353 rbuVfsGetLastError
, /* xGetLastError */
5354 0, /* xCurrentTimeInt64 (version 2) */
5355 0, 0, 0 /* Unimplemented version 3 methods */
5358 rbu_vfs
*pNew
= 0; /* Newly allocated VFS */
5363 nName
= strlen(zName
);
5364 nByte
= sizeof(rbu_vfs
) + nName
+ 1;
5365 pNew
= (rbu_vfs
*)sqlite3_malloc64(nByte
);
5369 sqlite3_vfs
*pParent
; /* Parent VFS */
5370 memset(pNew
, 0, nByte
);
5371 pParent
= sqlite3_vfs_find(zParent
);
5373 rc
= SQLITE_NOTFOUND
;
5376 memcpy(&pNew
->base
, &vfs_template
, sizeof(sqlite3_vfs
));
5377 pNew
->base
.mxPathname
= pParent
->mxPathname
;
5378 pNew
->base
.szOsFile
= sizeof(rbu_file
) + pParent
->szOsFile
;
5379 pNew
->pRealVfs
= pParent
;
5380 pNew
->base
.zName
= (const char*)(zSpace
= (char*)&pNew
[1]);
5381 memcpy(zSpace
, zName
, nName
);
5383 /* Allocate the mutex and register the new VFS (not as the default) */
5384 pNew
->mutex
= sqlite3_mutex_alloc(SQLITE_MUTEX_RECURSIVE
);
5385 if( pNew
->mutex
==0 ){
5388 rc
= sqlite3_vfs_register(&pNew
->base
, 0);
5392 if( rc
!=SQLITE_OK
){
5393 sqlite3_mutex_free(pNew
->mutex
);
5402 ** Configure the aggregate temp file size limit for this RBU handle.
5404 sqlite3_int64
sqlite3rbu_temp_size_limit(sqlite3rbu
*pRbu
, sqlite3_int64 n
){
5406 pRbu
->szTempLimit
= n
;
5408 return pRbu
->szTempLimit
;
5411 sqlite3_int64
sqlite3rbu_temp_size(sqlite3rbu
*pRbu
){
5412 return pRbu
->szTemp
;
5416 /**************************************************************************/
5418 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU) */