#include <assert.h>
#include <string.h>
#include <stdio.h>
#include "sqlite3.h"
#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU)
#include "sqlite3rbu.h"
#if defined(_WIN32_WCE)
#include "windows.h"
#endif
#define SQLITE_RBU_UPDATE_CACHESIZE 16
#ifndef RBU_ENABLE_DELTA_CKSUM
# define RBU_ENABLE_DELTA_CKSUM 0
#endif
#if !defined(SQLITE_AMALGAMATION)
# define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
#endif
#define RBU_EXCLUSIVE_CHECKPOINT "rbu_exclusive_checkpoint"
#define RBU_STATE_STAGE 1
#define RBU_STATE_TBL 2
#define RBU_STATE_IDX 3
#define RBU_STATE_ROW 4
#define RBU_STATE_PROGRESS 5
#define RBU_STATE_CKPT 6
#define RBU_STATE_COOKIE 7
#define RBU_STATE_OALSZ 8
#define RBU_STATE_PHASEONESTEP 9
#define RBU_STATE_DATATBL 10
#define RBU_STAGE_OAL 1
#define RBU_STAGE_MOVE 2
#define RBU_STAGE_CAPTURE 3
#define RBU_STAGE_CKPT 4
#define RBU_STAGE_DONE 5
#define RBU_CREATE_STATE \
"CREATE TABLE IF NOT EXISTS %s.rbu_state(k INTEGER PRIMARY KEY, v)"
typedef struct RbuFrame RbuFrame;
typedef struct RbuObjIter RbuObjIter;
typedef struct RbuState RbuState;
typedef struct RbuSpan RbuSpan;
typedef struct rbu_vfs rbu_vfs;
typedef struct rbu_file rbu_file;
typedef struct RbuUpdateStmt RbuUpdateStmt;
#if !defined(SQLITE_AMALGAMATION)
typedef unsigned int u32;
typedef unsigned short u16;
typedef unsigned char u8;
typedef sqlite3_int64 i64;
#endif
#define WAL_LOCK_WRITE 0
#define WAL_LOCK_CKPT 1
#define WAL_LOCK_READ0 3
#define SQLITE_FCNTL_RBUCNT 5149216
struct RbuState {
int eStage;
char *zTbl;
char *zDataTbl;
char *zIdx;
i64 iWalCksum;
int nRow;
i64 nProgress;
u32 iCookie;
i64 iOalSz;
i64 nPhaseOneStep;
};
struct RbuUpdateStmt {
char *zMask;
sqlite3_stmt *pUpdate;
RbuUpdateStmt *pNext;
};
struct RbuSpan {
const char *zSpan;
int nSpan;
};
struct RbuObjIter {
sqlite3_stmt *pTblIter;
sqlite3_stmt *pIdxIter;
int nTblCol;
char **azTblCol;
char **azTblType;
int *aiSrcOrder;
u8 *abTblPk;
u8 *abNotNull;
u8 *abIndexed;
int eType;
int bCleanup;
const char *zTbl;
const char *zDataTbl;
const char *zIdx;
int iTnum;
int iPkTnum;
int bUnique;
int nIndex;
int nCol;
sqlite3_stmt *pSelect;
sqlite3_stmt *pInsert;
sqlite3_stmt *pDelete;
sqlite3_stmt *pTmpInsert;
int nIdxCol;
RbuSpan *aIdxCol;
char *zIdxSql;
RbuUpdateStmt *pRbuUpdate;
};
#define RBU_PK_NOTABLE 0
#define RBU_PK_NONE 1
#define RBU_PK_IPK 2
#define RBU_PK_EXTERNAL 3
#define RBU_PK_WITHOUT_ROWID 4
#define RBU_PK_VTAB 5
#define RBU_INSERT 1
#define RBU_DELETE 2
#define RBU_REPLACE 3
#define RBU_IDX_DELETE 4
#define RBU_IDX_INSERT 5
#define RBU_UPDATE 6
struct RbuFrame {
u32 iDbPage;
u32 iWalFrame;
};
struct sqlite3rbu {
int eStage;
sqlite3 *dbMain;
sqlite3 *dbRbu;
char *zTarget;
char *zRbu;
char *zState;
char zStateDb[5];
int rc;
char *zErrmsg;
int nStep;
int nProgress;
RbuObjIter objiter;
const char *zVfsName;
rbu_file *pTargetFd;
int nPagePerSector;
i64 iOalSz;
i64 nPhaseOneStep;
void *pRenameArg;
int (*xRename)(void*, const char*, const char*);
u32 iMaxFrame;
u32 mLock;
int nFrame;
int nFrameAlloc;
RbuFrame *aFrame;
int pgsz;
u8 *aBuf;
i64 iWalCksum;
i64 szTemp;
i64 szTempLimit;
int nRbu;
rbu_file *pRbuFd;
};
struct rbu_vfs {
sqlite3_vfs base;
sqlite3_vfs *pRealVfs;
sqlite3_mutex *mutex;
sqlite3rbu *pRbu;
rbu_file *pMain;
rbu_file *pMainRbu;
};
struct rbu_file {
sqlite3_file base;
sqlite3_file *pReal;
rbu_vfs *pRbuVfs;
sqlite3rbu *pRbu;
i64 sz;
int openFlags;
u32 iCookie;
u8 iWriteVer;
u8 bNolock;
int nShm;
char **apShm;
char *zDel;
const char *zWal;
rbu_file *pWalFd;
rbu_file *pMainNext;
rbu_file *pMainRbuNext;
};
#define rbuIsVacuum(p) ((p)->zTarget==0)
static unsigned int rbuDeltaGetInt(const char **pz, int *pLen){
static const signed char zValue[] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
-1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, 36,
-1, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, -1, -1, -1, 63, -1,
};
unsigned int v = 0;
int c;
unsigned char *z = (unsigned char*)*pz;
unsigned char *zStart = z;
while( (c = zValue[0x7f&*(z++)])>=0 ){
v = (v<<6) + c;
}
z--;
*pLen -= z - zStart;
*pz = (char*)z;
return v;
}
#if RBU_ENABLE_DELTA_CKSUM
static unsigned int rbuDeltaChecksum(const char *zIn, size_t N){
const unsigned char *z = (const unsigned char *)zIn;
unsigned sum0 = 0;
unsigned sum1 = 0;
unsigned sum2 = 0;
unsigned sum3 = 0;
while(N >= 16){
sum0 += ((unsigned)z[0] + z[4] + z[8] + z[12]);
sum1 += ((unsigned)z[1] + z[5] + z[9] + z[13]);
sum2 += ((unsigned)z[2] + z[6] + z[10]+ z[14]);
sum3 += ((unsigned)z[3] + z[7] + z[11]+ z[15]);
z += 16;
N -= 16;
}
while(N >= 4){
sum0 += z[0];
sum1 += z[1];
sum2 += z[2];
sum3 += z[3];
z += 4;
N -= 4;
}
sum3 += (sum2 << 8) + (sum1 << 16) + (sum0 << 24);
switch(N){
case 3: sum3 += (z[2] << 8);
case 2: sum3 += (z[1] << 16);
case 1: sum3 += (z[0] << 24);
default: ;
}
return sum3;
}
#endif
static int rbuDeltaApply(
const char *zSrc,
int lenSrc,
const char *zDelta,
int lenDelta,
char *zOut
){
unsigned int limit;
unsigned int total = 0;
#if RBU_ENABLE_DELTA_CKSUM
char *zOrigOut = zOut;
#endif
limit = rbuDeltaGetInt(&zDelta, &lenDelta);
if( *zDelta!='\n' ){
return -1;
}
zDelta++; lenDelta--;
while( *zDelta && lenDelta>0 ){
unsigned int cnt, ofst;
cnt = rbuDeltaGetInt(&zDelta, &lenDelta);
switch( zDelta[0] ){
case '@': {
zDelta++; lenDelta--;
ofst = rbuDeltaGetInt(&zDelta, &lenDelta);
if( lenDelta>0 && zDelta[0]!=',' ){
return -1;
}
zDelta++; lenDelta--;
total += cnt;
if( total>limit ){
return -1;
}
if( (int)(ofst+cnt) > lenSrc ){
return -1;
}
memcpy(zOut, &zSrc[ofst], cnt);
zOut += cnt;
break;
}
case ':': {
zDelta++; lenDelta--;
total += cnt;
if( total>limit ){
return -1;
}
if( (int)cnt>lenDelta ){
return -1;
}
memcpy(zOut, zDelta, cnt);
zOut += cnt;
zDelta += cnt;
lenDelta -= cnt;
break;
}
case ';': {
zDelta++; lenDelta--;
zOut[0] = 0;
#if RBU_ENABLE_DELTA_CKSUM
if( cnt!=rbuDeltaChecksum(zOrigOut, total) ){
return -1;
}
#endif
if( total!=limit ){
return -1;
}
return total;
}
default: {
return -1;
}
}
}
return -1;
}
static int rbuDeltaOutputSize(const char *zDelta, int lenDelta){
int size;
size = rbuDeltaGetInt(&zDelta, &lenDelta);
if( *zDelta!='\n' ){
return -1;
}
return size;
}
static void rbuFossilDeltaFunc(
sqlite3_context *context,
int argc,
sqlite3_value **argv
){
const char *aDelta;
int nDelta;
const char *aOrig;
int nOrig;
int nOut;
int nOut2;
char *aOut;
assert( argc==2 );
nOrig = sqlite3_value_bytes(argv[0]);
aOrig = (const char*)sqlite3_value_blob(argv[0]);
nDelta = sqlite3_value_bytes(argv[1]);
aDelta = (const char*)sqlite3_value_blob(argv[1]);
nOut = rbuDeltaOutputSize(aDelta, nDelta);
if( nOut<0 ){
sqlite3_result_error(context, "corrupt fossil delta", -1);
return;
}
aOut = sqlite3_malloc(nOut+1);
if( aOut==0 ){
sqlite3_result_error_nomem(context);
}else{
nOut2 = rbuDeltaApply(aOrig, nOrig, aDelta, nDelta, aOut);
if( nOut2!=nOut ){
sqlite3_free(aOut);
sqlite3_result_error(context, "corrupt fossil delta", -1);
}else{
sqlite3_result_blob(context, aOut, nOut, sqlite3_free);
}
}
}
static int prepareAndCollectError(
sqlite3 *db,
sqlite3_stmt **ppStmt,
char **pzErrmsg,
const char *zSql
){
int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
if( rc!=SQLITE_OK ){
*pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
*ppStmt = 0;
}
return rc;
}
static int resetAndCollectError(sqlite3_stmt *pStmt, char **pzErrmsg){
int rc = sqlite3_reset(pStmt);
if( rc!=SQLITE_OK ){
*pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(sqlite3_db_handle(pStmt)));
}
return rc;
}
static int prepareFreeAndCollectError(
sqlite3 *db,
sqlite3_stmt **ppStmt,
char **pzErrmsg,
char *zSql
){
int rc;
assert( *pzErrmsg==0 );
if( zSql==0 ){
rc = SQLITE_NOMEM;
*ppStmt = 0;
}else{
rc = prepareAndCollectError(db, ppStmt, pzErrmsg, zSql);
sqlite3_free(zSql);
}
return rc;
}
static void rbuObjIterFreeCols(RbuObjIter *pIter){
int i;
for(i=0; i<pIter->nTblCol; i++){
sqlite3_free(pIter->azTblCol[i]);
sqlite3_free(pIter->azTblType[i]);
}
sqlite3_free(pIter->azTblCol);
pIter->azTblCol = 0;
pIter->azTblType = 0;
pIter->aiSrcOrder = 0;
pIter->abTblPk = 0;
pIter->abNotNull = 0;
pIter->nTblCol = 0;
pIter->eType = 0;
}
static void rbuObjIterClearStatements(RbuObjIter *pIter){
RbuUpdateStmt *pUp;
sqlite3_finalize(pIter->pSelect);
sqlite3_finalize(pIter->pInsert);
sqlite3_finalize(pIter->pDelete);
sqlite3_finalize(pIter->pTmpInsert);
pUp = pIter->pRbuUpdate;
while( pUp ){
RbuUpdateStmt *pTmp = pUp->pNext;
sqlite3_finalize(pUp->pUpdate);
sqlite3_free(pUp);
pUp = pTmp;
}
sqlite3_free(pIter->aIdxCol);
sqlite3_free(pIter->zIdxSql);
pIter->pSelect = 0;
pIter->pInsert = 0;
pIter->pDelete = 0;
pIter->pRbuUpdate = 0;
pIter->pTmpInsert = 0;
pIter->nCol = 0;
pIter->nIdxCol = 0;
pIter->aIdxCol = 0;
pIter->zIdxSql = 0;
}
static void rbuObjIterFinalize(RbuObjIter *pIter){
rbuObjIterClearStatements(pIter);
sqlite3_finalize(pIter->pTblIter);
sqlite3_finalize(pIter->pIdxIter);
rbuObjIterFreeCols(pIter);
memset(pIter, 0, sizeof(RbuObjIter));
}
static int rbuObjIterNext(sqlite3rbu *p, RbuObjIter *pIter){
int rc = p->rc;
if( rc==SQLITE_OK ){
rbuObjIterClearStatements(pIter);
if( pIter->zIdx==0 ){
rc = sqlite3_exec(p->dbMain,
"DROP TRIGGER IF EXISTS temp.rbu_insert_tr;"
"DROP TRIGGER IF EXISTS temp.rbu_update1_tr;"
"DROP TRIGGER IF EXISTS temp.rbu_update2_tr;"
"DROP TRIGGER IF EXISTS temp.rbu_delete_tr;"
, 0, 0, &p->zErrmsg
);
}
if( rc==SQLITE_OK ){
if( pIter->bCleanup ){
rbuObjIterFreeCols(pIter);
pIter->bCleanup = 0;
rc = sqlite3_step(pIter->pTblIter);
if( rc!=SQLITE_ROW ){
rc = resetAndCollectError(pIter->pTblIter, &p->zErrmsg);
pIter->zTbl = 0;
}else{
pIter->zTbl = (const char*)sqlite3_column_text(pIter->pTblIter, 0);
pIter->zDataTbl = (const char*)sqlite3_column_text(pIter->pTblIter,1);
rc = (pIter->zDataTbl && pIter->zTbl) ? SQLITE_OK : SQLITE_NOMEM;
}
}else{
if( pIter->zIdx==0 ){
sqlite3_stmt *pIdx = pIter->pIdxIter;
rc = sqlite3_bind_text(pIdx, 1, pIter->zTbl, -1, SQLITE_STATIC);
}
if( rc==SQLITE_OK ){
rc = sqlite3_step(pIter->pIdxIter);
if( rc!=SQLITE_ROW ){
rc = resetAndCollectError(pIter->pIdxIter, &p->zErrmsg);
pIter->bCleanup = 1;
pIter->zIdx = 0;
}else{
pIter->zIdx = (const char*)sqlite3_column_text(pIter->pIdxIter, 0);
pIter->iTnum = sqlite3_column_int(pIter->pIdxIter, 1);
pIter->bUnique = sqlite3_column_int(pIter->pIdxIter, 2);
rc = pIter->zIdx ? SQLITE_OK : SQLITE_NOMEM;
}
}
}
}
}
if( rc!=SQLITE_OK ){
rbuObjIterFinalize(pIter);
p->rc = rc;
}
return rc;
}
static void rbuTargetNameFunc(
sqlite3_context *pCtx,
int argc,
sqlite3_value **argv
){
sqlite3rbu *p = sqlite3_user_data(pCtx);
const char *zIn;
assert( argc==1 || argc==2 );
zIn = (const char*)sqlite3_value_text(argv[0]);
if( zIn ){
if( rbuIsVacuum(p) ){
assert( argc==2 || argc==1 );
if( argc==1 || 0==sqlite3_value_int(argv[1]) ){
sqlite3_result_text(pCtx, zIn, -1, SQLITE_STATIC);
}
}else{
if( strlen(zIn)>4 && memcmp("data", zIn, 4)==0 ){
int i;
for(i=4; zIn[i]>='0' && zIn[i]<='9'; i++);
if( zIn[i]=='_' && zIn[i+1] ){
sqlite3_result_text(pCtx, &zIn[i+1], -1, SQLITE_STATIC);
}
}
}
}
}
static int rbuObjIterFirst(sqlite3rbu *p, RbuObjIter *pIter){
int rc;
memset(pIter, 0, sizeof(RbuObjIter));
rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pTblIter, &p->zErrmsg,
sqlite3_mprintf(
"SELECT rbu_target_name(name, type='view') AS target, name "
"FROM sqlite_schema "
"WHERE type IN ('table', 'view') AND target IS NOT NULL "
" %s "
"ORDER BY name"
, rbuIsVacuum(p) ? "AND rootpage!=0 AND rootpage IS NOT NULL" : ""));
if( rc==SQLITE_OK ){
rc = prepareAndCollectError(p->dbMain, &pIter->pIdxIter, &p->zErrmsg,
"SELECT name, rootpage, sql IS NULL OR substr(8, 6)=='UNIQUE' "
" FROM main.sqlite_schema "
" WHERE type='index' AND tbl_name = ?"
);
}
pIter->bCleanup = 1;
p->rc = rc;
return rbuObjIterNext(p, pIter);
}
static char *rbuMPrintf(sqlite3rbu *p, const char *zFmt, ...){
char *zSql = 0;
va_list ap;
va_start(ap, zFmt);
zSql = sqlite3_vmprintf(zFmt, ap);
if( p->rc==SQLITE_OK ){
if( zSql==0 ) p->rc = SQLITE_NOMEM;
}else{
sqlite3_free(zSql);
zSql = 0;
}
va_end(ap);
return zSql;
}
static int rbuMPrintfExec(sqlite3rbu *p, sqlite3 *db, const char *zFmt, ...){
va_list ap;
char *zSql;
va_start(ap, zFmt);
zSql = sqlite3_vmprintf(zFmt, ap);
if( p->rc==SQLITE_OK ){
if( zSql==0 ){
p->rc = SQLITE_NOMEM;
}else{
p->rc = sqlite3_exec(db, zSql, 0, 0, &p->zErrmsg);
}
}
sqlite3_free(zSql);
va_end(ap);
return p->rc;
}
static void *rbuMalloc(sqlite3rbu *p, sqlite3_int64 nByte){
void *pRet = 0;
if( p->rc==SQLITE_OK ){
assert( nByte>0 );
pRet = sqlite3_malloc64(nByte);
if( pRet==0 ){
p->rc = SQLITE_NOMEM;
}else{
memset(pRet, 0, nByte);
}
}
return pRet;
}
static void rbuAllocateIterArrays(sqlite3rbu *p, RbuObjIter *pIter, int nCol){
sqlite3_int64 nByte = (2*sizeof(char*) + sizeof(int) + 3*sizeof(u8)) * nCol;
char **azNew;
azNew = (char**)rbuMalloc(p, nByte);
if( azNew ){
pIter->azTblCol = azNew;
pIter->azTblType = &azNew[nCol];
pIter->aiSrcOrder = (int*)&pIter->azTblType[nCol];
pIter->abTblPk = (u8*)&pIter->aiSrcOrder[nCol];
pIter->abNotNull = (u8*)&pIter->abTblPk[nCol];
pIter->abIndexed = (u8*)&pIter->abNotNull[nCol];
}
}
static char *rbuStrndup(const char *zStr, int *pRc){
char *zRet = 0;
if( *pRc==SQLITE_OK ){
if( zStr ){
size_t nCopy = strlen(zStr) + 1;
zRet = (char*)sqlite3_malloc64(nCopy);
if( zRet ){
memcpy(zRet, zStr, nCopy);
}else{
*pRc = SQLITE_NOMEM;
}
}
}
return zRet;
}
static void rbuFinalize(sqlite3rbu *p, sqlite3_stmt *pStmt){
sqlite3 *db = sqlite3_db_handle(pStmt);
int rc = sqlite3_finalize(pStmt);
if( p->rc==SQLITE_OK && rc!=SQLITE_OK ){
p->rc = rc;
p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
}
}
static void rbuTableType(
sqlite3rbu *p,
const char *zTab,
int *peType,
int *piTnum,
int *piPk
){
sqlite3_stmt *aStmt[4] = {0, 0, 0, 0};
*peType = RBU_PK_NOTABLE;
*piPk = 0;
assert( p->rc==SQLITE_OK );
p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[0], &p->zErrmsg,
sqlite3_mprintf(
"SELECT "
" (sql COLLATE nocase BETWEEN 'CREATE VIRTUAL' AND 'CREATE VIRTUAM'),"
" rootpage"
" FROM sqlite_schema"
" WHERE name=%Q", zTab
));
if( p->rc!=SQLITE_OK || sqlite3_step(aStmt[0])!=SQLITE_ROW ){
goto rbuTableType_end;
}
if( sqlite3_column_int(aStmt[0], 0) ){
*peType = RBU_PK_VTAB;
goto rbuTableType_end;
}
*piTnum = sqlite3_column_int(aStmt[0], 1);
p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[1], &p->zErrmsg,
sqlite3_mprintf("PRAGMA index_list=%Q",zTab)
);
if( p->rc ) goto rbuTableType_end;
while( sqlite3_step(aStmt[1])==SQLITE_ROW ){
const u8 *zOrig = sqlite3_column_text(aStmt[1], 3);
const u8 *zIdx = sqlite3_column_text(aStmt[1], 1);
if( zOrig && zIdx && zOrig[0]=='p' ){
p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[2], &p->zErrmsg,
sqlite3_mprintf(
"SELECT rootpage FROM sqlite_schema WHERE name = %Q", zIdx
));
if( p->rc==SQLITE_OK ){
if( sqlite3_step(aStmt[2])==SQLITE_ROW ){
*piPk = sqlite3_column_int(aStmt[2], 0);
*peType = RBU_PK_EXTERNAL;
}else{
*peType = RBU_PK_WITHOUT_ROWID;
}
}
goto rbuTableType_end;
}
}
p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[3], &p->zErrmsg,
sqlite3_mprintf("PRAGMA table_info=%Q",zTab)
);
if( p->rc==SQLITE_OK ){
while( sqlite3_step(aStmt[3])==SQLITE_ROW ){
if( sqlite3_column_int(aStmt[3],5)>0 ){
*peType = RBU_PK_IPK;
goto rbuTableType_end;
}
}
*peType = RBU_PK_NONE;
}
rbuTableType_end: {
unsigned int i;
for(i=0; i<sizeof(aStmt)/sizeof(aStmt[0]); i++){
rbuFinalize(p, aStmt[i]);
}
}
}
static void rbuObjIterCacheIndexedCols(sqlite3rbu *p, RbuObjIter *pIter){
sqlite3_stmt *pList = 0;
int bIndex = 0;
if( p->rc==SQLITE_OK ){
memcpy(pIter->abIndexed, pIter->abTblPk, sizeof(u8)*pIter->nTblCol);
p->rc = prepareFreeAndCollectError(p->dbMain, &pList, &p->zErrmsg,
sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
);
}
pIter->nIndex = 0;
while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pList) ){
const char *zIdx = (const char*)sqlite3_column_text(pList, 1);
int bPartial = sqlite3_column_int(pList, 4);
sqlite3_stmt *pXInfo = 0;
if( zIdx==0 ) break;
if( bPartial ){
memset(pIter->abIndexed, 0x01, sizeof(u8)*pIter->nTblCol);
}
p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
);
while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
int iCid = sqlite3_column_int(pXInfo, 1);
if( iCid>=0 ) pIter->abIndexed[iCid] = 1;
if( iCid==-2 ){
memset(pIter->abIndexed, 0x01, sizeof(u8)*pIter->nTblCol);
}
}
rbuFinalize(p, pXInfo);
bIndex = 1;
pIter->nIndex++;
}
if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
pIter->nIndex--;
}
rbuFinalize(p, pList);
if( bIndex==0 ) pIter->abIndexed = 0;
}
static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){
if( pIter->azTblCol==0 ){
sqlite3_stmt *pStmt = 0;
int nCol = 0;
int i;
int bRbuRowid = 0;
int iOrder = 0;
int iTnum = 0;
assert( pIter->eType==0 );
rbuTableType(p, pIter->zTbl, &pIter->eType, &iTnum, &pIter->iPkTnum);
if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_NOTABLE ){
p->rc = SQLITE_ERROR;
p->zErrmsg = sqlite3_mprintf("no such table: %s", pIter->zTbl);
}
if( p->rc ) return p->rc;
if( pIter->zIdx==0 ) pIter->iTnum = iTnum;
assert( pIter->eType==RBU_PK_NONE || pIter->eType==RBU_PK_IPK
|| pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_WITHOUT_ROWID
|| pIter->eType==RBU_PK_VTAB
);
p->rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
sqlite3_mprintf("SELECT * FROM '%q'", pIter->zDataTbl)
);
if( p->rc==SQLITE_OK ){
nCol = sqlite3_column_count(pStmt);
rbuAllocateIterArrays(p, pIter, nCol);
}
for(i=0; p->rc==SQLITE_OK && i<nCol; i++){
const char *zName = (const char*)sqlite3_column_name(pStmt, i);
if( sqlite3_strnicmp("rbu_", zName, 4) ){
char *zCopy = rbuStrndup(zName, &p->rc);
pIter->aiSrcOrder[pIter->nTblCol] = pIter->nTblCol;
pIter->azTblCol[pIter->nTblCol++] = zCopy;
}
else if( 0==sqlite3_stricmp("rbu_rowid", zName) ){
bRbuRowid = 1;
}
}
sqlite3_finalize(pStmt);
pStmt = 0;
if( p->rc==SQLITE_OK
&& rbuIsVacuum(p)==0
&& bRbuRowid!=(pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
){
p->rc = SQLITE_ERROR;
p->zErrmsg = sqlite3_mprintf(
"table %q %s rbu_rowid column", pIter->zDataTbl,
(bRbuRowid ? "may not have" : "requires")
);
}
if( p->rc==SQLITE_OK ){
p->rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
sqlite3_mprintf("PRAGMA table_info(%Q)", pIter->zTbl)
);
}
while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
if( zName==0 ) break;
for(i=iOrder; i<pIter->nTblCol; i++){
if( 0==strcmp(zName, pIter->azTblCol[i]) ) break;
}
if( i==pIter->nTblCol ){
p->rc = SQLITE_ERROR;
p->zErrmsg = sqlite3_mprintf("column missing from %q: %s",
pIter->zDataTbl, zName
);
}else{
int iPk = sqlite3_column_int(pStmt, 5);
int bNotNull = sqlite3_column_int(pStmt, 3);
const char *zType = (const char*)sqlite3_column_text(pStmt, 2);
if( i!=iOrder ){
SWAP(int, pIter->aiSrcOrder[i], pIter->aiSrcOrder[iOrder]);
SWAP(char*, pIter->azTblCol[i], pIter->azTblCol[iOrder]);
}
pIter->azTblType[iOrder] = rbuStrndup(zType, &p->rc);
assert( iPk>=0 );
pIter->abTblPk[iOrder] = (u8)iPk;
pIter->abNotNull[iOrder] = (u8)bNotNull || (iPk!=0);
iOrder++;
}
}
rbuFinalize(p, pStmt);
rbuObjIterCacheIndexedCols(p, pIter);
assert( pIter->eType!=RBU_PK_VTAB || pIter->abIndexed==0 );
assert( pIter->eType!=RBU_PK_VTAB || pIter->nIndex==0 );
}
return p->rc;
}
static char *rbuObjIterGetCollist(
sqlite3rbu *p,
RbuObjIter *pIter
){
char *zList = 0;
const char *zSep = "";
int i;
for(i=0; i<pIter->nTblCol; i++){
const char *z = pIter->azTblCol[i];
zList = rbuMPrintf(p, "%z%s\"%w\"", zList, zSep, z);
zSep = ", ";
}
return zList;
}
static char *rbuObjIterGetPkList(
sqlite3rbu *p,
RbuObjIter *pIter,
const char *zPre,
const char *zSeparator,
const char *zPost
){
int iPk = 1;
char *zRet = 0;
const char *zSep = "";
while( 1 ){
int i;
for(i=0; i<pIter->nTblCol; i++){
if( (int)pIter->abTblPk[i]==iPk ){
const char *zCol = pIter->azTblCol[i];
zRet = rbuMPrintf(p, "%z%s%s\"%w\"%s", zRet, zSep, zPre, zCol, zPost);
zSep = zSeparator;
break;
}
}
if( i==pIter->nTblCol ) break;
iPk++;
}
return zRet;
}
static char *rbuVacuumTableStart(
sqlite3rbu *p,
RbuObjIter *pIter,
int bRowid,
const char *zWrite
){
sqlite3_stmt *pMax = 0;
char *zRet = 0;
if( bRowid ){
p->rc = prepareFreeAndCollectError(p->dbMain, &pMax, &p->zErrmsg,
sqlite3_mprintf(
"SELECT max(_rowid_) FROM \"%s%w\"", zWrite, pIter->zTbl
)
);
if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){
sqlite3_int64 iMax = sqlite3_column_int64(pMax, 0);
zRet = rbuMPrintf(p, " WHERE _rowid_ > %lld ", iMax);
}
rbuFinalize(p, pMax);
}else{
char *zOrder = rbuObjIterGetPkList(p, pIter, "", ", ", " DESC");
char *zSelect = rbuObjIterGetPkList(p, pIter, "quote(", "||','||", ")");
char *zList = rbuObjIterGetPkList(p, pIter, "", ", ", "");
if( p->rc==SQLITE_OK ){
p->rc = prepareFreeAndCollectError(p->dbMain, &pMax, &p->zErrmsg,
sqlite3_mprintf(
"SELECT %s FROM \"%s%w\" ORDER BY %s LIMIT 1",
zSelect, zWrite, pIter->zTbl, zOrder
)
);
if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){
const char *zVal = (const char*)sqlite3_column_text(pMax, 0);
zRet = rbuMPrintf(p, " WHERE (%s) > (%s) ", zList, zVal);
}
rbuFinalize(p, pMax);
}
sqlite3_free(zOrder);
sqlite3_free(zSelect);
sqlite3_free(zList);
}
return zRet;
}
static char *rbuVacuumIndexStart(
sqlite3rbu *p,
RbuObjIter *pIter
){
char *zOrder = 0;
char *zLhs = 0;
char *zSelect = 0;
char *zVector = 0;
char *zRet = 0;
int bFailed = 0;
const char *zSep = "";
int iCol = 0;
sqlite3_stmt *pXInfo = 0;
p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter->zIdx)
);
while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
int iCid = sqlite3_column_int(pXInfo, 1);
const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
const char *zCol;
if( sqlite3_column_int(pXInfo, 3) ){
bFailed = 1;
break;
}
if( iCid<0 ){
if( pIter->eType==RBU_PK_IPK ){
int i;
for(i=0; pIter->abTblPk[i]==0; i++);
assert( i<pIter->nTblCol );
zCol = pIter->azTblCol[i];
}else{
zCol = "_rowid_";
}
}else{
zCol = pIter->azTblCol[iCid];
}
zLhs = rbuMPrintf(p, "%z%s \"%w\" COLLATE %Q",
zLhs, zSep, zCol, zCollate
);
zOrder = rbuMPrintf(p, "%z%s \"rbu_imp_%d%w\" COLLATE %Q DESC",
zOrder, zSep, iCol, zCol, zCollate
);
zSelect = rbuMPrintf(p, "%z%s quote(\"rbu_imp_%d%w\")",
zSelect, zSep, iCol, zCol
);
zSep = ", ";
iCol++;
}
rbuFinalize(p, pXInfo);
if( bFailed ) goto index_start_out;
if( p->rc==SQLITE_OK ){
sqlite3_stmt *pSel = 0;
p->rc = prepareFreeAndCollectError(p->dbMain, &pSel, &p->zErrmsg,
sqlite3_mprintf("SELECT %s FROM \"rbu_imp_%w\" ORDER BY %s LIMIT 1",
zSelect, pIter->zTbl, zOrder
)
);
if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSel) ){
zSep = "";
for(iCol=0; iCol<pIter->nCol; iCol++){
const char *zQuoted = (const char*)sqlite3_column_text(pSel, iCol);
if( zQuoted==0 ){
p->rc = SQLITE_NOMEM;
}else if( zQuoted[0]=='N' ){
bFailed = 1;
break;
}
zVector = rbuMPrintf(p, "%z%s%s", zVector, zSep, zQuoted);
zSep = ", ";
}
if( !bFailed ){
zRet = rbuMPrintf(p, "(%s) > (%s)", zLhs, zVector);
}
}
rbuFinalize(p, pSel);
}
index_start_out:
sqlite3_free(zOrder);
sqlite3_free(zSelect);
sqlite3_free(zVector);
sqlite3_free(zLhs);
return zRet;
}
static char *rbuObjIterGetIndexCols(
sqlite3rbu *p,
RbuObjIter *pIter,
char **pzImposterCols,
char **pzImposterPk,
char **pzWhere,
int *pnBind
){
int rc = p->rc;
int rc2;
char *zRet = 0;
char *zImpCols = 0;
char *zImpPK = 0;
char *zWhere = 0;
int nBind = 0;
const char *zCom = "";
const char *zAnd = "";
sqlite3_stmt *pXInfo = 0;
if( rc==SQLITE_OK ){
assert( p->zErrmsg==0 );
rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter->zIdx)
);
}
while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
int iCid = sqlite3_column_int(pXInfo, 1);
int bDesc = sqlite3_column_int(pXInfo, 3);
const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
const char *zCol = 0;
const char *zType;
if( iCid==-2 ){
int iSeq = sqlite3_column_int(pXInfo, 0);
zRet = sqlite3_mprintf("%z%s(%.*s) COLLATE %Q", zRet, zCom,
pIter->aIdxCol[iSeq].nSpan, pIter->aIdxCol[iSeq].zSpan, zCollate
);
zType = "";
}else {
if( iCid<0 ){
if( pIter->eType==RBU_PK_IPK ){
int i;
for(i=0; pIter->abTblPk[i]==0; i++);
assert( i<pIter->nTblCol );
zCol = pIter->azTblCol[i];
}else if( rbuIsVacuum(p) ){
zCol = "_rowid_";
}else{
zCol = "rbu_rowid";
}
zType = "INTEGER";
}else{
zCol = pIter->azTblCol[iCid];
zType = pIter->azTblType[iCid];
}
zRet = sqlite3_mprintf("%z%s\"%w\" COLLATE %Q", zRet, zCom,zCol,zCollate);
}
if( pIter->bUnique==0 || sqlite3_column_int(pXInfo, 5) ){
const char *zOrder = (bDesc ? " DESC" : "");
zImpPK = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\"%s",
zImpPK, zCom, nBind, zCol, zOrder
);
}
zImpCols = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\" %s COLLATE %Q",
zImpCols, zCom, nBind, zCol, zType, zCollate
);
zWhere = sqlite3_mprintf(
"%z%s\"rbu_imp_%d%w\" IS ?", zWhere, zAnd, nBind, zCol
);
if( zRet==0 || zImpPK==0 || zImpCols==0 || zWhere==0 ) rc = SQLITE_NOMEM;
zCom = ", ";
zAnd = " AND ";
nBind++;
}
rc2 = sqlite3_finalize(pXInfo);
if( rc==SQLITE_OK ) rc = rc2;
if( rc!=SQLITE_OK ){
sqlite3_free(zRet);
sqlite3_free(zImpCols);
sqlite3_free(zImpPK);
sqlite3_free(zWhere);
zRet = 0;
zImpCols = 0;
zImpPK = 0;
zWhere = 0;
p->rc = rc;
}
*pzImposterCols = zImpCols;
*pzImposterPk = zImpPK;
*pzWhere = zWhere;
*pnBind = nBind;
return zRet;
}
static char *rbuObjIterGetOldlist(
sqlite3rbu *p,
RbuObjIter *pIter,
const char *zObj
){
char *zList = 0;
if( p->rc==SQLITE_OK && pIter->abIndexed ){
const char *zS = "";
int i;
for(i=0; i<pIter->nTblCol; i++){
if( pIter->abIndexed[i] ){
const char *zCol = pIter->azTblCol[i];
zList = sqlite3_mprintf("%z%s%s.\"%w\"", zList, zS, zObj, zCol);
}else{
zList = sqlite3_mprintf("%z%sNULL", zList, zS);
}
zS = ", ";
if( zList==0 ){
p->rc = SQLITE_NOMEM;
break;
}
}
if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
zList = rbuMPrintf(p, "%z, %s._rowid_", zList, zObj);
}
}
return zList;
}
static char *rbuObjIterGetWhere(
sqlite3rbu *p,
RbuObjIter *pIter
){
char *zList = 0;
if( pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE ){
zList = rbuMPrintf(p, "_rowid_ = ?%d", pIter->nTblCol+1);
}else if( pIter->eType==RBU_PK_EXTERNAL ){
const char *zSep = "";
int i;
for(i=0; i<pIter->nTblCol; i++){
if( pIter->abTblPk[i] ){
zList = rbuMPrintf(p, "%z%sc%d=?%d", zList, zSep, i, i+1);
zSep = " AND ";
}
}
zList = rbuMPrintf(p,
"_rowid_ = (SELECT id FROM rbu_imposter2 WHERE %z)", zList
);
}else{
const char *zSep = "";
int i;
for(i=0; i<pIter->nTblCol; i++){
if( pIter->abTblPk[i] ){
const char *zCol = pIter->azTblCol[i];
zList = rbuMPrintf(p, "%z%s\"%w\"=?%d", zList, zSep, zCol, i+1);
zSep = " AND ";
}
}
}
return zList;
}
static void rbuBadControlError(sqlite3rbu *p){
p->rc = SQLITE_ERROR;
p->zErrmsg = sqlite3_mprintf("invalid rbu_control value");
}
static char *rbuObjIterGetSetlist(
sqlite3rbu *p,
RbuObjIter *pIter,
const char *zMask
){
char *zList = 0;
if( p->rc==SQLITE_OK ){
int i;
if( (int)strlen(zMask)!=pIter->nTblCol ){
rbuBadControlError(p);
}else{
const char *zSep = "";
for(i=0; i<pIter->nTblCol; i++){
char c = zMask[pIter->aiSrcOrder[i]];
if( c=='x' ){
zList = rbuMPrintf(p, "%z%s\"%w\"=?%d",
zList, zSep, pIter->azTblCol[i], i+1
);
zSep = ", ";
}
else if( c=='d' ){
zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_delta(\"%w\", ?%d)",
zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
);
zSep = ", ";
}
else if( c=='f' ){
zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_fossil_delta(\"%w\", ?%d)",
zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
);
zSep = ", ";
}
}
}
}
return zList;
}
static char *rbuObjIterGetBindlist(sqlite3rbu *p, int nBind){
char *zRet = 0;
sqlite3_int64 nByte = 2*(sqlite3_int64)nBind + 1;
zRet = (char*)rbuMalloc(p, nByte);
if( zRet ){
int i;
for(i=0; i<nBind; i++){
zRet[i*2] = '?';
zRet[i*2+1] = (i+1==nBind) ? '\0' : ',';
}
}
return zRet;
}
static char *rbuWithoutRowidPK(sqlite3rbu *p, RbuObjIter *pIter){
char *z = 0;
assert( pIter->zIdx==0 );
if( p->rc==SQLITE_OK ){
const char *zSep = "PRIMARY KEY(";
sqlite3_stmt *pXList = 0;
sqlite3_stmt *pXInfo = 0;
p->rc = prepareFreeAndCollectError(p->dbMain, &pXList, &p->zErrmsg,
sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
);
while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXList) ){
const char *zOrig = (const char*)sqlite3_column_text(pXList,3);
if( zOrig && strcmp(zOrig, "pk")==0 ){
const char *zIdx = (const char*)sqlite3_column_text(pXList,1);
if( zIdx ){
p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
);
}
break;
}
}
rbuFinalize(p, pXList);
while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
if( sqlite3_column_int(pXInfo, 5) ){
const char *zCol = (const char*)sqlite3_column_text(pXInfo, 2);
const char *zDesc = sqlite3_column_int(pXInfo, 3) ? " DESC" : "";
z = rbuMPrintf(p, "%z%s\"%w\"%s", z, zSep, zCol, zDesc);
zSep = ", ";
}
}
z = rbuMPrintf(p, "%z)", z);
rbuFinalize(p, pXInfo);
}
return z;
}
static void rbuCreateImposterTable2(sqlite3rbu *p, RbuObjIter *pIter){
if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_EXTERNAL ){
int tnum = pIter->iPkTnum;
sqlite3_stmt *pQuery = 0;
const char *zIdx = 0;
sqlite3_stmt *pXInfo = 0;
const char *zComma = "";
char *zCols = 0;
char *zPk = 0;
p->rc = prepareAndCollectError(p->dbMain, &pQuery, &p->zErrmsg,
"SELECT name FROM sqlite_schema WHERE rootpage = ?"
);
if( p->rc==SQLITE_OK ){
sqlite3_bind_int(pQuery, 1, tnum);
if( SQLITE_ROW==sqlite3_step(pQuery) ){
zIdx = (const char*)sqlite3_column_text(pQuery, 0);
}
}
if( zIdx ){
p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
);
}
rbuFinalize(p, pQuery);
while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
int bKey = sqlite3_column_int(pXInfo, 5);
if( bKey ){
int iCid = sqlite3_column_int(pXInfo, 1);
int bDesc = sqlite3_column_int(pXInfo, 3);
const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
zCols = rbuMPrintf(p, "%z%sc%d %s COLLATE %Q", zCols, zComma,
iCid, pIter->azTblType[iCid], zCollate
);
zPk = rbuMPrintf(p, "%z%sc%d%s", zPk, zComma, iCid, bDesc?" DESC":"");
zComma = ", ";
}
}
zCols = rbuMPrintf(p, "%z, id INTEGER", zCols);
rbuFinalize(p, pXInfo);
sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
rbuMPrintfExec(p, p->dbMain,
"CREATE TABLE rbu_imposter2(%z, PRIMARY KEY(%z)) WITHOUT ROWID",
zCols, zPk
);
sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
}
}
static void rbuCreateImposterTable(sqlite3rbu *p, RbuObjIter *pIter){
if( p->rc==SQLITE_OK && pIter->eType!=RBU_PK_VTAB ){
int tnum = pIter->iTnum;
const char *zComma = "";
char *zSql = 0;
int iCol;
sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
for(iCol=0; p->rc==SQLITE_OK && iCol<pIter->nTblCol; iCol++){
const char *zPk = "";
const char *zCol = pIter->azTblCol[iCol];
const char *zColl = 0;
p->rc = sqlite3_table_column_metadata(
p->dbMain, "main", pIter->zTbl, zCol, 0, &zColl, 0, 0, 0
);
if( pIter->eType==RBU_PK_IPK && pIter->abTblPk[iCol] ){
zPk = "PRIMARY KEY ";
}
zSql = rbuMPrintf(p, "%z%s\"%w\" %s %sCOLLATE %Q%s",
zSql, zComma, zCol, pIter->azTblType[iCol], zPk, zColl,
(pIter->abNotNull[iCol] ? " NOT NULL" : "")
);
zComma = ", ";
}
if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
char *zPk = rbuWithoutRowidPK(p, pIter);
if( zPk ){
zSql = rbuMPrintf(p, "%z, %z", zSql, zPk);
}
}
sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
rbuMPrintfExec(p, p->dbMain, "CREATE TABLE \"rbu_imp_%w\"(%z)%s",
pIter->zTbl, zSql,
(pIter->eType==RBU_PK_WITHOUT_ROWID ? " WITHOUT ROWID" : "")
);
sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
}
}
static void rbuObjIterPrepareTmpInsert(
sqlite3rbu *p,
RbuObjIter *pIter,
const char *zCollist,
const char *zRbuRowid
){
int bRbuRowid = (pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE);
char *zBind = rbuObjIterGetBindlist(p, pIter->nTblCol + 1 + bRbuRowid);
if( zBind ){
assert( pIter->pTmpInsert==0 );
p->rc = prepareFreeAndCollectError(
p->dbRbu, &pIter->pTmpInsert, &p->zErrmsg, sqlite3_mprintf(
"INSERT INTO %s.'rbu_tmp_%q'(rbu_control,%s%s) VALUES(%z)",
p->zStateDb, pIter->zDataTbl, zCollist, zRbuRowid, zBind
));
}
}
static void rbuTmpInsertFunc(
sqlite3_context *pCtx,
int nVal,
sqlite3_value **apVal
){
sqlite3rbu *p = sqlite3_user_data(pCtx);
int rc = SQLITE_OK;
int i;
assert( sqlite3_value_int(apVal[0])!=0
|| p->objiter.eType==RBU_PK_EXTERNAL
|| p->objiter.eType==RBU_PK_NONE
);
if( sqlite3_value_int(apVal[0])!=0 ){
p->nPhaseOneStep += p->objiter.nIndex;
}
for(i=0; rc==SQLITE_OK && i<nVal; i++){
rc = sqlite3_bind_value(p->objiter.pTmpInsert, i+1, apVal[i]);
}
if( rc==SQLITE_OK ){
sqlite3_step(p->objiter.pTmpInsert);
rc = sqlite3_reset(p->objiter.pTmpInsert);
}
if( rc!=SQLITE_OK ){
sqlite3_result_error_code(pCtx, rc);
}
}
static char *rbuObjIterGetIndexWhere(sqlite3rbu *p, RbuObjIter *pIter){
sqlite3_stmt *pStmt = 0;
int rc = p->rc;
char *zRet = 0;
assert( pIter->zIdxSql==0 && pIter->nIdxCol==0 && pIter->aIdxCol==0 );
if( rc==SQLITE_OK ){
rc = prepareAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
"SELECT trim(sql) FROM sqlite_schema WHERE type='index' AND name=?"
);
}
if( rc==SQLITE_OK ){
int rc2;
rc = sqlite3_bind_text(pStmt, 1, pIter->zIdx, -1, SQLITE_STATIC);
if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
char *zSql = (char*)sqlite3_column_text(pStmt, 0);
if( zSql ){
pIter->zIdxSql = zSql = rbuStrndup(zSql, &rc);
}
if( zSql ){
int nParen = 0;
int i;
int iIdxCol = 0;
int nIdxAlloc = 0;
for(i=0; zSql[i]; i++){
char c = zSql[i];
if( iIdxCol==nIdxAlloc ){
RbuSpan *aIdxCol = (RbuSpan*)sqlite3_realloc(
pIter->aIdxCol, (nIdxAlloc+16)*sizeof(RbuSpan)
);
if( aIdxCol==0 ){
rc = SQLITE_NOMEM;
break;
}
pIter->aIdxCol = aIdxCol;
nIdxAlloc += 16;
}
if( c=='(' ){
if( nParen==0 ){
assert( iIdxCol==0 );
pIter->aIdxCol[0].zSpan = &zSql[i+1];
}
nParen++;
}
else if( c==')' ){
nParen--;
if( nParen==0 ){
int nSpan = &zSql[i] - pIter->aIdxCol[iIdxCol].zSpan;
pIter->aIdxCol[iIdxCol++].nSpan = nSpan;
i++;
break;
}
}else if( c==',' && nParen==1 ){
int nSpan = &zSql[i] - pIter->aIdxCol[iIdxCol].zSpan;
pIter->aIdxCol[iIdxCol++].nSpan = nSpan;
pIter->aIdxCol[iIdxCol].zSpan = &zSql[i+1];
}else if( c=='"' || c=='\'' || c=='`' ){
for(i++; 1; i++){
if( zSql[i]==c ){
if( zSql[i+1]!=c ) break;
i++;
}
}
}else if( c=='[' ){
for(i++; 1; i++){
if( zSql[i]==']' ) break;
}
}else if( c=='-' && zSql[i+1]=='-' ){
for(i=i+2; zSql[i] && zSql[i]!='\n'; i++);
if( zSql[i]=='\0' ) break;
}else if( c=='/' && zSql[i+1]=='*' ){
for(i=i+2; zSql[i] && (zSql[i]!='*' || zSql[i+1]!='/'); i++);
if( zSql[i]=='\0' ) break;
i++;
}
}
if( zSql[i] ){
zRet = rbuStrndup(&zSql[i], &rc);
}
pIter->nIdxCol = iIdxCol;
}
}
rc2 = sqlite3_finalize(pStmt);
if( rc==SQLITE_OK ) rc = rc2;
}
p->rc = rc;
return zRet;
}
static int rbuObjIterPrepareAll(
sqlite3rbu *p,
RbuObjIter *pIter,
int nOffset
){
assert( pIter->bCleanup==0 );
if( pIter->pSelect==0 && rbuObjIterCacheTableInfo(p, pIter)==SQLITE_OK ){
const int tnum = pIter->iTnum;
char *zCollist = 0;
char **pz = &p->zErrmsg;
const char *zIdx = pIter->zIdx;
char *zLimit = 0;
if( nOffset ){
zLimit = sqlite3_mprintf(" LIMIT -1 OFFSET %d", nOffset);
if( !zLimit ) p->rc = SQLITE_NOMEM;
}
if( zIdx ){
const char *zTbl = pIter->zTbl;
char *zImposterCols = 0;
char *zImposterPK = 0;
char *zWhere = 0;
char *zBind = 0;
char *zPart = 0;
int nBind = 0;
assert( pIter->eType!=RBU_PK_VTAB );
zPart = rbuObjIterGetIndexWhere(p, pIter);
zCollist = rbuObjIterGetIndexCols(
p, pIter, &zImposterCols, &zImposterPK, &zWhere, &nBind
);
zBind = rbuObjIterGetBindlist(p, nBind);
sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1,tnum);
rbuMPrintfExec(p, p->dbMain,
"CREATE TABLE \"rbu_imp_%w\"( %s, PRIMARY KEY( %s ) ) WITHOUT ROWID",
zTbl, zImposterCols, zImposterPK
);
sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
pIter->nCol = nBind;
if( p->rc==SQLITE_OK ){
p->rc = prepareFreeAndCollectError(
p->dbMain, &pIter->pInsert, &p->zErrmsg,
sqlite3_mprintf("INSERT INTO \"rbu_imp_%w\" VALUES(%s)", zTbl, zBind)
);
}
if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
p->rc = prepareFreeAndCollectError(
p->dbMain, &pIter->pDelete, &p->zErrmsg,
sqlite3_mprintf("DELETE FROM \"rbu_imp_%w\" WHERE %s", zTbl, zWhere)
);
}
if( p->rc==SQLITE_OK ){
char *zSql;
if( rbuIsVacuum(p) ){
char *zStart = 0;
if( nOffset ){
zStart = rbuVacuumIndexStart(p, pIter);
if( zStart ){
sqlite3_free(zLimit);
zLimit = 0;
}
}
zSql = sqlite3_mprintf(
"SELECT %s, 0 AS rbu_control FROM '%q' %s %s %s ORDER BY %s%s",
zCollist,
pIter->zDataTbl,
zPart,
(zStart ? (zPart ? "AND" : "WHERE") : ""), zStart,
zCollist, zLimit
);
sqlite3_free(zStart);
}else
if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
zSql = sqlite3_mprintf(
"SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' %s ORDER BY %s%s",
zCollist, p->zStateDb, pIter->zDataTbl,
zPart, zCollist, zLimit
);
}else{
zSql = sqlite3_mprintf(
"SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' %s "
"UNION ALL "
"SELECT %s, rbu_control FROM '%q' "
"%s %s typeof(rbu_control)='integer' AND rbu_control!=1 "
"ORDER BY %s%s",
zCollist, p->zStateDb, pIter->zDataTbl, zPart,
zCollist, pIter->zDataTbl,
zPart,
(zPart ? "AND" : "WHERE"),
zCollist, zLimit
);
}
if( p->rc==SQLITE_OK ){
p->rc = prepareFreeAndCollectError(p->dbRbu,&pIter->pSelect,pz,zSql);
}else{
sqlite3_free(zSql);
}
}
sqlite3_free(zImposterCols);
sqlite3_free(zImposterPK);
sqlite3_free(zWhere);
sqlite3_free(zBind);
sqlite3_free(zPart);
}else{
int bRbuRowid = (pIter->eType==RBU_PK_VTAB)
||(pIter->eType==RBU_PK_NONE)
||(pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p));
const char *zTbl = pIter->zTbl;
const char *zWrite;
char *zBindings = rbuObjIterGetBindlist(p, pIter->nTblCol + bRbuRowid);
char *zWhere = rbuObjIterGetWhere(p, pIter);
char *zOldlist = rbuObjIterGetOldlist(p, pIter, "old");
char *zNewlist = rbuObjIterGetOldlist(p, pIter, "new");
zCollist = rbuObjIterGetCollist(p, pIter);
pIter->nCol = pIter->nTblCol;
rbuCreateImposterTable(p, pIter);
rbuCreateImposterTable2(p, pIter);
zWrite = (pIter->eType==RBU_PK_VTAB ? "" : "rbu_imp_");
if( p->rc==SQLITE_OK ){
p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pInsert, pz,
sqlite3_mprintf(
"INSERT INTO \"%s%w\"(%s%s) VALUES(%s)",
zWrite, zTbl, zCollist, (bRbuRowid ? ", _rowid_" : ""), zBindings
)
);
}
if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pDelete, pz,
sqlite3_mprintf(
"DELETE FROM \"%s%w\" WHERE %s", zWrite, zTbl, zWhere
)
);
}
if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
const char *zRbuRowid = "";
if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
zRbuRowid = ", rbu_rowid";
}
rbuMPrintfExec(p, p->dbRbu,
"CREATE TABLE IF NOT EXISTS %s.'rbu_tmp_%q' AS "
"SELECT *%s FROM '%q' WHERE 0;"
, p->zStateDb, pIter->zDataTbl
, (pIter->eType==RBU_PK_EXTERNAL ? ", 0 AS rbu_rowid" : "")
, pIter->zDataTbl
);
rbuMPrintfExec(p, p->dbMain,
"CREATE TEMP TRIGGER rbu_delete_tr BEFORE DELETE ON \"%s%w\" "
"BEGIN "
" SELECT rbu_tmp_insert(3, %s);"
"END;"
"CREATE TEMP TRIGGER rbu_update1_tr BEFORE UPDATE ON \"%s%w\" "
"BEGIN "
" SELECT rbu_tmp_insert(3, %s);"
"END;"
"CREATE TEMP TRIGGER rbu_update2_tr AFTER UPDATE ON \"%s%w\" "
"BEGIN "
" SELECT rbu_tmp_insert(4, %s);"
"END;",
zWrite, zTbl, zOldlist,
zWrite, zTbl, zOldlist,
zWrite, zTbl, zNewlist
);
if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
rbuMPrintfExec(p, p->dbMain,
"CREATE TEMP TRIGGER rbu_insert_tr AFTER INSERT ON \"%s%w\" "
"BEGIN "
" SELECT rbu_tmp_insert(0, %s);"
"END;",
zWrite, zTbl, zNewlist
);
}
rbuObjIterPrepareTmpInsert(p, pIter, zCollist, zRbuRowid);
}
if( p->rc==SQLITE_OK ){
const char *zRbuRowid = "";
char *zStart = 0;
char *zOrder = 0;
if( bRbuRowid ){
zRbuRowid = rbuIsVacuum(p) ? ",_rowid_ " : ",rbu_rowid";
}
if( rbuIsVacuum(p) ){
if( nOffset ){
zStart = rbuVacuumTableStart(p, pIter, bRbuRowid, zWrite);
if( zStart ){
sqlite3_free(zLimit);
zLimit = 0;
}
}
if( bRbuRowid ){
zOrder = rbuMPrintf(p, "_rowid_");
}else{
zOrder = rbuObjIterGetPkList(p, pIter, "", ", ", "");
}
}
if( p->rc==SQLITE_OK ){
p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz,
sqlite3_mprintf(
"SELECT %s,%s rbu_control%s FROM '%q'%s %s %s %s",
zCollist,
(rbuIsVacuum(p) ? "0 AS " : ""),
zRbuRowid,
pIter->zDataTbl, (zStart ? zStart : ""),
(zOrder ? "ORDER BY" : ""), zOrder,
zLimit
)
);
}
sqlite3_free(zStart);
sqlite3_free(zOrder);
}
sqlite3_free(zWhere);
sqlite3_free(zOldlist);
sqlite3_free(zNewlist);
sqlite3_free(zBindings);
}
sqlite3_free(zCollist);
sqlite3_free(zLimit);
}
return p->rc;
}
static int rbuGetUpdateStmt(
sqlite3rbu *p,
RbuObjIter *pIter,
const char *zMask,
sqlite3_stmt **ppStmt
){
RbuUpdateStmt **pp;
RbuUpdateStmt *pUp = 0;
int nUp = 0;
*ppStmt = 0;
for(pp=&pIter->pRbuUpdate; *pp; pp=&((*pp)->pNext)){
pUp = *pp;
if( strcmp(pUp->zMask, zMask)==0 ){
*pp = pUp->pNext;
pUp->pNext = pIter->pRbuUpdate;
pIter->pRbuUpdate = pUp;
*ppStmt = pUp->pUpdate;
return SQLITE_OK;
}
nUp++;
}
assert( pUp==0 || pUp->pNext==0 );
if( nUp>=SQLITE_RBU_UPDATE_CACHESIZE ){
for(pp=&pIter->pRbuUpdate; *pp!=pUp; pp=&((*pp)->pNext));
*pp = 0;
sqlite3_finalize(pUp->pUpdate);
pUp->pUpdate = 0;
}else{
pUp = (RbuUpdateStmt*)rbuMalloc(p, sizeof(RbuUpdateStmt)+pIter->nTblCol+1);
}
if( pUp ){
char *zWhere = rbuObjIterGetWhere(p, pIter);
char *zSet = rbuObjIterGetSetlist(p, pIter, zMask);
char *zUpdate = 0;
pUp->zMask = (char*)&pUp[1];
memcpy(pUp->zMask, zMask, pIter->nTblCol);
pUp->pNext = pIter->pRbuUpdate;
pIter->pRbuUpdate = pUp;
if( zSet ){
const char *zPrefix = "";
if( pIter->eType!=RBU_PK_VTAB ) zPrefix = "rbu_imp_";
zUpdate = sqlite3_mprintf("UPDATE \"%s%w\" SET %s WHERE %s",
zPrefix, pIter->zTbl, zSet, zWhere
);
p->rc = prepareFreeAndCollectError(
p->dbMain, &pUp->pUpdate, &p->zErrmsg, zUpdate
);
*ppStmt = pUp->pUpdate;
}
sqlite3_free(zWhere);
sqlite3_free(zSet);
}
return p->rc;
}
static sqlite3 *rbuOpenDbhandle(
sqlite3rbu *p,
const char *zName,
int bUseVfs
){
sqlite3 *db = 0;
if( p->rc==SQLITE_OK ){
const int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_URI;
p->rc = sqlite3_open_v2(zName, &db, flags, bUseVfs ? p->zVfsName : 0);
if( p->rc ){
p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
sqlite3_close(db);
db = 0;
}
}
return db;
}
static void rbuFreeState(RbuState *p){
if( p ){
sqlite3_free(p->zTbl);
sqlite3_free(p->zDataTbl);
sqlite3_free(p->zIdx);
sqlite3_free(p);
}
}
static RbuState *rbuLoadState(sqlite3rbu *p){
RbuState *pRet = 0;
sqlite3_stmt *pStmt = 0;
int rc;
int rc2;
pRet = (RbuState*)rbuMalloc(p, sizeof(RbuState));
if( pRet==0 ) return 0;
rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
sqlite3_mprintf("SELECT k, v FROM %s.rbu_state", p->zStateDb)
);
while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
switch( sqlite3_column_int(pStmt, 0) ){
case RBU_STATE_STAGE:
pRet->eStage = sqlite3_column_int(pStmt, 1);
if( pRet->eStage!=RBU_STAGE_OAL
&& pRet->eStage!=RBU_STAGE_MOVE
&& pRet->eStage!=RBU_STAGE_CKPT
){
p->rc = SQLITE_CORRUPT;
}
break;
case RBU_STATE_TBL:
pRet->zTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
break;
case RBU_STATE_IDX:
pRet->zIdx = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
break;
case RBU_STATE_ROW:
pRet->nRow = sqlite3_column_int(pStmt, 1);
break;
case RBU_STATE_PROGRESS:
pRet->nProgress = sqlite3_column_int64(pStmt, 1);
break;
case RBU_STATE_CKPT:
pRet->iWalCksum = sqlite3_column_int64(pStmt, 1);
break;
case RBU_STATE_COOKIE:
pRet->iCookie = (u32)sqlite3_column_int64(pStmt, 1);
break;
case RBU_STATE_OALSZ:
pRet->iOalSz = sqlite3_column_int64(pStmt, 1);
break;
case RBU_STATE_PHASEONESTEP:
pRet->nPhaseOneStep = sqlite3_column_int64(pStmt, 1);
break;
case RBU_STATE_DATATBL:
pRet->zDataTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
break;
default:
rc = SQLITE_CORRUPT;
break;
}
}
rc2 = sqlite3_finalize(pStmt);
if( rc==SQLITE_OK ) rc = rc2;
p->rc = rc;
return pRet;
}
static void rbuOpenDatabase(sqlite3rbu *p, sqlite3 *dbMain, int *pbRetry){
assert( p->rc || (p->dbMain==0 && p->dbRbu==0) );
assert( p->rc || rbuIsVacuum(p) || p->zTarget!=0 );
assert( dbMain==0 || rbuIsVacuum(p)==0 );
p->dbRbu = rbuOpenDbhandle(p, p->zRbu, 1);
p->dbMain = dbMain;
if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
if( p->zState==0 ){
const char *zFile = sqlite3_db_filename(p->dbRbu, "main");
p->zState = rbuMPrintf(p, "file:///%s-vacuum?modeof=%s", zFile, zFile);
}
}
if( p->zState ){
rbuMPrintfExec(p, p->dbRbu, "ATTACH %Q AS stat", p->zState);
memcpy(p->zStateDb, "stat", 4);
}else{
memcpy(p->zStateDb, "main", 4);
}
#if 0#endif
rbuMPrintfExec(p, p->dbRbu, RBU_CREATE_STATE, p->zStateDb);
#if 0#endif
if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
int bOpen = 0;
int rc;
p->nRbu = 0;
p->pRbuFd = 0;
rc = sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
if( rc!=SQLITE_NOTFOUND ) p->rc = rc;
if( p->eStage>=RBU_STAGE_MOVE ){
bOpen = 1;
}else{
RbuState *pState = rbuLoadState(p);
if( pState ){
bOpen = (pState->eStage>=RBU_STAGE_MOVE);
rbuFreeState(pState);
}
}
if( bOpen ) p->dbMain = rbuOpenDbhandle(p, p->zRbu, p->nRbu<=1);
}
p->eStage = 0;
if( p->rc==SQLITE_OK && p->dbMain==0 ){
if( !rbuIsVacuum(p) ){
p->dbMain = rbuOpenDbhandle(p, p->zTarget, 1);
}else if( p->pRbuFd->pWalFd ){
if( pbRetry ){
p->pRbuFd->bNolock = 0;
sqlite3_close(p->dbRbu);
sqlite3_close(p->dbMain);
p->dbMain = 0;
p->dbRbu = 0;
*pbRetry = 1;
return;
}
p->rc = SQLITE_ERROR;
p->zErrmsg = sqlite3_mprintf("cannot vacuum wal mode database");
}else{
char *zTarget;
char *zExtra = 0;
if( strlen(p->zRbu)>=5 && 0==memcmp("file:", p->zRbu, 5) ){
zExtra = &p->zRbu[5];
while( *zExtra ){
if( *zExtra++=='?' ) break;
}
if( *zExtra=='\0' ) zExtra = 0;
}
zTarget = sqlite3_mprintf("file:%s-vactmp?rbu_memory=1%s%s",
sqlite3_db_filename(p->dbRbu, "main"),
(zExtra==0 ? "" : "&"), (zExtra==0 ? "" : zExtra)
);
if( zTarget==0 ){
p->rc = SQLITE_NOMEM;
return;
}
p->dbMain = rbuOpenDbhandle(p, zTarget, p->nRbu<=1);
sqlite3_free(zTarget);
}
}
if( p->rc==SQLITE_OK ){
p->rc = sqlite3_create_function(p->dbMain,
"rbu_tmp_insert", -1, SQLITE_UTF8, (void*)p, rbuTmpInsertFunc, 0, 0
);
}
if( p->rc==SQLITE_OK ){
p->rc = sqlite3_create_function(p->dbMain,
"rbu_fossil_delta", 2, SQLITE_UTF8, 0, rbuFossilDeltaFunc, 0, 0
);
}
if( p->rc==SQLITE_OK ){
p->rc = sqlite3_create_function(p->dbRbu,
"rbu_target_name", -1, SQLITE_UTF8, (void*)p, rbuTargetNameFunc, 0, 0
);
}
if( p->rc==SQLITE_OK ){
p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
}
rbuMPrintfExec(p, p->dbMain, "SELECT * FROM sqlite_schema");
if( p->rc==SQLITE_OK ){
p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
}
if( p->rc==SQLITE_NOTFOUND ){
p->rc = SQLITE_ERROR;
p->zErrmsg = sqlite3_mprintf("rbu vfs not found");
}
}
static void rbuFileSuffix3(const char *zBase, char *z){
#ifdef SQLITE_ENABLE_8_3_NAMES
#if SQLITE_ENABLE_8_3_NAMES<2
if( sqlite3_uri_boolean(zBase, "8_3_names", 0) )
#endif
{
int i, sz;
sz = (int)strlen(z)&0xffffff;
for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
if( z[i]=='.' && sz>i+4 ) memmove(&z[i+1], &z[sz-3], 4);
}
#endif
}
static i64 rbuShmChecksum(sqlite3rbu *p){
i64 iRet = 0;
if( p->rc==SQLITE_OK ){
sqlite3_file *pDb = p->pTargetFd->pReal;
u32 volatile *ptr;
p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, (void volatile**)&ptr);
if( p->rc==SQLITE_OK ){
iRet = ((i64)ptr[10] << 32) + ptr[11];
}
}
return iRet;
}
static void rbuSetupCheckpoint(sqlite3rbu *p, RbuState *pState){
if( pState==0 ){
p->eStage = 0;
if( p->rc==SQLITE_OK ){
p->rc = sqlite3_exec(p->dbMain, "SELECT * FROM sqlite_schema", 0, 0, 0);
}
}
if( p->rc==SQLITE_OK ){
int rc2;
p->eStage = RBU_STAGE_CAPTURE;
rc2 = sqlite3_exec(p->dbMain, "PRAGMA main.wal_checkpoint=restart", 0, 0,0);
if( rc2!=SQLITE_NOTICE ) p->rc = rc2;
}
if( p->rc==SQLITE_OK && p->nFrame>0 ){
p->eStage = RBU_STAGE_CKPT;
p->nStep = (pState ? pState->nRow : 0);
p->aBuf = rbuMalloc(p, p->pgsz);
p->iWalCksum = rbuShmChecksum(p);
}
if( p->rc==SQLITE_OK ){
if( p->nFrame==0 || (pState && pState->iWalCksum!=p->iWalCksum) ){
p->rc = SQLITE_DONE;
p->eStage = RBU_STAGE_DONE;
}else{
int nSectorSize;
sqlite3_file *pDb = p->pTargetFd->pReal;
sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
assert( p->nPagePerSector==0 );
nSectorSize = pDb->pMethods->xSectorSize(pDb);
if( nSectorSize>p->pgsz ){
p->nPagePerSector = nSectorSize / p->pgsz;
}else{
p->nPagePerSector = 1;
}
p->rc = pWal->pMethods->xSync(pWal, SQLITE_SYNC_NORMAL);
}
}
}
static int rbuCaptureWalRead(sqlite3rbu *pRbu, i64 iOff, int iAmt){
const u32 mReq = (1<<WAL_LOCK_WRITE)|(1<<WAL_LOCK_CKPT)|(1<<WAL_LOCK_READ0);
u32 iFrame;
if( pRbu->mLock!=mReq ){
pRbu->rc = SQLITE_BUSY;
return SQLITE_NOTICE_RBU;
}
pRbu->pgsz = iAmt;
if( pRbu->nFrame==pRbu->nFrameAlloc ){
int nNew = (pRbu->nFrameAlloc ? pRbu->nFrameAlloc : 64) * 2;
RbuFrame *aNew;
aNew = (RbuFrame*)sqlite3_realloc64(pRbu->aFrame, nNew * sizeof(RbuFrame));
if( aNew==0 ) return SQLITE_NOMEM;
pRbu->aFrame = aNew;
pRbu->nFrameAlloc = nNew;
}
iFrame = (u32)((iOff-32) / (i64)(iAmt+24)) + 1;
if( pRbu->iMaxFrame<iFrame ) pRbu->iMaxFrame = iFrame;
pRbu->aFrame[pRbu->nFrame].iWalFrame = iFrame;
pRbu->aFrame[pRbu->nFrame].iDbPage = 0;
pRbu->nFrame++;
return SQLITE_OK;
}
static int rbuCaptureDbWrite(sqlite3rbu *pRbu, i64 iOff){
pRbu->aFrame[pRbu->nFrame-1].iDbPage = (u32)(iOff / pRbu->pgsz) + 1;
return SQLITE_OK;
}
static void rbuCheckpointFrame(sqlite3rbu *p, RbuFrame *pFrame){
sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
sqlite3_file *pDb = p->pTargetFd->pReal;
i64 iOff;
assert( p->rc==SQLITE_OK );
iOff = (i64)(pFrame->iWalFrame-1) * (p->pgsz + 24) + 32 + 24;
p->rc = pWal->pMethods->xRead(pWal, p->aBuf, p->pgsz, iOff);
if( p->rc ) return;
iOff = (i64)(pFrame->iDbPage-1) * p->pgsz;
p->rc = pDb->pMethods->xWrite(pDb, p->aBuf, p->pgsz, iOff);
}
#define RBU_ZIPVFS_CTRL_FILE_POINTER 230439
static int rbuLockDatabase(sqlite3 *db){
int rc = SQLITE_OK;
sqlite3_file *fd = 0;
sqlite3_file_control(db, "main", RBU_ZIPVFS_CTRL_FILE_POINTER, &fd);
if( fd ){
sqlite3_file_control(db, "main", SQLITE_FCNTL_FILE_POINTER, &fd);
rc = fd->pMethods->xLock(fd, SQLITE_LOCK_SHARED);
if( rc==SQLITE_OK ){
rc = fd->pMethods->xUnlock(fd, SQLITE_LOCK_NONE);
}
sqlite3_file_control(db, "main", RBU_ZIPVFS_CTRL_FILE_POINTER, &fd);
}else{
sqlite3_file_control(db, "main", SQLITE_FCNTL_FILE_POINTER, &fd);
}
if( rc==SQLITE_OK && fd->pMethods ){
rc = fd->pMethods->xLock(fd, SQLITE_LOCK_SHARED);
if( rc==SQLITE_OK ){
rc = fd->pMethods->xLock(fd, SQLITE_LOCK_EXCLUSIVE);
}
}
return rc;
}
static int rbuExclusiveCheckpoint(sqlite3 *db){
const char *zUri = sqlite3_db_filename(db, 0);
return sqlite3_uri_boolean(zUri, RBU_EXCLUSIVE_CHECKPOINT, 0);
}
#if defined(_WIN32_WCE)
static LPWSTR rbuWinUtf8ToUnicode(const char *zFilename){
int nChar;
LPWSTR zWideFilename;
nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
if( nChar==0 ){
return 0;
}
zWideFilename = sqlite3_malloc64( nChar*sizeof(zWideFilename[0]) );
if( zWideFilename==0 ){
return 0;
}
memset(zWideFilename, 0, nChar*sizeof(zWideFilename[0]));
nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
nChar);
if( nChar==0 ){
sqlite3_free(zWideFilename);
zWideFilename = 0;
}
return zWideFilename;
}
#endif
static void rbuMoveOalFile(sqlite3rbu *p){
const char *zBase = sqlite3_db_filename(p->dbMain, "main");
const char *zMove = zBase;
char *zOal;
char *zWal;
if( rbuIsVacuum(p) ){
zMove = sqlite3_db_filename(p->dbRbu, "main");
}
zOal = sqlite3_mprintf("%s-oal", zMove);
zWal = sqlite3_mprintf("%s-wal", zMove);
assert( p->eStage==RBU_STAGE_MOVE );
assert( p->rc==SQLITE_OK && p->zErrmsg==0 );
if( zWal==0 || zOal==0 ){
p->rc = SQLITE_NOMEM;
}else{
sqlite3 *dbMain = 0;
rbuFileSuffix3(zBase, zWal);
rbuFileSuffix3(zBase, zOal);
rbuObjIterFinalize(&p->objiter);
sqlite3_close(p->dbRbu);
sqlite3_close(p->dbMain);
p->dbMain = 0;
p->dbRbu = 0;
dbMain = rbuOpenDbhandle(p, p->zTarget, 1);
if( dbMain ){
assert( p->rc==SQLITE_OK );
p->rc = rbuLockDatabase(dbMain);
}
if( p->rc==SQLITE_OK ){
p->rc = p->xRename(p->pRenameArg, zOal, zWal);
}
if( p->rc!=SQLITE_OK
|| rbuIsVacuum(p)
|| rbuExclusiveCheckpoint(dbMain)==0
){
sqlite3_close(dbMain);
dbMain = 0;
}
if( p->rc==SQLITE_OK ){
rbuOpenDatabase(p, dbMain, 0);
rbuSetupCheckpoint(p, 0);
}
}
sqlite3_free(zWal);
sqlite3_free(zOal);
}
static int rbuStepType(sqlite3rbu *p, const char **pzMask){
int iCol = p->objiter.nCol;
int res = 0;
switch( sqlite3_column_type(p->objiter.pSelect, iCol) ){
case SQLITE_INTEGER: {
int iVal = sqlite3_column_int(p->objiter.pSelect, iCol);
switch( iVal ){
case 0: res = RBU_INSERT; break;
case 1: res = RBU_DELETE; break;
case 2: res = RBU_REPLACE; break;
case 3: res = RBU_IDX_DELETE; break;
case 4: res = RBU_IDX_INSERT; break;
}
break;
}
case SQLITE_TEXT: {
const unsigned char *z = sqlite3_column_text(p->objiter.pSelect, iCol);
if( z==0 ){
p->rc = SQLITE_NOMEM;
}else{
*pzMask = (const char*)z;
}
res = RBU_UPDATE;
break;
}
default:
break;
}
if( res==0 ){
rbuBadControlError(p);
}
return res;
}
#ifdef SQLITE_DEBUG
static void assertColumnName(sqlite3_stmt *pStmt, int iCol, const char *zName){
const char *zCol = sqlite3_column_name(pStmt, iCol);
assert( 0==sqlite3_stricmp(zName, zCol) );
}
#else
# define assertColumnName(x,y,z)
#endif
static void rbuStepOneOp(sqlite3rbu *p, int eType){
RbuObjIter *pIter = &p->objiter;
sqlite3_value *pVal;
sqlite3_stmt *pWriter;
int i;
assert( p->rc==SQLITE_OK );
assert( eType!=RBU_DELETE || pIter->zIdx==0 );
assert( eType==RBU_DELETE || eType==RBU_IDX_DELETE
|| eType==RBU_INSERT || eType==RBU_IDX_INSERT
);
if( eType==RBU_DELETE ){
p->nPhaseOneStep -= p->objiter.nIndex;
}
if( eType==RBU_IDX_DELETE || eType==RBU_DELETE ){
pWriter = pIter->pDelete;
}else{
pWriter = pIter->pInsert;
}
for(i=0; i<pIter->nCol; i++){
if( eType==RBU_INSERT
&& pIter->zIdx==0 && pIter->eType==RBU_PK_IPK && pIter->abTblPk[i]
&& sqlite3_column_type(pIter->pSelect, i)==SQLITE_NULL
){
p->rc = SQLITE_MISMATCH;
p->zErrmsg = sqlite3_mprintf("datatype mismatch");
return;
}
if( eType==RBU_DELETE && pIter->abTblPk[i]==0 ){
continue;
}
pVal = sqlite3_column_value(pIter->pSelect, i);
p->rc = sqlite3_bind_value(pWriter, i+1, pVal);
if( p->rc ) return;
}
if( pIter->zIdx==0 ){
if( pIter->eType==RBU_PK_VTAB
|| pIter->eType==RBU_PK_NONE
|| (pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p))
){
assertColumnName(pIter->pSelect, pIter->nCol+1,
rbuIsVacuum(p) ? "rowid" : "rbu_rowid"
);
pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
p->rc = sqlite3_bind_value(pWriter, pIter->nCol+1, pVal);
}
}
if( p->rc==SQLITE_OK ){
sqlite3_step(pWriter);
p->rc = resetAndCollectError(pWriter, &p->zErrmsg);
}
}
static int rbuStep(sqlite3rbu *p){
RbuObjIter *pIter = &p->objiter;
const char *zMask = 0;
int eType = rbuStepType(p, &zMask);
if( eType ){
assert( eType==RBU_INSERT || eType==RBU_DELETE
|| eType==RBU_REPLACE || eType==RBU_IDX_DELETE
|| eType==RBU_IDX_INSERT || eType==RBU_UPDATE
);
assert( eType!=RBU_UPDATE || pIter->zIdx==0 );
if( pIter->zIdx==0 && (eType==RBU_IDX_DELETE || eType==RBU_IDX_INSERT) ){
rbuBadControlError(p);
}
else if( eType==RBU_REPLACE ){
if( pIter->zIdx==0 ){
p->nPhaseOneStep += p->objiter.nIndex;
rbuStepOneOp(p, RBU_DELETE);
}
if( p->rc==SQLITE_OK ) rbuStepOneOp(p, RBU_INSERT);
}
else if( eType!=RBU_UPDATE ){
rbuStepOneOp(p, eType);
}
else{
sqlite3_value *pVal;
sqlite3_stmt *pUpdate = 0;
assert( eType==RBU_UPDATE );
p->nPhaseOneStep -= p->objiter.nIndex;
rbuGetUpdateStmt(p, pIter, zMask, &pUpdate);
if( pUpdate ){
int i;
for(i=0; p->rc==SQLITE_OK && i<pIter->nCol; i++){
char c = zMask[pIter->aiSrcOrder[i]];
pVal = sqlite3_column_value(pIter->pSelect, i);
if( pIter->abTblPk[i] || c!='.' ){
p->rc = sqlite3_bind_value(pUpdate, i+1, pVal);
}
}
if( p->rc==SQLITE_OK
&& (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
){
assertColumnName(pIter->pSelect, pIter->nCol+1, "rbu_rowid");
pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
p->rc = sqlite3_bind_value(pUpdate, pIter->nCol+1, pVal);
}
if( p->rc==SQLITE_OK ){
sqlite3_step(pUpdate);
p->rc = resetAndCollectError(pUpdate, &p->zErrmsg);
}
}
}
}
return p->rc;
}
static void rbuIncrSchemaCookie(sqlite3rbu *p){
if( p->rc==SQLITE_OK ){
sqlite3 *dbread = (rbuIsVacuum(p) ? p->dbRbu : p->dbMain);
int iCookie = 1000000;
sqlite3_stmt *pStmt;
p->rc = prepareAndCollectError(dbread, &pStmt, &p->zErrmsg,
"PRAGMA schema_version"
);
if( p->rc==SQLITE_OK ){
if( SQLITE_ROW==sqlite3_step(pStmt) ){
iCookie = sqlite3_column_int(pStmt, 0);
}
rbuFinalize(p, pStmt);
}
if( p->rc==SQLITE_OK ){
rbuMPrintfExec(p, p->dbMain, "PRAGMA schema_version = %d", iCookie+1);
}
}
}
static void rbuSaveState(sqlite3rbu *p, int eStage){
if( p->rc==SQLITE_OK || p->rc==SQLITE_DONE ){
sqlite3_stmt *pInsert = 0;
rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
int rc;
assert( p->zErrmsg==0 );
rc = prepareFreeAndCollectError(p->dbRbu, &pInsert, &p->zErrmsg,
sqlite3_mprintf(
"INSERT OR REPLACE INTO %s.rbu_state(k, v) VALUES "
"(%d, %d), "
"(%d, %Q), "
"(%d, %Q), "
"(%d, %d), "
"(%d, %d), "
"(%d, %lld), "
"(%d, %lld), "
"(%d, %lld), "
"(%d, %lld), "
"(%d, %Q) ",
p->zStateDb,
RBU_STATE_STAGE, eStage,
RBU_STATE_TBL, p->objiter.zTbl,
RBU_STATE_IDX, p->objiter.zIdx,
RBU_STATE_ROW, p->nStep,
RBU_STATE_PROGRESS, p->nProgress,
RBU_STATE_CKPT, p->iWalCksum,
RBU_STATE_COOKIE, (i64)pFd->iCookie,
RBU_STATE_OALSZ, p->iOalSz,
RBU_STATE_PHASEONESTEP, p->nPhaseOneStep,
RBU_STATE_DATATBL, p->objiter.zDataTbl
)
);
assert( pInsert==0 || rc==SQLITE_OK );
if( rc==SQLITE_OK ){
sqlite3_step(pInsert);
rc = sqlite3_finalize(pInsert);
}
if( rc!=SQLITE_OK ) p->rc = rc;
}
}
static void rbuCopyPragma(sqlite3rbu *p, const char *zPragma){
if( p->rc==SQLITE_OK ){
sqlite3_stmt *pPragma = 0;
p->rc = prepareFreeAndCollectError(p->dbRbu, &pPragma, &p->zErrmsg,
sqlite3_mprintf("PRAGMA main.%s", zPragma)
);
if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPragma) ){
p->rc = rbuMPrintfExec(p, p->dbMain, "PRAGMA main.%s = %d",
zPragma, sqlite3_column_int(pPragma, 0)
);
}
rbuFinalize(p, pPragma);
}
}
static void rbuCreateTargetSchema(sqlite3rbu *p){
sqlite3_stmt *pSql = 0;
sqlite3_stmt *pInsert = 0;
assert( rbuIsVacuum(p) );
p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=1", 0,0, &p->zErrmsg);
if( p->rc==SQLITE_OK ){
p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
"SELECT sql FROM sqlite_schema WHERE sql!='' AND rootpage!=0"
" AND name!='sqlite_sequence' "
" ORDER BY type DESC"
);
}
while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
p->rc = sqlite3_exec(p->dbMain, zSql, 0, 0, &p->zErrmsg);
}
rbuFinalize(p, pSql);
if( p->rc!=SQLITE_OK ) return;
if( p->rc==SQLITE_OK ){
p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
"SELECT * FROM sqlite_schema WHERE rootpage=0 OR rootpage IS NULL"
);
}
if( p->rc==SQLITE_OK ){
p->rc = prepareAndCollectError(p->dbMain, &pInsert, &p->zErrmsg,
"INSERT INTO sqlite_schema VALUES(?,?,?,?,?)"
);
}
while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
int i;
for(i=0; i<5; i++){
sqlite3_bind_value(pInsert, i+1, sqlite3_column_value(pSql, i));
}
sqlite3_step(pInsert);
p->rc = sqlite3_reset(pInsert);
}
if( p->rc==SQLITE_OK ){
p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=0",0,0,&p->zErrmsg);
}
rbuFinalize(p, pSql);
rbuFinalize(p, pInsert);
}
int sqlite3rbu_step(sqlite3rbu *p){
if( p ){
switch( p->eStage ){
case RBU_STAGE_OAL: {
RbuObjIter *pIter = &p->objiter;
if( rbuIsVacuum(p) && p->nProgress==0 && p->rc==SQLITE_OK ){
rbuCreateTargetSchema(p);
rbuCopyPragma(p, "user_version");
rbuCopyPragma(p, "application_id");
}
while( p->rc==SQLITE_OK && pIter->zTbl ){
if( pIter->bCleanup ){
if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
rbuMPrintfExec(p, p->dbRbu,
"DELETE FROM %s.'rbu_tmp_%q'", p->zStateDb, pIter->zDataTbl
);
}
}else{
rbuObjIterPrepareAll(p, pIter, 0);
if( p->rc==SQLITE_OK ){
int rc = sqlite3_step(pIter->pSelect);
if( rc==SQLITE_ROW ){
p->nProgress++;
p->nStep++;
return rbuStep(p);
}
p->rc = sqlite3_reset(pIter->pSelect);
p->nStep = 0;
}
}
rbuObjIterNext(p, pIter);
}
if( p->rc==SQLITE_OK ){
assert( pIter->zTbl==0 );
rbuSaveState(p, RBU_STAGE_MOVE);
rbuIncrSchemaCookie(p);
if( p->rc==SQLITE_OK ){
p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
}
if( p->rc==SQLITE_OK ){
p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
}
p->eStage = RBU_STAGE_MOVE;
}
break;
}
case RBU_STAGE_MOVE: {
if( p->rc==SQLITE_OK ){
rbuMoveOalFile(p);
p->nProgress++;
}
break;
}
case RBU_STAGE_CKPT: {
if( p->rc==SQLITE_OK ){
if( p->nStep>=p->nFrame ){
sqlite3_file *pDb = p->pTargetFd->pReal;
p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
if( p->rc==SQLITE_OK ){
void volatile *ptr;
p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, &ptr);
if( p->rc==SQLITE_OK ){
((u32 volatile*)ptr)[24] = p->iMaxFrame;
}
}
if( p->rc==SQLITE_OK ){
p->eStage = RBU_STAGE_DONE;
p->rc = SQLITE_DONE;
}
}else{
u32 iSector;
do{
RbuFrame *pFrame = &p->aFrame[p->nStep];
iSector = (pFrame->iDbPage-1) / p->nPagePerSector;
rbuCheckpointFrame(p, pFrame);
p->nStep++;
}while( p->nStep<p->nFrame
&& iSector==((p->aFrame[p->nStep].iDbPage-1) / p->nPagePerSector)
&& p->rc==SQLITE_OK
);
}
p->nProgress++;
}
break;
}
default:
break;
}
return p->rc;
}else{
return SQLITE_NOMEM;
}
}
static int rbuStrCompare(const char *z1, const char *z2){
if( z1==0 && z2==0 ) return 0;
if( z1==0 || z2==0 ) return 1;
return (sqlite3_stricmp(z1, z2)!=0);
}
static void rbuSetupOal(sqlite3rbu *p, RbuState *pState){
assert( p->rc==SQLITE_OK );
if( pState->zTbl ){
RbuObjIter *pIter = &p->objiter;
int rc = SQLITE_OK;
while( rc==SQLITE_OK && pIter->zTbl && (pIter->bCleanup
|| rbuStrCompare(pIter->zIdx, pState->zIdx)
|| (pState->zDataTbl==0 && rbuStrCompare(pIter->zTbl, pState->zTbl))
|| (pState->zDataTbl && rbuStrCompare(pIter->zDataTbl, pState->zDataTbl))
)){
rc = rbuObjIterNext(p, pIter);
}
if( rc==SQLITE_OK && !pIter->zTbl ){
rc = SQLITE_ERROR;
p->zErrmsg = sqlite3_mprintf("rbu_state mismatch error");
}
if( rc==SQLITE_OK ){
p->nStep = pState->nRow;
rc = rbuObjIterPrepareAll(p, &p->objiter, p->nStep);
}
p->rc = rc;
}
}
static void rbuDeleteOalFile(sqlite3rbu *p){
char *zOal = rbuMPrintf(p, "%s-oal", p->zTarget);
if( zOal ){
sqlite3_vfs *pVfs = 0;
sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_VFS_POINTER, &pVfs);
assert( pVfs && p->rc==SQLITE_OK && p->zErrmsg==0 );
pVfs->xDelete(pVfs, zOal, 0);
sqlite3_free(zOal);
}
}
static void rbuCreateVfs(sqlite3rbu *p){
int rnd;
char zRnd[64];
assert( p->rc==SQLITE_OK );
sqlite3_randomness(sizeof(int), (void*)&rnd);
sqlite3_snprintf(sizeof(zRnd), zRnd, "rbu_vfs_%d", rnd);
p->rc = sqlite3rbu_create_vfs(zRnd, 0);
if( p->rc==SQLITE_OK ){
sqlite3_vfs *pVfs = sqlite3_vfs_find(zRnd);
assert( pVfs );
p->zVfsName = pVfs->zName;
((rbu_vfs*)pVfs)->pRbu = p;
}
}
static void rbuDeleteVfs(sqlite3rbu *p){
if( p->zVfsName ){
sqlite3rbu_destroy_vfs(p->zVfsName);
p->zVfsName = 0;
}
}
static void rbuIndexCntFunc(
sqlite3_context *pCtx,
int nVal,
sqlite3_value **apVal
){
sqlite3rbu *p = (sqlite3rbu*)sqlite3_user_data(pCtx);
sqlite3_stmt *pStmt = 0;
char *zErrmsg = 0;
int rc;
sqlite3 *db = (rbuIsVacuum(p) ? p->dbRbu : p->dbMain);
assert( nVal==1 );
rc = prepareFreeAndCollectError(db, &pStmt, &zErrmsg,
sqlite3_mprintf("SELECT count(*) FROM sqlite_schema "
"WHERE type='index' AND tbl_name = %Q", sqlite3_value_text(apVal[0]))
);
if( rc!=SQLITE_OK ){
sqlite3_result_error(pCtx, zErrmsg, -1);
}else{
int nIndex = 0;
if( SQLITE_ROW==sqlite3_step(pStmt) ){
nIndex = sqlite3_column_int(pStmt, 0);
}
rc = sqlite3_finalize(pStmt);
if( rc==SQLITE_OK ){
sqlite3_result_int(pCtx, nIndex);
}else{
sqlite3_result_error(pCtx, sqlite3_errmsg(db), -1);
}
}
sqlite3_free(zErrmsg);
}
static void rbuInitPhaseOneSteps(sqlite3rbu *p){
if( p->rc==SQLITE_OK ){
sqlite3_stmt *pStmt = 0;
int bExists = 0;
p->nPhaseOneStep = -1;
p->rc = sqlite3_create_function(p->dbRbu,
"rbu_index_cnt", 1, SQLITE_UTF8, (void*)p, rbuIndexCntFunc, 0, 0
);
if( p->rc==SQLITE_OK ){
p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
"SELECT 1 FROM sqlite_schema WHERE tbl_name = 'rbu_count'"
);
}
if( p->rc==SQLITE_OK ){
if( SQLITE_ROW==sqlite3_step(pStmt) ){
bExists = 1;
}
p->rc = sqlite3_finalize(pStmt);
}
if( p->rc==SQLITE_OK && bExists ){
p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
"SELECT sum(cnt * (1 + rbu_index_cnt(rbu_target_name(tbl))))"
"FROM rbu_count"
);
if( p->rc==SQLITE_OK ){
if( SQLITE_ROW==sqlite3_step(pStmt) ){
p->nPhaseOneStep = sqlite3_column_int64(pStmt, 0);
}
p->rc = sqlite3_finalize(pStmt);
}
}
}
}
static sqlite3rbu *openRbuHandle(
const char *zTarget,
const char *zRbu,
const char *zState
){
sqlite3rbu *p;
size_t nTarget = zTarget ? strlen(zTarget) : 0;
size_t nRbu = strlen(zRbu);
size_t nByte = sizeof(sqlite3rbu) + nTarget+1 + nRbu+1;
p = (sqlite3rbu*)sqlite3_malloc64(nByte);
if( p ){
RbuState *pState = 0;
memset(p, 0, sizeof(sqlite3rbu));
sqlite3rbu_rename_handler(p, 0, 0);
rbuCreateVfs(p);
if( p->rc==SQLITE_OK ){
char *pCsr = (char*)&p[1];
int bRetry = 0;
if( zTarget ){
p->zTarget = pCsr;
memcpy(p->zTarget, zTarget, nTarget+1);
pCsr += nTarget+1;
}
p->zRbu = pCsr;
memcpy(p->zRbu, zRbu, nRbu+1);
pCsr += nRbu+1;
if( zState ){
p->zState = rbuMPrintf(p, "%s", zState);
}
rbuOpenDatabase(p, 0, &bRetry);
if( bRetry ){
rbuOpenDatabase(p, 0, 0);
}
}
if( p->rc==SQLITE_OK ){
pState = rbuLoadState(p);
assert( pState || p->rc!=SQLITE_OK );
if( p->rc==SQLITE_OK ){
if( pState->eStage==0 ){
rbuDeleteOalFile(p);
rbuInitPhaseOneSteps(p);
p->eStage = RBU_STAGE_OAL;
}else{
p->eStage = pState->eStage;
p->nPhaseOneStep = pState->nPhaseOneStep;
}
p->nProgress = pState->nProgress;
p->iOalSz = pState->iOalSz;
}
}
assert( p->rc!=SQLITE_OK || p->eStage!=0 );
if( p->rc==SQLITE_OK && p->pTargetFd->pWalFd ){
if( p->eStage==RBU_STAGE_OAL ){
p->rc = SQLITE_ERROR;
p->zErrmsg = sqlite3_mprintf("cannot update wal mode database");
}else if( p->eStage==RBU_STAGE_MOVE ){
p->eStage = RBU_STAGE_CKPT;
p->nStep = 0;
}
}
if( p->rc==SQLITE_OK
&& (p->eStage==RBU_STAGE_OAL || p->eStage==RBU_STAGE_MOVE)
&& pState->eStage!=0
){
rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
if( pFd->iCookie!=pState->iCookie ){
p->rc = SQLITE_BUSY;
p->zErrmsg = sqlite3_mprintf("database modified during rbu %s",
(rbuIsVacuum(p) ? "vacuum" : "update")
);
}
}
if( p->rc==SQLITE_OK ){
if( p->eStage==RBU_STAGE_OAL ){
sqlite3 *db = p->dbMain;
p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, &p->zErrmsg);
if( p->rc==SQLITE_OK ){
p->rc = rbuObjIterFirst(p, &p->objiter);
}
if( p->rc==SQLITE_OK && p->objiter.zTbl==0 ){
p->rc = SQLITE_DONE;
p->eStage = RBU_STAGE_DONE;
}else{
if( p->rc==SQLITE_OK && pState->eStage==0 && rbuIsVacuum(p) ){
rbuCopyPragma(p, "page_size");
rbuCopyPragma(p, "auto_vacuum");
}
if( p->rc==SQLITE_OK ){
p->rc = sqlite3_exec(db, "BEGIN IMMEDIATE", 0, 0, &p->zErrmsg);
}
if( p->rc==SQLITE_OK ){
int frc = sqlite3_file_control(db, "main", SQLITE_FCNTL_ZIPVFS, 0);
if( frc==SQLITE_OK ){
p->rc = sqlite3_exec(
db, "PRAGMA journal_mode=off",0,0,&p->zErrmsg);
}
}
if( p->rc==SQLITE_OK ){
rbuSetupOal(p, pState);
}
}
}else if( p->eStage==RBU_STAGE_MOVE ){
}else if( p->eStage==RBU_STAGE_CKPT ){
if( !rbuIsVacuum(p) && rbuExclusiveCheckpoint(p->dbMain) ){
p->eStage = RBU_STAGE_DONE;
rbuLockDatabase(p->dbMain);
p->eStage = RBU_STAGE_CKPT;
}
rbuSetupCheckpoint(p, pState);
}else if( p->eStage==RBU_STAGE_DONE ){
p->rc = SQLITE_DONE;
}else{
p->rc = SQLITE_CORRUPT;
}
}
rbuFreeState(pState);
}
return p;
}
static sqlite3rbu *rbuMisuseError(void){
sqlite3rbu *pRet;
pRet = sqlite3_malloc64(sizeof(sqlite3rbu));
if( pRet ){
memset(pRet, 0, sizeof(sqlite3rbu));
pRet->rc = SQLITE_MISUSE;
}
return pRet;
}
sqlite3rbu *sqlite3rbu_open(
const char *zTarget,
const char *zRbu,
const char *zState
){
if( zTarget==0 || zRbu==0 ){ return rbuMisuseError(); }
return openRbuHandle(zTarget, zRbu, zState);
}
sqlite3rbu *sqlite3rbu_vacuum(
const char *zTarget,
const char *zState
){
if( zTarget==0 ){ return rbuMisuseError(); }
if( zState ){
int n = strlen(zState);
if( n>=7 && 0==memcmp("-vactmp", &zState[n-7], 7) ){
return rbuMisuseError();
}
}
return openRbuHandle(0, zTarget, zState);
}
sqlite3 *sqlite3rbu_db(sqlite3rbu *pRbu, int bRbu){
sqlite3 *db = 0;
if( pRbu ){
db = (bRbu ? pRbu->dbRbu : pRbu->dbMain);
}
return db;
}
static void rbuEditErrmsg(sqlite3rbu *p){
if( p->rc==SQLITE_CONSTRAINT && p->zErrmsg ){
unsigned int i;
size_t nErrmsg = strlen(p->zErrmsg);
for(i=0; i<(nErrmsg-8); i++){
if( memcmp(&p->zErrmsg[i], "rbu_imp_", 8)==0 ){
int nDel = 8;
while( p->zErrmsg[i+nDel]>='0' && p->zErrmsg[i+nDel]<='9' ) nDel++;
memmove(&p->zErrmsg[i], &p->zErrmsg[i+nDel], nErrmsg + 1 - i - nDel);
nErrmsg -= nDel;
}
}
}
}
int sqlite3rbu_close(sqlite3rbu *p, char **pzErrmsg){
int rc;
if( p ){
if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
}
if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_CKPT ){
sqlite3_file *pDb = p->pTargetFd->pReal;
p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
}
rbuSaveState(p, p->eStage);
if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
}
rbuObjIterFinalize(&p->objiter);
if( rbuIsVacuum(p) && p->rc!=SQLITE_OK && p->dbRbu ){
int rc2 = sqlite3_exec(p->dbRbu, "DELETE FROM stat.rbu_state", 0, 0, 0);
if( p->rc==SQLITE_DONE && rc2!=SQLITE_OK ) p->rc = rc2;
}
sqlite3_close(p->dbRbu);
sqlite3_close(p->dbMain);
assert( p->szTemp==0 );
rbuDeleteVfs(p);
sqlite3_free(p->aBuf);
sqlite3_free(p->aFrame);
rbuEditErrmsg(p);
rc = p->rc;
if( pzErrmsg ){
*pzErrmsg = p->zErrmsg;
}else{
sqlite3_free(p->zErrmsg);
}
sqlite3_free(p->zState);
sqlite3_free(p);
}else{
rc = SQLITE_NOMEM;
*pzErrmsg = 0;
}
return rc;
}
sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu){
return pRbu->nProgress;
}
void sqlite3rbu_bp_progress(sqlite3rbu *p, int *pnOne, int *pnTwo){
const int MAX_PROGRESS = 10000;
switch( p->eStage ){
case RBU_STAGE_OAL:
if( p->nPhaseOneStep>0 ){
*pnOne = (int)(MAX_PROGRESS * (i64)p->nProgress/(i64)p->nPhaseOneStep);
}else{
*pnOne = -1;
}
*pnTwo = 0;
break;
case RBU_STAGE_MOVE:
*pnOne = MAX_PROGRESS;
*pnTwo = 0;
break;
case RBU_STAGE_CKPT:
*pnOne = MAX_PROGRESS;
*pnTwo = (int)(MAX_PROGRESS * (i64)p->nStep / (i64)p->nFrame);
break;
case RBU_STAGE_DONE:
*pnOne = MAX_PROGRESS;
*pnTwo = MAX_PROGRESS;
break;
default:
assert( 0 );
}
}
int sqlite3rbu_state(sqlite3rbu *p){
int aRes[] = {
0, SQLITE_RBU_STATE_OAL, SQLITE_RBU_STATE_MOVE,
0, SQLITE_RBU_STATE_CHECKPOINT, SQLITE_RBU_STATE_DONE
};
assert( RBU_STAGE_OAL==1 );
assert( RBU_STAGE_MOVE==2 );
assert( RBU_STAGE_CKPT==4 );
assert( RBU_STAGE_DONE==5 );
assert( aRes[RBU_STAGE_OAL]==SQLITE_RBU_STATE_OAL );
assert( aRes[RBU_STAGE_MOVE]==SQLITE_RBU_STATE_MOVE );
assert( aRes[RBU_STAGE_CKPT]==SQLITE_RBU_STATE_CHECKPOINT );
assert( aRes[RBU_STAGE_DONE]==SQLITE_RBU_STATE_DONE );
if( p->rc!=SQLITE_OK && p->rc!=SQLITE_DONE ){
return SQLITE_RBU_STATE_ERROR;
}else{
assert( p->rc!=SQLITE_DONE || p->eStage==RBU_STAGE_DONE );
assert( p->eStage==RBU_STAGE_OAL
|| p->eStage==RBU_STAGE_MOVE
|| p->eStage==RBU_STAGE_CKPT
|| p->eStage==RBU_STAGE_DONE
);
return aRes[p->eStage];
}
}
int sqlite3rbu_savestate(sqlite3rbu *p){
int rc = p->rc;
if( rc==SQLITE_DONE ) return SQLITE_OK;
assert( p->eStage>=RBU_STAGE_OAL && p->eStage<=RBU_STAGE_DONE );
if( p->eStage==RBU_STAGE_OAL ){
assert( rc!=SQLITE_DONE );
if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, 0);
}
if( rc==SQLITE_OK && p->eStage==RBU_STAGE_CKPT ){
sqlite3_file *pDb = p->pTargetFd->pReal;
rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
}
p->rc = rc;
rbuSaveState(p, p->eStage);
rc = p->rc;
if( p->eStage==RBU_STAGE_OAL ){
assert( rc!=SQLITE_DONE );
if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
if( rc==SQLITE_OK ){
const char *zBegin = rbuIsVacuum(p) ? "BEGIN" : "BEGIN IMMEDIATE";
rc = sqlite3_exec(p->dbRbu, zBegin, 0, 0, 0);
}
if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "BEGIN IMMEDIATE", 0, 0,0);
}
p->rc = rc;
return rc;
}
static int xDefaultRename(void *pArg, const char *zOld, const char *zNew){
int rc = SQLITE_OK;
#if defined(_WIN32_WCE)
{
LPWSTR zWideOld;
LPWSTR zWideNew;
zWideOld = rbuWinUtf8ToUnicode(zOld);
if( zWideOld ){
zWideNew = rbuWinUtf8ToUnicode(zNew);
if( zWideNew ){
if( MoveFileW(zWideOld, zWideNew) ){
rc = SQLITE_OK;
}else{
rc = SQLITE_IOERR;
}
sqlite3_free(zWideNew);
}else{
rc = SQLITE_IOERR_NOMEM;
}
sqlite3_free(zWideOld);
}else{
rc = SQLITE_IOERR_NOMEM;
}
}
#else
rc = rename(zOld, zNew) ? SQLITE_IOERR : SQLITE_OK;
#endif
return rc;
}
void sqlite3rbu_rename_handler(
sqlite3rbu *pRbu,
void *pArg,
int (*xRename)(void *pArg, const char *zOld, const char *zNew)
){
if( xRename ){
pRbu->xRename = xRename;
pRbu->pRenameArg = pArg;
}else{
pRbu->xRename = xDefaultRename;
pRbu->pRenameArg = 0;
}
}
static void rbuUnlockShm(rbu_file *p){
assert( p->openFlags & SQLITE_OPEN_MAIN_DB );
if( p->pRbu ){
int (*xShmLock)(sqlite3_file*,int,int,int) = p->pReal->pMethods->xShmLock;
int i;
for(i=0; i<SQLITE_SHM_NLOCK;i++){
if( (1<<i) & p->pRbu->mLock ){
xShmLock(p->pReal, i, 1, SQLITE_SHM_UNLOCK|SQLITE_SHM_EXCLUSIVE);
}
}
p->pRbu->mLock = 0;
}
}
static int rbuUpdateTempSize(rbu_file *pFd, sqlite3_int64 nNew){
sqlite3rbu *pRbu = pFd->pRbu;
i64 nDiff = nNew - pFd->sz;
pRbu->szTemp += nDiff;
pFd->sz = nNew;
assert( pRbu->szTemp>=0 );
if( pRbu->szTempLimit && pRbu->szTemp>pRbu->szTempLimit ) return SQLITE_FULL;
return SQLITE_OK;
}
static void rbuMainlistAdd(rbu_file *p){
rbu_vfs *pRbuVfs = p->pRbuVfs;
rbu_file *pIter;
assert( (p->openFlags & SQLITE_OPEN_MAIN_DB) );
sqlite3_mutex_enter(pRbuVfs->mutex);
if( p->pRbu==0 ){
for(pIter=pRbuVfs->pMain; pIter; pIter=pIter->pMainNext);
p->pMainNext = pRbuVfs->pMain;
pRbuVfs->pMain = p;
}else{
for(pIter=pRbuVfs->pMainRbu; pIter && pIter!=p; pIter=pIter->pMainRbuNext){}
if( pIter==0 ){
p->pMainRbuNext = pRbuVfs->pMainRbu;
pRbuVfs->pMainRbu = p;
}
}
sqlite3_mutex_leave(pRbuVfs->mutex);
}
static void rbuMainlistRemove(rbu_file *p){
rbu_file **pp;
sqlite3_mutex_enter(p->pRbuVfs->mutex);
for(pp=&p->pRbuVfs->pMain; *pp && *pp!=p; pp=&((*pp)->pMainNext)){}
if( *pp ) *pp = p->pMainNext;
p->pMainNext = 0;
for(pp=&p->pRbuVfs->pMainRbu; *pp && *pp!=p; pp=&((*pp)->pMainRbuNext)){}
if( *pp ) *pp = p->pMainRbuNext;
p->pMainRbuNext = 0;
sqlite3_mutex_leave(p->pRbuVfs->mutex);
}
static rbu_file *rbuFindMaindb(rbu_vfs *pRbuVfs, const char *zWal, int bRbu){
rbu_file *pDb;
sqlite3_mutex_enter(pRbuVfs->mutex);
if( bRbu ){
for(pDb=pRbuVfs->pMainRbu; pDb && pDb->zWal!=zWal; pDb=pDb->pMainRbuNext){}
}else{
for(pDb=pRbuVfs->pMain; pDb && pDb->zWal!=zWal; pDb=pDb->pMainNext){}
}
sqlite3_mutex_leave(pRbuVfs->mutex);
return pDb;
}
static int rbuVfsClose(sqlite3_file *pFile){
rbu_file *p = (rbu_file*)pFile;
int rc;
int i;
for(i=0; i<p->nShm; i++){
sqlite3_free(p->apShm[i]);
}
sqlite3_free(p->apShm);
p->apShm = 0;
sqlite3_free(p->zDel);
if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
const sqlite3_io_methods *pMeth = p->pReal->pMethods;
rbuMainlistRemove(p);
rbuUnlockShm(p);
if( pMeth->iVersion>1 && pMeth->xShmUnmap ){
pMeth->xShmUnmap(p->pReal, 0);
}
}
else if( (p->openFlags & SQLITE_OPEN_DELETEONCLOSE) && p->pRbu ){
rbuUpdateTempSize(p, 0);
}
assert( p->pMainNext==0 && p->pRbuVfs->pMain!=p );
rc = p->pReal->pMethods->xClose(p->pReal);
return rc;
}
static u32 rbuGetU32(u8 *aBuf){
return ((u32)aBuf[0] << 24)
+ ((u32)aBuf[1] << 16)
+ ((u32)aBuf[2] << 8)
+ ((u32)aBuf[3]);
}
static void rbuPutU32(u8 *aBuf, u32 iVal){
aBuf[0] = (iVal >> 24) & 0xFF;
aBuf[1] = (iVal >> 16) & 0xFF;
aBuf[2] = (iVal >> 8) & 0xFF;
aBuf[3] = (iVal >> 0) & 0xFF;
}
static void rbuPutU16(u8 *aBuf, u16 iVal){
aBuf[0] = (iVal >> 8) & 0xFF;
aBuf[1] = (iVal >> 0) & 0xFF;
}
static int rbuVfsRead(
sqlite3_file *pFile,
void *zBuf,
int iAmt,
sqlite_int64 iOfst
){
rbu_file *p = (rbu_file*)pFile;
sqlite3rbu *pRbu = p->pRbu;
int rc;
if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
assert( p->openFlags & SQLITE_OPEN_WAL );
rc = rbuCaptureWalRead(p->pRbu, iOfst, iAmt);
}else{
if( pRbu && pRbu->eStage==RBU_STAGE_OAL
&& (p->openFlags & SQLITE_OPEN_WAL)
&& iOfst>=pRbu->iOalSz
){
rc = SQLITE_OK;
memset(zBuf, 0, iAmt);
}else{
rc = p->pReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst);
#if 1
if( pRbu && rbuIsVacuum(pRbu)
&& rc==SQLITE_IOERR_SHORT_READ && iOfst==0
&& (p->openFlags & SQLITE_OPEN_MAIN_DB)
&& pRbu->rc==SQLITE_OK
){
sqlite3_file *pFd = (sqlite3_file*)pRbu->pRbuFd;
rc = pFd->pMethods->xRead(pFd, zBuf, iAmt, iOfst);
if( rc==SQLITE_OK ){
u8 *aBuf = (u8*)zBuf;
u32 iRoot = rbuGetU32(&aBuf[52]) ? 1 : 0;
rbuPutU32(&aBuf[52], iRoot);
rbuPutU32(&aBuf[36], 0);
rbuPutU32(&aBuf[32], 0);
rbuPutU32(&aBuf[28], 1);
rbuPutU32(&aBuf[24], pRbu->pRbuFd->iCookie+1);
if( iAmt>100 ){
memset(&aBuf[100], 0, iAmt-100);
rbuPutU16(&aBuf[105], iAmt & 0xFFFF);
aBuf[100] = 0x0D;
}
}
}
#endif
}
if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
u8 *pBuf = (u8*)zBuf;
p->iCookie = rbuGetU32(&pBuf[24]);
p->iWriteVer = pBuf[19];
}
}
return rc;
}
static int rbuVfsWrite(
sqlite3_file *pFile,
const void *zBuf,
int iAmt,
sqlite_int64 iOfst
){
rbu_file *p = (rbu_file*)pFile;
sqlite3rbu *pRbu = p->pRbu;
int rc;
if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
assert( p->openFlags & SQLITE_OPEN_MAIN_DB );
rc = rbuCaptureDbWrite(p->pRbu, iOfst);
}else{
if( pRbu ){
if( pRbu->eStage==RBU_STAGE_OAL
&& (p->openFlags & SQLITE_OPEN_WAL)
&& iOfst>=pRbu->iOalSz
){
pRbu->iOalSz = iAmt + iOfst;
}else if( p->openFlags & SQLITE_OPEN_DELETEONCLOSE ){
i64 szNew = iAmt+iOfst;
if( szNew>p->sz ){
rc = rbuUpdateTempSize(p, szNew);
if( rc!=SQLITE_OK ) return rc;
}
}
}
rc = p->pReal->pMethods->xWrite(p->pReal, zBuf, iAmt, iOfst);
if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
u8 *pBuf = (u8*)zBuf;
p->iCookie = rbuGetU32(&pBuf[24]);
p->iWriteVer = pBuf[19];
}
}
return rc;
}
static int rbuVfsTruncate(sqlite3_file *pFile, sqlite_int64 size){
rbu_file *p = (rbu_file*)pFile;
if( (p->openFlags & SQLITE_OPEN_DELETEONCLOSE) && p->pRbu ){
int rc = rbuUpdateTempSize(p, size);
if( rc!=SQLITE_OK ) return rc;
}
return p->pReal->pMethods->xTruncate(p->pReal, size);
}
static int rbuVfsSync(sqlite3_file *pFile, int flags){
rbu_file *p = (rbu_file *)pFile;
if( p->pRbu && p->pRbu->eStage==RBU_STAGE_CAPTURE ){
if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
return SQLITE_NOTICE_RBU;
}
return SQLITE_OK;
}
return p->pReal->pMethods->xSync(p->pReal, flags);
}
static int rbuVfsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
rbu_file *p = (rbu_file *)pFile;
int rc;
rc = p->pReal->pMethods->xFileSize(p->pReal, pSize);
if( rc==SQLITE_OK && *pSize==0
&& p->pRbu && rbuIsVacuum(p->pRbu)
&& (p->openFlags & SQLITE_OPEN_MAIN_DB)
){
*pSize = 1024;
}
return rc;
}
static int rbuVfsLock(sqlite3_file *pFile, int eLock){
rbu_file *p = (rbu_file*)pFile;
sqlite3rbu *pRbu = p->pRbu;
int rc = SQLITE_OK;
assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
if( eLock==SQLITE_LOCK_EXCLUSIVE
&& (p->bNolock || (pRbu && pRbu->eStage!=RBU_STAGE_DONE))
){
rc = SQLITE_BUSY;
}else{
rc = p->pReal->pMethods->xLock(p->pReal, eLock);
}
return rc;
}
static int rbuVfsUnlock(sqlite3_file *pFile, int eLock){
rbu_file *p = (rbu_file *)pFile;
return p->pReal->pMethods->xUnlock(p->pReal, eLock);
}
static int rbuVfsCheckReservedLock(sqlite3_file *pFile, int *pResOut){
rbu_file *p = (rbu_file *)pFile;
return p->pReal->pMethods->xCheckReservedLock(p->pReal, pResOut);
}
static int rbuVfsFileControl(sqlite3_file *pFile, int op, void *pArg){
rbu_file *p = (rbu_file *)pFile;
int (*xControl)(sqlite3_file*,int,void*) = p->pReal->pMethods->xFileControl;
int rc;
assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB)
|| p->openFlags & (SQLITE_OPEN_TRANSIENT_DB|SQLITE_OPEN_TEMP_JOURNAL)
);
if( op==SQLITE_FCNTL_RBU ){
sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
rc = xControl(p->pReal, op, pArg);
if( rc==SQLITE_NOTFOUND ){
void *dummy = 0;
rc = xControl(p->pReal, SQLITE_FCNTL_ZIPVFS, &dummy);
if( rc==SQLITE_OK ){
rc = SQLITE_ERROR;
pRbu->zErrmsg = sqlite3_mprintf("rbu/zipvfs setup error");
}else if( rc==SQLITE_NOTFOUND ){
pRbu->pTargetFd = p;
p->pRbu = pRbu;
rbuMainlistAdd(p);
if( p->pWalFd ) p->pWalFd->pRbu = pRbu;
rc = SQLITE_OK;
}
}
return rc;
}
else if( op==SQLITE_FCNTL_RBUCNT ){
sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
pRbu->nRbu++;
pRbu->pRbuFd = p;
p->bNolock = 1;
}
rc = xControl(p->pReal, op, pArg);
if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
rbu_vfs *pRbuVfs = p->pRbuVfs;
char *zIn = *(char**)pArg;
char *zOut = sqlite3_mprintf("rbu(%s)/%z", pRbuVfs->base.zName, zIn);
*(char**)pArg = zOut;
if( zOut==0 ) rc = SQLITE_NOMEM;
}
return rc;
}
static int rbuVfsSectorSize(sqlite3_file *pFile){
rbu_file *p = (rbu_file *)pFile;
return p->pReal->pMethods->xSectorSize(p->pReal);
}
static int rbuVfsDeviceCharacteristics(sqlite3_file *pFile){
rbu_file *p = (rbu_file *)pFile;
return p->pReal->pMethods->xDeviceCharacteristics(p->pReal);
}
static int rbuVfsShmLock(sqlite3_file *pFile, int ofst, int n, int flags){
rbu_file *p = (rbu_file*)pFile;
sqlite3rbu *pRbu = p->pRbu;
int rc = SQLITE_OK;
#ifdef SQLITE_AMALGAMATION
assert( WAL_CKPT_LOCK==1 );
#endif
assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
if( pRbu && (
pRbu->eStage==RBU_STAGE_OAL
|| pRbu->eStage==RBU_STAGE_MOVE
|| pRbu->eStage==RBU_STAGE_DONE
)){
if( ofst==WAL_LOCK_CKPT && n==1 ) rc = SQLITE_BUSY;
}else{
int bCapture = 0;
if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
bCapture = 1;
}
if( bCapture==0 || 0==(flags & SQLITE_SHM_UNLOCK) ){
rc = p->pReal->pMethods->xShmLock(p->pReal, ofst, n, flags);
if( bCapture && rc==SQLITE_OK ){
pRbu->mLock |= ((1<<n) - 1) << ofst;
}
}
}
return rc;
}
static int rbuVfsShmMap(
sqlite3_file *pFile,
int iRegion,
int szRegion,
int isWrite,
void volatile **pp
){
rbu_file *p = (rbu_file*)pFile;
int rc = SQLITE_OK;
int eStage = (p->pRbu ? p->pRbu->eStage : 0);
assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
if( eStage==RBU_STAGE_OAL ){
sqlite3_int64 nByte = (iRegion+1) * sizeof(char*);
char **apNew = (char**)sqlite3_realloc64(p->apShm, nByte);
assert( iRegion==p->nShm );
if( apNew==0 ){
rc = SQLITE_NOMEM;
}else{
memset(&apNew[p->nShm], 0, sizeof(char*) * (1 + iRegion - p->nShm));
p->apShm = apNew;
p->nShm = iRegion+1;
}
if( rc==SQLITE_OK ){
char *pNew = (char*)sqlite3_malloc64(szRegion);
if( pNew==0 ){
rc = SQLITE_NOMEM;
}else{
memset(pNew, 0, szRegion);
p->apShm[iRegion] = pNew;
}
}
if( rc==SQLITE_OK ){
*pp = p->apShm[iRegion];
}else{
*pp = 0;
}
}else{
assert( p->apShm==0 );
rc = p->pReal->pMethods->xShmMap(p->pReal, iRegion, szRegion, isWrite, pp);
}
return rc;
}
static void rbuVfsShmBarrier(sqlite3_file *pFile){
rbu_file *p = (rbu_file *)pFile;
p->pReal->pMethods->xShmBarrier(p->pReal);
}
static int rbuVfsShmUnmap(sqlite3_file *pFile, int delFlag){
rbu_file *p = (rbu_file*)pFile;
int rc = SQLITE_OK;
int eStage = (p->pRbu ? p->pRbu->eStage : 0);
assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
}else{
rbuUnlockShm(p);
rc = p->pReal->pMethods->xShmUnmap(p->pReal, delFlag);
}
return rc;
}
static int rbuVfsOpen(
sqlite3_vfs *pVfs,
const char *zName,
sqlite3_file *pFile,
int flags,
int *pOutFlags
){
static sqlite3_io_methods rbuvfs_io_methods = {
2,
rbuVfsClose,
rbuVfsRead,
rbuVfsWrite,
rbuVfsTruncate,
rbuVfsSync,
rbuVfsFileSize,
rbuVfsLock,
rbuVfsUnlock,
rbuVfsCheckReservedLock,
rbuVfsFileControl,
rbuVfsSectorSize,
rbuVfsDeviceCharacteristics,
rbuVfsShmMap,
rbuVfsShmLock,
rbuVfsShmBarrier,
rbuVfsShmUnmap,
0, 0
};
static sqlite3_io_methods rbuvfs_io_methods1 = {
1,
rbuVfsClose,
rbuVfsRead,
rbuVfsWrite,
rbuVfsTruncate,
rbuVfsSync,
rbuVfsFileSize,
rbuVfsLock,
rbuVfsUnlock,
rbuVfsCheckReservedLock,
rbuVfsFileControl,
rbuVfsSectorSize,
rbuVfsDeviceCharacteristics,
0, 0, 0, 0, 0, 0
};
rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
rbu_file *pFd = (rbu_file *)pFile;
int rc = SQLITE_OK;
const char *zOpen = zName;
int oflags = flags;
memset(pFd, 0, sizeof(rbu_file));
pFd->pReal = (sqlite3_file*)&pFd[1];
pFd->pRbuVfs = pRbuVfs;
pFd->openFlags = flags;
if( zName ){
if( flags & SQLITE_OPEN_MAIN_DB ){
pFd->zWal = sqlite3_filename_wal(zName);
}
else if( flags & SQLITE_OPEN_WAL ){
rbu_file *pDb = rbuFindMaindb(pRbuVfs, zName, 0);
if( pDb ){
if( pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
size_t nOpen;
if( rbuIsVacuum(pDb->pRbu) ){
zOpen = sqlite3_db_filename(pDb->pRbu->dbRbu, "main");
zOpen = sqlite3_filename_wal(zOpen);
}
nOpen = strlen(zOpen);
((char*)zOpen)[nOpen-3] = 'o';
pFd->pRbu = pDb->pRbu;
}
pDb->pWalFd = pFd;
}
}
}else{
pFd->pRbu = pRbuVfs->pRbu;
}
if( oflags & SQLITE_OPEN_MAIN_DB
&& sqlite3_uri_boolean(zName, "rbu_memory", 0)
){
assert( oflags & SQLITE_OPEN_MAIN_DB );
oflags = SQLITE_OPEN_TEMP_DB | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
zOpen = 0;
}
if( rc==SQLITE_OK ){
rc = pRealVfs->xOpen(pRealVfs, zOpen, pFd->pReal, oflags, pOutFlags);
}
if( pFd->pReal->pMethods ){
const sqlite3_io_methods *pMeth = pFd->pReal->pMethods;
if( pMeth->iVersion<2 || pMeth->xShmLock==0 ){
pFile->pMethods = &rbuvfs_io_methods1;
}else{
pFile->pMethods = &rbuvfs_io_methods;
}
if( flags & SQLITE_OPEN_MAIN_DB ){
rbuMainlistAdd(pFd);
}
}else{
sqlite3_free(pFd->zDel);
}
return rc;
}
static int rbuVfsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
return pRealVfs->xDelete(pRealVfs, zPath, dirSync);
}
static int rbuVfsAccess(
sqlite3_vfs *pVfs,
const char *zPath,
int flags,
int *pResOut
){
rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
int rc;
rc = pRealVfs->xAccess(pRealVfs, zPath, flags, pResOut);
if( rc==SQLITE_OK && flags==SQLITE_ACCESS_EXISTS ){
rbu_file *pDb = rbuFindMaindb(pRbuVfs, zPath, 1);
if( pDb && pDb->pRbu->eStage==RBU_STAGE_OAL ){
assert( pDb->pRbu );
if( *pResOut ){
rc = SQLITE_CANTOPEN;
}else{
sqlite3_int64 sz = 0;
rc = rbuVfsFileSize(&pDb->base, &sz);
*pResOut = (sz>0);
}
}
}
return rc;
}
static int rbuVfsFullPathname(
sqlite3_vfs *pVfs,
const char *zPath,
int nOut,
char *zOut
){
sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
return pRealVfs->xFullPathname(pRealVfs, zPath, nOut, zOut);
}
#ifndef SQLITE_OMIT_LOAD_EXTENSION
static void *rbuVfsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
return pRealVfs->xDlOpen(pRealVfs, zPath);
}
static void rbuVfsDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
pRealVfs->xDlError(pRealVfs, nByte, zErrMsg);
}
static void (*rbuVfsDlSym(
sqlite3_vfs *pVfs,
void *pArg,
const char *zSym
))(void){
sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
return pRealVfs->xDlSym(pRealVfs, pArg, zSym);
}
static void rbuVfsDlClose(sqlite3_vfs *pVfs, void *pHandle){
sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
pRealVfs->xDlClose(pRealVfs, pHandle);
}
#endif
static int rbuVfsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
return pRealVfs->xRandomness(pRealVfs, nByte, zBufOut);
}
static int rbuVfsSleep(sqlite3_vfs *pVfs, int nMicro){
sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
return pRealVfs->xSleep(pRealVfs, nMicro);
}
static int rbuVfsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
return pRealVfs->xCurrentTime(pRealVfs, pTimeOut);
}
static int rbuVfsGetLastError(sqlite3_vfs *pVfs, int a, char *b){
return 0;
}
void sqlite3rbu_destroy_vfs(const char *zName){
sqlite3_vfs *pVfs = sqlite3_vfs_find(zName);
if( pVfs && pVfs->xOpen==rbuVfsOpen ){
sqlite3_mutex_free(((rbu_vfs*)pVfs)->mutex);
sqlite3_vfs_unregister(pVfs);
sqlite3_free(pVfs);
}
}
int sqlite3rbu_create_vfs(const char *zName, const char *zParent){
static sqlite3_vfs vfs_template = {
1,
0,
0,
0,
0,
0,
rbuVfsOpen,
rbuVfsDelete,
rbuVfsAccess,
rbuVfsFullPathname,
#ifndef SQLITE_OMIT_LOAD_EXTENSION
rbuVfsDlOpen,
rbuVfsDlError,
rbuVfsDlSym,
rbuVfsDlClose,
#else
0, 0, 0, 0,
#endif
rbuVfsRandomness,
rbuVfsSleep,
rbuVfsCurrentTime,
rbuVfsGetLastError,
0,
0, 0, 0
};
rbu_vfs *pNew = 0;
int rc = SQLITE_OK;
size_t nName;
size_t nByte;
nName = strlen(zName);
nByte = sizeof(rbu_vfs) + nName + 1;
pNew = (rbu_vfs*)sqlite3_malloc64(nByte);
if( pNew==0 ){
rc = SQLITE_NOMEM;
}else{
sqlite3_vfs *pParent;
memset(pNew, 0, nByte);
pParent = sqlite3_vfs_find(zParent);
if( pParent==0 ){
rc = SQLITE_NOTFOUND;
}else{
char *zSpace;
memcpy(&pNew->base, &vfs_template, sizeof(sqlite3_vfs));
pNew->base.mxPathname = pParent->mxPathname;
pNew->base.szOsFile = sizeof(rbu_file) + pParent->szOsFile;
pNew->pRealVfs = pParent;
pNew->base.zName = (const char*)(zSpace = (char*)&pNew[1]);
memcpy(zSpace, zName, nName);
pNew->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_RECURSIVE);
if( pNew->mutex==0 ){
rc = SQLITE_NOMEM;
}else{
rc = sqlite3_vfs_register(&pNew->base, 0);
}
}
if( rc!=SQLITE_OK ){
sqlite3_mutex_free(pNew->mutex);
sqlite3_free(pNew);
}
}
return rc;
}
sqlite3_int64 sqlite3rbu_temp_size_limit(sqlite3rbu *pRbu, sqlite3_int64 n){
if( n>=0 ){
pRbu->szTempLimit = n;
}
return pRbu->szTempLimit;
}
sqlite3_int64 sqlite3rbu_temp_size(sqlite3rbu *pRbu){
return pRbu->szTemp;
}
#endif