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