interplane.Get Omega
Read in your language

sqlite

[Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI.

Brought by drakestapleton

branch master Branches Tags History

sqlite / ext / rbu / sqlite3rbu.c

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