modernc.org/cc@v1.0.1/v2/testdata/_sqlite/ext/rbu/sqlite3rbu.c (about)

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