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