/ Changes On Branch begin-concurrent-wal2
Login

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Changes In Branch begin-concurrent-wal2 Excluding Merge-Ins

This is equivalent to a diff from fdbf97e611 to 41e742bd0f

2019-03-26
12:07
Merge recent enhancements from trunk. (check-in: 774d0d5288 user: drh tags: begin-concurrent)
2019-01-11
15:26
Merge documentation changes from branch begin-concurrent-wal2 into this branch. (check-in: cf8a0c71cf user: dan tags: begin-concurrent-pnu-wal2)
15:22
Merge documentation changes from branch "begin-concurrent" into this branch. (Closed-Leaf check-in: 41e742bd0f user: dan tags: begin-concurrent-wal2)
15:06
Add new documentation file begin_concurrent.md. (check-in: fdbf97e611 user: dan tags: begin-concurrent)
14:59
Merge latest wal2 changes (documentation only) into this branch. (check-in: 820ba1cc7e user: dan tags: begin-concurrent-wal2)
2019-01-02
16:08
Merge latest trunk changes into this branch. (check-in: 5bf212f1a7 user: dan tags: begin-concurrent)

Added doc/wal2.md.



































































































1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

Wal2 Mode Notes
===============

## Activating/Deactivating Wal2 Mode

"Wal2" mode is very similar to "wal" mode. To change a database to wal2 mode,
use the command:

>
     PRAGMA journal_mode = wal2;

It is not possible to change a database directly from "wal" mode to "wal2"
mode. Instead, it must first be changed to rollback mode. So, to change a wal
mode database to wal2 mode, the following two commands may be used:

>
     PRAGMA journal_mode = delete;
     PRAGMA journal_mode = wal2;

A database in wal2 mode may only be accessed by versions of SQLite compiled
from this branch. Attempting to use any other version of SQLite results in an
SQLITE_NOTADB error. A wal2 mode database may be changed back to rollback mode
(making it accessible by all versions of SQLite) using:

>
     PRAGMA journal_mode = delete;

## The Advantage of Wal2 Mode

In legacy wal mode, when a writer writes data to the database, it doesn't
modify the database file directly. Instead, it appends new data to the
"<database>-wal" file. Readers read data from both the original database
file and the "<database>-wal" file. At some point, data is copied from the
"<database>-wal" file into the database file, after which the wal file can
be deleted or overwritten. Copying data from the wal file into the database
file is called a "checkpoint", and may be done explictly (either by "PRAGMA
wal_checkpoint" or sqlite3_wal_checkpoint_v2()), or
automatically (by configuring "PRAGMA wal_autocheckpoint" - this is the
default).

Checkpointers do not block writers, and writers do not block checkpointers.
However, if a writer writes to the database while a checkpoint is ongoing,
then the new data is appended to the end of the wal file. This means that,
even following the checkpoint, the wal file cannot be overwritten or deleted,
and so all subsequent transactions must also be appended to the wal file. The
work of the checkpointer is not wasted - SQLite remembers which parts of the
wal file have already been copied into the db file so that the next checkpoint
does not have to do so again - but it does mean that the wal file may grow
indefinitely if the checkpointer never gets a chance to finish without a
writer appending to the wal file. There are also circumstances in which
long-running readers may prevent a checkpointer from checkpointing the entire
wal file - also causing the wal file to grow indefinitely in a busy system.

Wal2 mode does not have this problem. In wal2 mode, wal files do not grow
indefinitely even if the checkpointer never has a chance to finish
uninterrupted.

In wal2 mode, the system uses two wal files instead of one. The files are named
"<database>-wal" and "<database>-wal2", where "<database>" is of
course the name of the database file. When data is written to the database, the
writer begins by appending the new data to the first wal file. Once the first
wal file has grown large enough, writers switch to appending data to the second
wal file. At this point the first wal file can be checkpointed (after which it
can be overwritten). Then, once the second wal file has grown large enough and
the first wal file has been checkpointed, writers switch back to the first wal
file. And so on.

## Application Programming

From the point of view of the user, the main differences between wal and 
wal2 mode are to do with checkpointing:

  * In wal mode, a checkpoint may be attempted at any time. In wal2 
    mode, the checkpointer has to wait until writers have switched 
    to the "other" wal file before a checkpoint can take place.

  * In wal mode, the wal-hook (callback registered using
    sqlite3_wal_hook()) is invoked after a transaction is committed
    with the total number of pages in the wal file as an argument. In wal2
    mode, the argument is either the total number of uncheckpointed pages in
    both wal files, or - if the "other" wal file is empty or already
    checkpointed - 0.

Clients are recommended to use the same strategies for checkpointing wal2 mode
databases as for wal databases - by registering a wal-hook using
sqlite3_wal_hook() and attempting a checkpoint when the parameter
exceeds a certain threshold.

However, it should be noted that although the wal-hook is invoked after each
transaction is committed to disk and database locks released, it is still
invoked from within the sqlite3_step() call used to execute the "COMMIT"
command. In BEGIN CONCURRENT systems, where the "COMMIT" is often protected by
an application mutex, this may reduce concurrency. In such systems, instead of
executing a checkpoint from within the wal-hook, a thread might defer this
action until after the application mutex has been released.


Added ext/misc/bgckpt.c.





















































































































































































































































1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
** 2017-10-11
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
******************************************************************************
**
*/

#if !defined(SQLITE_TEST) || defined(SQLITE_OS_UNIX)

#include "sqlite3.h"
#include <string.h>
#include <pthread.h>

/*
** API declarations.
*/
typedef struct Checkpointer Checkpointer;
int sqlite3_bgckpt_create(const char *zFilename, Checkpointer **pp);
int sqlite3_bgckpt_checkpoint(Checkpointer *p, int bBlock);
void sqlite3_bgckpt_destroy(Checkpointer *p);


struct Checkpointer {
  sqlite3 *db;                    /* Database handle */

  pthread_t thread;               /* Background thread */
  pthread_mutex_t mutex;
  pthread_cond_t cond;

  int rc;                         /* Error from "PRAGMA wal_checkpoint" */
  int bCkpt;                      /* True if checkpoint requested */
  int bExit;                      /* True if exit requested */
};

static void *bgckptThreadMain(void *pCtx){
  int rc = SQLITE_OK;
  Checkpointer *p = (Checkpointer*)pCtx;

  while( rc==SQLITE_OK ){
    int bExit;

    pthread_mutex_lock(&p->mutex);
    if( p->bCkpt==0 && p->bExit==0 ){
      pthread_cond_wait(&p->cond, &p->mutex);
    }
    p->bCkpt = 0;
    bExit = p->bExit;
    pthread_mutex_unlock(&p->mutex);

    if( bExit ) break;
    rc = sqlite3_exec(p->db, "PRAGMA wal_checkpoint", 0, 0, 0);
    if( rc==SQLITE_BUSY ){
      rc = SQLITE_OK;
    }
  }

  pthread_mutex_lock(&p->mutex);
  p->rc = rc;
  pthread_mutex_unlock(&p->mutex);
  return 0;
}

void sqlite3_bgckpt_destroy(Checkpointer *p){
  if( p ){
    void *ret = 0;

    /* Signal the background thread to exit */
    pthread_mutex_lock(&p->mutex);
    p->bExit = 1;
    pthread_cond_broadcast(&p->cond);
    pthread_mutex_unlock(&p->mutex);

    pthread_join(p->thread, &ret);
    sqlite3_close(p->db);
    sqlite3_free(p);
  }
}


int sqlite3_bgckpt_create(const char *zFilename, Checkpointer **pp){
  Checkpointer *pNew = 0;
  int rc;

  pNew = (Checkpointer*)sqlite3_malloc(sizeof(Checkpointer));
  if( pNew==0 ){
    rc = SQLITE_NOMEM;
  }else{
    memset(pNew, 0, sizeof(Checkpointer));
    rc = sqlite3_open(zFilename, &pNew->db);
  }

  if( rc==SQLITE_OK ){
    pthread_mutex_init(&pNew->mutex, 0);
    pthread_cond_init(&pNew->cond, 0);
    pthread_create(&pNew->thread, 0, bgckptThreadMain, (void*)pNew);
  }

  if( rc!=SQLITE_OK ){
    sqlite3_bgckpt_destroy(pNew);
    pNew = 0;
  }
  *pp = pNew;
  return rc;
}

int sqlite3_bgckpt_checkpoint(Checkpointer *p, int bBlock){
  int rc;
  pthread_mutex_lock(&p->mutex);
  rc = p->rc;
  if( rc==SQLITE_OK ){
    p->bCkpt = 1;
    pthread_cond_broadcast(&p->cond);
  }
  pthread_mutex_unlock(&p->mutex);
  return rc;
}

#ifdef SQLITE_TEST

#if defined(INCLUDE_SQLITE_TCL_H)
#  include "sqlite_tcl.h"
#else
#  include "tcl.h"
#  ifndef SQLITE_TCLAPI
#    define SQLITE_TCLAPI
#  endif
#endif

const char *sqlite3ErrName(int rc);

static void SQLITE_TCLAPI bgckpt_del(void * clientData){
  Checkpointer *pCkpt = (Checkpointer*)clientData;
  sqlite3_bgckpt_destroy(pCkpt);
}

/*
** Tclcmd: $ckpt SUBCMD ...
*/
static int SQLITE_TCLAPI bgckpt_obj_cmd(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  Checkpointer *pCkpt = (Checkpointer*)clientData;
  const char *aCmd[] = { "checkpoint", "destroy", 0 };
  int iCmd;

  if( objc<2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "SUBCMD ...");
    return TCL_ERROR;
  }

  if( Tcl_GetIndexFromObj(interp, objv[1], aCmd, "sub-command", 0, &iCmd) ){
    return TCL_ERROR;
  }

  switch( iCmd ){
    case 0: {
      int rc;
      int bBlock = 0;

      if( objc>3 ){
        Tcl_WrongNumArgs(interp, 2, objv, "?BLOCKING?");
        return TCL_ERROR;
      }
      if( objc==3 && Tcl_GetBooleanFromObj(interp, objv[2], &bBlock) ){
        return TCL_ERROR;
      }

      rc = sqlite3_bgckpt_checkpoint(pCkpt, bBlock);
      if( rc!=SQLITE_OK ){
        Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3ErrName(rc), -1));
        return TCL_ERROR;
      }
      break;
    }

    case 1: {
      Tcl_DeleteCommand(interp, Tcl_GetString(objv[0]));
      break;
    }
  }

  return TCL_OK;
}

/*
** Tclcmd: bgckpt CMDNAME FILENAME
*/
static int SQLITE_TCLAPI bgckpt_cmd(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  const char *zCmd;
  const char *zFilename;
  int rc;
  Checkpointer *pCkpt;

  if( objc!=3 ){
    Tcl_WrongNumArgs(interp, 1, objv, "CMDNAME FILENAME");
    return TCL_ERROR;
  }
  zCmd = Tcl_GetString(objv[1]);
  zFilename = Tcl_GetString(objv[2]);

  rc = sqlite3_bgckpt_create(zFilename, &pCkpt);
  if( rc!=SQLITE_OK ){
    Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3ErrName(rc), -1));
    return TCL_ERROR;
  }

  Tcl_CreateObjCommand(interp, zCmd, bgckpt_obj_cmd, (void*)pCkpt, bgckpt_del);
  Tcl_SetObjResult(interp, objv[1]);
  return TCL_OK;
}

int Bgckpt_Init(Tcl_Interp *interp){
  Tcl_CreateObjCommand(interp, "bgckpt", bgckpt_cmd, 0, 0);
  return TCL_OK;
}
#endif   /* SQLITE_TEST */

#else
#if defined(INCLUDE_SQLITE_TCL_H)
#  include "sqlite_tcl.h"
#else
#  include "tcl.h"
#  ifndef SQLITE_TCLAPI
#    define SQLITE_TCLAPI
#  endif
#endif
int Bgckpt_Init(Tcl_Interp *interp){ return TCL_OK; }
#endif

Changes to ext/session/sqlite3session.h.

314
315
316
317
318
319
320













321
322
323
324
325
326
327
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340







+
+
+
+
+
+
+
+
+
+
+
+
+







** the same session object is disabled, no INSERT record will appear in the
** changeset, even though the delete took place while the session was disabled.
** Or, if one field of a row is updated while a session is disabled, and 
** another field of the same row is updated while the session is enabled, the
** resulting changeset will contain an UPDATE change that updates both fields.
*/
int sqlite3session_changeset(
  sqlite3_session *pSession,      /* Session object */
  int *pnChangeset,               /* OUT: Size of buffer at *ppChangeset */
  void **ppChangeset              /* OUT: Buffer containing changeset */
);

/*
** CAPI3REF: Generate A Full Changeset From A Session Object
**
** This function is similar to sqlite3session_changeset(), except that for
** each row affected by an UPDATE statement, all old.* values are recorded
** as part of the changeset, not just those modified.
*/
int sqlite3session_fullchangeset(
  sqlite3_session *pSession,      /* Session object */
  int *pnChangeset,               /* OUT: Size of buffer at *ppChangeset */
  void **ppChangeset              /* OUT: Buffer containing changeset */
);

/*
** CAPI3REF: Generate A Full Changeset From A Session Object

Changes to main.mk.

353
354
355
356
357
358
359

360
361
362
363
364
365
366
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367







+







  $(TOP)/src/test_window.c \
  $(TOP)/src/test_wsd.c

# Extensions to be statically loaded.
#
TESTSRC += \
  $(TOP)/ext/misc/amatch.c \
  $(TOP)/ext/misc/bgckpt.c \
  $(TOP)/ext/misc/carray.c \
  $(TOP)/ext/misc/closure.c \
  $(TOP)/ext/misc/csv.c \
  $(TOP)/ext/misc/eval.c \
  $(TOP)/ext/misc/explain.c \
  $(TOP)/ext/misc/fileio.c \
  $(TOP)/ext/misc/fuzzer.c \

Changes to src/btree.c.

3293
3294
3295
3296
3297
3298
3299
3300

3301
3302
3303

3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315

3316
3317

3318
3319
3320
3321
3322
3323
3324
3293
3294
3295
3296
3297
3298
3299

3300
3301
3302

3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314

3315
3316

3317
3318
3319
3320
3321
3322
3323
3324







-
+


-
+











-
+

-
+







    if( page1[18]>1 ){
      pBt->btsFlags |= BTS_READ_ONLY;
    }
    if( page1[19]>1 ){
      goto page1_init_failed;
    }
#else
    if( page1[18]>2 ){
    if( page1[18]>3 ){
      pBt->btsFlags |= BTS_READ_ONLY;
    }
    if( page1[19]>2 ){
    if( page1[19]>3 ){
      goto page1_init_failed;
    }

    /* If the write version is set to 2, this database should be accessed
    ** in WAL mode. If the log is not already open, open it now. Then 
    ** return SQLITE_OK and return without populating BtShared.pPage1.
    ** The caller detects this and calls this function again. This is
    ** required as the version of page 1 currently in the page1 buffer
    ** may not be the latest version - there may be a newer one in the log
    ** file.
    */
    if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
    if( page1[19]>=2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
      int isOpen = 0;
      rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
      rc = sqlite3PagerOpenWal(pBt->pPager, (page1[19]==3), &isOpen);
      if( rc!=SQLITE_OK ){
        goto page1_init_failed;
      }else{
        setDefaultSyncFlag(pBt, SQLITE_DEFAULT_WAL_SYNCHRONOUS+1);
        if( isOpen==0 ){
          releasePageOne(pPage1);
          return SQLITE_OK;
10613
10614
10615
10616
10617
10618
10619
10620

10621
10622
10623
10624
10625
10626
10627
10613
10614
10615
10616
10617
10618
10619

10620
10621
10622
10623
10624
10625
10626
10627







-
+







** "write version" (single byte at byte offset 19) fields in the database
** header to iVersion.
*/
int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
  BtShared *pBt = pBtree->pBt;
  int rc;                         /* Return code */
 
  assert( iVersion==1 || iVersion==2 );
  assert( iVersion==1 || iVersion==2 || iVersion==3 );

  /* If setting the version fields to 1, do not automatically open the
  ** WAL connection, even if the version fields are currently set to 2.
  */
  pBt->btsFlags &= ~BTS_NO_WAL;
  if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;

Changes to src/pager.c.

810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
810
811
812
813
814
815
816














817
818
819
820
821
822
823







-
-
-
-
-
-
-
-
-
-
-
-
-
-







#endif

/*
** The maximum legal page number is (2^31 - 1).
*/
#define PAGER_MAX_PGNO 2147483647

/*
** The argument to this macro is a file descriptor (type sqlite3_file*).
** Return 0 if it is not open, or non-zero (but not 1) if it is.
**
** This is so that expressions can be written as:
**
**   if( isOpen(pPager->jfd) ){ ...
**
** instead of
**
**   if( pPager->jfd->pMethods ){ ...
*/
#define isOpen(pFd) ((pFd)->pMethods!=0)

#ifdef SQLITE_DIRECT_OVERFLOW_READ
/*
** Return true if page pgno can be read directly from the database file
** by the b-tree layer. This is the case if:
**
**   * the database file is open,
**   * there are no dirty pages in the cache, and
957
958
959
960
961
962
963

964
965
966
967
968
969
970
971
972
973
974
975
976
977

978
979
980
981
982
983
984
985
986
987
988
989

990
991
992
993
994
995
996
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985







+














+












+







        ** a rollback transaction that switches from journal_mode=off
        ** to journal_mode=wal.
        */
        assert( p->eLock>=RESERVED_LOCK );
        assert( isOpen(p->jfd) 
             || p->journalMode==PAGER_JOURNALMODE_OFF 
             || p->journalMode==PAGER_JOURNALMODE_WAL 
             || p->journalMode==PAGER_JOURNALMODE_WAL2
        );
      }
      assert( pPager->dbOrigSize==pPager->dbFileSize );
      assert( pPager->dbOrigSize==pPager->dbHintSize );
      break;

    case PAGER_WRITER_DBMOD:
      assert( p->eLock==EXCLUSIVE_LOCK );
      assert( pPager->errCode==SQLITE_OK );
      assert( !pagerUseWal(pPager) );
      assert( p->eLock>=EXCLUSIVE_LOCK );
      assert( isOpen(p->jfd) 
           || p->journalMode==PAGER_JOURNALMODE_OFF 
           || p->journalMode==PAGER_JOURNALMODE_WAL 
           || p->journalMode==PAGER_JOURNALMODE_WAL2
           || (sqlite3OsDeviceCharacteristics(p->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
      );
      assert( pPager->dbOrigSize<=pPager->dbHintSize );
      break;

    case PAGER_WRITER_FINISHED:
      assert( p->eLock==EXCLUSIVE_LOCK );
      assert( pPager->errCode==SQLITE_OK );
      assert( !pagerUseWal(pPager) );
      assert( isOpen(p->jfd) 
           || p->journalMode==PAGER_JOURNALMODE_OFF 
           || p->journalMode==PAGER_JOURNALMODE_WAL 
           || p->journalMode==PAGER_JOURNALMODE_WAL2
           || (sqlite3OsDeviceCharacteristics(p->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
      );
      break;

    case PAGER_ERROR:
      /* There must be at least one outstanding reference to the pager if
      ** in ERROR state. Otherwise the pager should have already dropped
2127
2128
2129
2130
2131
2132
2133
2134

2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148


2149
2150
2151
2152
2153
2154
2155
2116
2117
2118
2119
2120
2121
2122

2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136

2137
2138
2139
2140
2141
2142
2143
2144
2145







-
+













-
+
+







          ** https://bugzilla.mozilla.org/show_bug.cgi?id=1072773
          */
          rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
        }
      }
      pPager->journalOff = 0;
    }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
      || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
      || (pPager->exclusiveMode && pPager->journalMode<PAGER_JOURNALMODE_WAL)
    ){
      rc = zeroJournalHdr(pPager, hasMaster||pPager->tempFile);
      pPager->journalOff = 0;
    }else{
      /* This branch may be executed with Pager.journalMode==MEMORY if
      ** a hot-journal was just rolled back. In this case the journal
      ** file should be closed and deleted. If this connection writes to
      ** the database file, it will do so using an in-memory journal.
      */
      int bDelete = !pPager->tempFile;
      assert( sqlite3JournalIsInMemory(pPager->jfd)==0 );
      assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE 
           || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
           || pPager->journalMode==PAGER_JOURNALMODE_WAL 
           || pPager->journalMode==PAGER_JOURNALMODE_WAL
           || pPager->journalMode==PAGER_JOURNALMODE_WAL2
      );
      sqlite3OsClose(pPager->jfd);
      if( bDelete ){
        rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, pPager->extraSync);
      }
    }
  }
3332
3333
3334
3335
3336
3337
3338




3339
3340
3341
3342
3343
3344
3345
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339







+
+
+
+







  */
  sqlite3WalEndReadTransaction(pPager->pWal);

  rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
  if( rc!=SQLITE_OK || changed ){
    pager_reset(pPager);
    if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
    assert( pPager->journalMode==PAGER_JOURNALMODE_WAL
         || pPager->journalMode==PAGER_JOURNALMODE_WAL2
    );
    pPager->journalMode = sqlite3WalJournalMode(pPager->pWal);
  }

  return rc;
}
#endif

/*
3427
3428
3429
3430
3431
3432
3433
3434

3435
3436

3437
3438
3439
3440
3441
3442
3443
3421
3422
3423
3424
3425
3426
3427

3428
3429

3430
3431
3432
3433
3434
3435
3436
3437







-
+

-
+








        rc = pagerPagecount(pPager, &nPage);
        if( rc ) return rc;
        if( nPage==0 ){
          rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
        }else{
          testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
          rc = sqlite3PagerOpenWal(pPager, 0);
          rc = sqlite3PagerOpenWal(pPager, 0, 0);
        }
      }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
      }else if( pPager->journalMode>=PAGER_JOURNALMODE_WAL ){
        pPager->journalMode = PAGER_JOURNALMODE_DELETE;
      }
    }
  }
  return rc;
}
#endif
7460
7461
7462
7463
7464
7465
7466

7467
7468
7469
7470
7471
7472
7473
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468







+








  /* The eMode parameter is always valid */
  assert(      eMode==PAGER_JOURNALMODE_DELETE
            || eMode==PAGER_JOURNALMODE_TRUNCATE
            || eMode==PAGER_JOURNALMODE_PERSIST
            || eMode==PAGER_JOURNALMODE_OFF 
            || eMode==PAGER_JOURNALMODE_WAL 
            || eMode==PAGER_JOURNALMODE_WAL2
            || eMode==PAGER_JOURNALMODE_MEMORY );

  /* This routine is only called from the OP_JournalMode opcode, and
  ** the logic there will never allow a temporary file to be changed
  ** to WAL mode.
  */
  assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
7494
7495
7496
7497
7498
7499
7500

7501
7502
7503



7504
7505
7506
7507
7508
7509
7510
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498

7499
7500
7501
7502
7503
7504
7505
7506
7507
7508







+


-
+
+
+







    */
    assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
    assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
    assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
    assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
    assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
    assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
    assert( (PAGER_JOURNALMODE_WAL2 & 5)==4 );

    assert( isOpen(pPager->fd) || pPager->exclusiveMode );
    if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
    if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 
     && eMode!=PAGER_JOURNALMODE_WAL2       /* TODO: fix this if possible */
    ){

      /* In this case we would like to delete the journal file. If it is
      ** not possible, then that is not a problem. Deleting the journal file
      ** here is an optimization only.
      **
      ** Before deleting the journal file, obtain a RESERVED lock on the
      ** database file. This ensures that the journal file is not deleted
7659
7660
7661
7662
7663
7664
7665
7666

7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687

7688
7689
7690
7691
7692
7693
7694
7657
7658
7659
7660
7661
7662
7663

7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684

7685
7686
7687
7688
7689
7690
7691
7692







-
+




















-
+








/*
** Call sqlite3WalOpen() to open the WAL handle. If the pager is in 
** exclusive-locking mode when this function is called, take an EXCLUSIVE
** lock on the database file and use heap-memory to store the wal-index
** in. Otherwise, use the normal shared-memory.
*/
static int pagerOpenWal(Pager *pPager){
static int pagerOpenWal(Pager *pPager, int bWal2){
  int rc = SQLITE_OK;

  assert( pPager->pWal==0 && pPager->tempFile==0 );
  assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );

  /* If the pager is already in exclusive-mode, the WAL module will use 
  ** heap-memory for the wal-index instead of the VFS shared-memory 
  ** implementation. Take the exclusive lock now, before opening the WAL
  ** file, to make sure this is safe.
  */
  if( pPager->exclusiveMode ){
    rc = pagerExclusiveLock(pPager);
  }

  /* Open the connection to the log file. If this operation fails, 
  ** (e.g. due to malloc() failure), return an error code.
  */
  if( rc==SQLITE_OK ){
    rc = sqlite3WalOpen(pPager->pVfs,
        pPager->fd, pPager->zWal, pPager->exclusiveMode,
        pPager->journalSizeLimit, &pPager->pWal
        pPager->journalSizeLimit, bWal2, &pPager->pWal
    );
  }
  pagerFixMaplimit(pPager);

  return rc;
}

7706
7707
7708
7709
7710
7711
7712

7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729

7730
7731

7732
7733
7734
7735
7736
7737
7738
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727

7728
7729

7730
7731
7732
7733
7734
7735
7736
7737







+
















-
+

-
+







**
** If the pager is open on a temp-file (or in-memory database), or if
** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
** without doing anything.
*/
int sqlite3PagerOpenWal(
  Pager *pPager,                  /* Pager object */
  int bWal2,                      /* Open in wal2 mode if not already open */
  int *pbOpen                     /* OUT: Set to true if call is a no-op */
){
  int rc = SQLITE_OK;             /* Return code */

  assert( assert_pager_state(pPager) );
  assert( pPager->eState==PAGER_OPEN   || pbOpen );
  assert( pPager->eState==PAGER_READER || !pbOpen );
  assert( pbOpen==0 || *pbOpen==0 );
  assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );

  if( !pPager->tempFile && !pPager->pWal ){
    if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;

    /* Close any rollback journal previously open */
    sqlite3OsClose(pPager->jfd);

    rc = pagerOpenWal(pPager);
    rc = pagerOpenWal(pPager, bWal2);
    if( rc==SQLITE_OK ){
      pPager->journalMode = PAGER_JOURNALMODE_WAL;
      pPager->journalMode = bWal2?PAGER_JOURNALMODE_WAL2:PAGER_JOURNALMODE_WAL;
      pPager->eState = PAGER_OPEN;
    }
  }else{
    *pbOpen = 1;
  }

  return rc;
7746
7747
7748
7749
7750
7751
7752
7753



7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768

7769
7770
7771
7772
7773
7774
7775
7745
7746
7747
7748
7749
7750
7751

7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768

7769
7770
7771
7772
7773
7774
7775
7776







-
+
+
+














-
+







** EXCLUSIVE lock on the database file. If this cannot be obtained, an
** error (SQLITE_BUSY) is returned and the log connection is not closed.
** If successful, the EXCLUSIVE lock is not released before returning.
*/
int sqlite3PagerCloseWal(Pager *pPager, sqlite3 *db){
  int rc = SQLITE_OK;

  assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
  assert( pPager->journalMode==PAGER_JOURNALMODE_WAL 
       || pPager->journalMode==PAGER_JOURNALMODE_WAL2
  );

  /* If the log file is not already open, but does exist in the file-system,
  ** it may need to be checkpointed before the connection can switch to
  ** rollback mode. Open it now so this can happen.
  */
  if( !pPager->pWal ){
    int logexists = 0;
    rc = pagerLockDb(pPager, SHARED_LOCK);
    if( rc==SQLITE_OK ){
      rc = sqlite3OsAccess(
          pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
      );
    }
    if( rc==SQLITE_OK && logexists ){
      rc = pagerOpenWal(pPager);
      rc = pagerOpenWal(pPager, 0);
    }
  }
    
  /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
  ** the database file, the log and log-summary files will be deleted.
  */
  if( rc==SQLITE_OK && pPager->pWal ){

Changes to src/pager.h.

77
78
79
80
81
82
83

















84
85
86
87
88
89
90
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107







+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+







#define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */
#define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
#define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
#define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
#define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
#define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
#define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */
#define PAGER_JOURNALMODE_WAL2        6   /* Use write-ahead logging mode 2 */

#define isWalMode(x) ((x)==PAGER_JOURNALMODE_WAL || (x)==PAGER_JOURNALMODE_WAL2)

/*
** The argument to this macro is a file descriptor (type sqlite3_file*).
** Return 0 if it is not open, or non-zero (but not 1) if it is.
**
** This is so that expressions can be written as:
**
**   if( isOpen(pPager->jfd) ){ ...
**
** instead of
**
**   if( pPager->jfd->pMethods ){ ...
*/
#define isOpen(pFd) ((pFd)->pMethods!=0)

/*
** Flags that make up the mask passed to sqlite3PagerGet().
*/
#define PAGER_GET_NOCONTENT     0x01  /* Do not load data from disk */
#define PAGER_GET_READONLY      0x02  /* Read-only page is acceptable */

174
175
176
177
178
179
180
181

182
183
184
185
186
187
188
191
192
193
194
195
196
197

198
199
200
201
202
203
204
205







-
+







int sqlite3PagerSharedLock(Pager *pPager);


#ifndef SQLITE_OMIT_WAL
  int sqlite3PagerCheckpoint(Pager *pPager, sqlite3*, int, int*, int*);
  int sqlite3PagerWalSupported(Pager *pPager);
  int sqlite3PagerWalCallback(Pager *pPager);
  int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
  int sqlite3PagerOpenWal(Pager *pPager, int, int *pisOpen);
  int sqlite3PagerCloseWal(Pager *pPager, sqlite3*);
# ifdef SQLITE_ENABLE_SNAPSHOT
  int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot);
  int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot);
  int sqlite3PagerSnapshotRecover(Pager *pPager);
  int sqlite3PagerSnapshotCheck(Pager *pPager, sqlite3_snapshot *pSnapshot);
  void sqlite3PagerSnapshotUnlock(Pager *pPager);

Changes to src/pragma.c.

256
257
258
259
260
261
262
263

264
265
266
267
268
269
270
271

272
273
274
275
276
277
278
256
257
258
259
260
261
262

263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279







-
+








+







** defined in pager.h. This function returns the associated lowercase
** journal-mode name.
*/
const char *sqlite3JournalModename(int eMode){
  static char * const azModeName[] = {
    "delete", "persist", "off", "truncate", "memory"
#ifndef SQLITE_OMIT_WAL
     , "wal"
     , "wal", "wal2"
#endif
  };
  assert( PAGER_JOURNALMODE_DELETE==0 );
  assert( PAGER_JOURNALMODE_PERSIST==1 );
  assert( PAGER_JOURNALMODE_OFF==2 );
  assert( PAGER_JOURNALMODE_TRUNCATE==3 );
  assert( PAGER_JOURNALMODE_MEMORY==4 );
  assert( PAGER_JOURNALMODE_WAL==5 );
  assert( PAGER_JOURNALMODE_WAL2==6 );
  assert( eMode>=0 && eMode<=ArraySize(azModeName) );

  if( eMode==ArraySize(azModeName) ) return 0;
  return azModeName[eMode];
}

/*

Changes to src/test_hexio.c.

186
187
188
189
190
191
192
193

194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209

210
211
212









213
214
215

216
217
218
219
220
221
222
223
224
225
226
227



228


229
230
231
232
233
234
235
186
187
188
189
190
191
192

193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211


212
213
214
215
216
217
218
219
220
221
222

223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238

239
240
241
242
243
244
245
246
247







-
+
















+

-
-
+
+
+
+
+
+
+
+
+


-
+












+
+
+
-
+
+







  sqlite3_free(aOut);
  fclose(out);
  Tcl_SetObjResult(interp, Tcl_NewIntObj(written));
  return TCL_OK;
}

/*
** USAGE:   hexio_get_int   HEXDATA
** USAGE:   hexio_get_int [-littleendian] HEXDATA
**
** Interpret the HEXDATA argument as a big-endian integer.  Return
** the value of that integer.  HEXDATA can contain between 2 and 8
** hexadecimal digits.
*/
static int SQLITE_TCLAPI hexio_get_int(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  int val;
  int nIn, nOut;
  const unsigned char *zIn;
  unsigned char *aOut;
  unsigned char aNum[4];
  int bLittle = 0;

  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "HEXDATA");
  if( objc==3 ){
    int n;
    char *z = Tcl_GetStringFromObj(objv[1], &n);
    if( n>=2 && n<=13 && memcmp(z, "-littleendian", n)==0 ){
      bLittle = 1;
    }
  }
  if( (objc-bLittle)!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "[-littleendian] HEXDATA");
    return TCL_ERROR;
  }
  zIn = (const unsigned char *)Tcl_GetStringFromObj(objv[1], &nIn);
  zIn = (const unsigned char *)Tcl_GetStringFromObj(objv[1+bLittle], &nIn);
  aOut = sqlite3_malloc( nIn/2 );
  if( aOut==0 ){
    return TCL_ERROR;
  }
  nOut = sqlite3TestHexToBin(zIn, nIn, aOut);
  if( nOut>=4 ){
    memcpy(aNum, aOut, 4);
  }else{
    memset(aNum, 0, sizeof(aNum));
    memcpy(&aNum[4-nOut], aOut, nOut);
  }
  sqlite3_free(aOut);
  if( bLittle ){
    val = (aNum[3]<<24) | (aNum[2]<<16) | (aNum[1]<<8) | aNum[0];
  }else{
  val = (aNum[0]<<24) | (aNum[1]<<16) | (aNum[2]<<8) | aNum[3];
    val = (aNum[0]<<24) | (aNum[1]<<16) | (aNum[2]<<8) | aNum[3];
  }
  Tcl_SetObjResult(interp, Tcl_NewIntObj(val));
  return TCL_OK;
}


/*
** USAGE:   hexio_render_int16   INTEGER

Changes to src/test_tclsh.c.

94
95
96
97
98
99
100

101
102
103
104
105
106
107
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108







+







#if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
  extern int TestSession_Init(Tcl_Interp*);
#endif
  extern int Md5_Init(Tcl_Interp*);
  extern int Fts5tcl_Init(Tcl_Interp *);
  extern int SqliteRbu_Init(Tcl_Interp*);
  extern int Sqlitetesttcl_Init(Tcl_Interp*);
  extern int Bgckpt_Init(Tcl_Interp*);
#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
  extern int Sqlitetestfts3_Init(Tcl_Interp *interp);
#endif
#ifdef SQLITE_ENABLE_ZIPVFS
  extern int Zipvfs_Init(Tcl_Interp*);
#endif
  extern int TestExpert_Init(Tcl_Interp*);
161
162
163
164
165
166
167


168
169
170
171
172
173
174
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177







+
+







  SqlitetestSyscall_Init(interp);
#if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
  TestSession_Init(interp);
#endif
  Fts5tcl_Init(interp);
  SqliteRbu_Init(interp);
  Sqlitetesttcl_Init(interp);
  Bgckpt_Init(interp);


#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
  Sqlitetestfts3_Init(interp);
#endif
  TestExpert_Init(interp);
  Sqlitetest_window_Init(interp);

Changes to src/vdbe.c.

6653
6654
6655
6656
6657
6658
6659

6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677

6678
6679
6680
6681
6682
6683
6684
6685
6686












6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717

























6718


6719
6720
6721
6722
6723
6724
6725
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677

6678
6679
6680
6681
6682
6683
6684



6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
























6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728

6729
6730
6731
6732
6733
6734
6735
6736
6737







+

















-
+






-
-
-
+
+
+
+
+
+
+
+
+
+
+
+







-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
+
+







  eNew = pOp->p3;
  assert( eNew==PAGER_JOURNALMODE_DELETE 
       || eNew==PAGER_JOURNALMODE_TRUNCATE 
       || eNew==PAGER_JOURNALMODE_PERSIST 
       || eNew==PAGER_JOURNALMODE_OFF
       || eNew==PAGER_JOURNALMODE_MEMORY
       || eNew==PAGER_JOURNALMODE_WAL
       || eNew==PAGER_JOURNALMODE_WAL2
       || eNew==PAGER_JOURNALMODE_QUERY
  );
  assert( pOp->p1>=0 && pOp->p1<db->nDb );
  assert( p->readOnly==0 );

  pBt = db->aDb[pOp->p1].pBt;
  pPager = sqlite3BtreePager(pBt);
  eOld = sqlite3PagerGetJournalMode(pPager);
  if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
  if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;

#ifndef SQLITE_OMIT_WAL
  zFilename = sqlite3PagerFilename(pPager, 1);

  /* Do not allow a transition to journal_mode=WAL for a database
  ** in temporary storage or if the VFS does not support shared memory 
  */
  if( eNew==PAGER_JOURNALMODE_WAL
  if( isWalMode(eNew)
   && (sqlite3Strlen30(zFilename)==0           /* Temp file */
       || !sqlite3PagerWalSupported(pPager))   /* No shared-memory support */
  ){
    eNew = eOld;
  }

  if( (eNew!=eOld)
   && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
  ){
  if( eNew!=eOld && (isWalMode(eNew) || isWalMode(eOld)) ){

    /* Prevent changing directly to wal2 from wal mode. And vice versa. */
    if( isWalMode(eNew) && isWalMode(eOld) ){
      rc = SQLITE_ERROR;
      sqlite3VdbeError(p, "cannot change from %s to %s mode",
          sqlite3JournalModename(eOld), sqlite3JournalModename(eNew)
      );
      goto abort_due_to_error;
    }

    /* Prevent switching into or out of wal/wal2 mode mid-transaction */
    if( !db->autoCommit || db->nVdbeRead>1 ){
      rc = SQLITE_ERROR;
      sqlite3VdbeError(p,
          "cannot change %s wal mode from within a transaction",
          (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
      );
      goto abort_due_to_error;
    }else{
 
      if( eOld==PAGER_JOURNALMODE_WAL ){
        /* If leaving WAL mode, close the log file. If successful, the call
        ** to PagerCloseWal() checkpoints and deletes the write-ahead-log 
        ** file. An EXCLUSIVE lock may still be held on the database file 
        ** after a successful return. 
        */
        rc = sqlite3PagerCloseWal(pPager, db);
        if( rc==SQLITE_OK ){
          sqlite3PagerSetJournalMode(pPager, eNew);
        }
      }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
        /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
        ** as an intermediate */
        sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
      }
  
      /* Open a transaction on the database file. Regardless of the journal
      ** mode, this transaction always uses a rollback journal.
      */
      assert( sqlite3BtreeIsInTrans(pBt)==0 );
      if( rc==SQLITE_OK ){
        rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
    }
 
    if( isWalMode(eOld) ){
      /* If leaving WAL mode, close the log file. If successful, the call
      ** to PagerCloseWal() checkpoints and deletes the write-ahead-log 
      ** file. An EXCLUSIVE lock may still be held on the database file 
      ** after a successful return. 
      */
      rc = sqlite3PagerCloseWal(pPager, db);
      if( rc==SQLITE_OK ){
        sqlite3PagerSetJournalMode(pPager, eNew);
      }
    }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
      /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
      ** as an intermediate */
      sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
    }

    /* Open a transaction on the database file. Regardless of the journal
    ** mode, this transaction always uses a rollback journal.
    */
    assert( sqlite3BtreeIsInTrans(pBt)==0 );
    if( rc==SQLITE_OK ){
      /* 1==rollback, 2==wal, 3==wal2 */
      rc = sqlite3BtreeSetVersion(pBt, 
      }
          1 + isWalMode(eNew) + (eNew==PAGER_JOURNALMODE_WAL2)
      );
    }
  }
#endif /* ifndef SQLITE_OMIT_WAL */

  if( rc ) eNew = eOld;
  eNew = sqlite3PagerSetJournalMode(pPager, eNew);

Changes to src/wal.c.

97
98
99
100
101
102
103
104

105
106
107
108
109
110
111
97
98
99
100
101
102
103

104
105
106
107
108
109
110
111







-
+







** being considered valid at the same time and being checkpointing together
** following a crash.
**
** READER ALGORITHM
**
** To read a page from the database (call it page number P), a reader
** first checks the WAL to see if it contains page P.  If so, then the
** last valid instance of page P that is a followed by a commit frame
** last valid instance of page P that is followed by a commit frame
** or is a commit frame itself becomes the value read.  If the WAL
** contains no copies of page P that are valid and which are a commit
** frame or are followed by a commit frame, then page P is read from
** the database file.
**
** To start a read transaction, the reader records the index of the last
** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
229
230
231
232
233
234
235
236

237
238
239
240
241
242
243
244
245
246

























































































































































































247
248
249
250
251
252
253
229
230
231
232
233
234
235

236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438







-
+










+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+







**
** Note that entries are added in order of increasing K.  Hence, one
** reader might be using some value K0 and a second reader that started
** at a later time (after additional transactions were added to the WAL
** and to the wal-index) might be using a different value K1, where K1>K0.
** Both readers can use the same hash table and mapping section to get
** the correct result.  There may be entries in the hash table with
** K>K0 but to the first reader, those entries will appear to be unused
** K>K0, but to the first reader those entries will appear to be unused
** slots in the hash table and so the first reader will get an answer as
** if no values greater than K0 had ever been inserted into the hash table
** in the first place - which is what reader one wants.  Meanwhile, the
** second reader using K1 will see additional values that were inserted
** later, which is exactly what reader two wants.  
**
** When a rollback occurs, the value of K is decreased. Hash table entries
** that correspond to frames greater than the new K value are removed
** from the hash table at this point.
*/

/*
** WAL2 NOTES
**
** This file also contains the implementation of "wal2" mode - activated
** using "PRAGMA journal_mode = wal2". Wal2 mode is very similar to wal
** mode, except that it uses two wal files instead of one. Under some
** circumstances, wal2 mode provides more concurrency than legacy wal 
** mode.
**
** THE PROBLEM WAL2 SOLVES:
**
** In legacy wal mode, if a writer wishes to write to the database while
** a checkpoint is ongoing, it may append frames to the existing wal file.
** This means that after the checkpoint has finished, the wal file consists
** of a large block of checkpointed frames, followed by a block of
** uncheckpointed frames. In a deployment that features a high volume of
** write traffic, this may mean that the wal file is never completely
** checkpointed. And so grows indefinitely.
**
** An alternative is to use "PRAGMA wal_checkpoint=RESTART" or similar to
** force a complete checkpoint of the wal file. But this must:
**
**   1) Wait on all existing readers to finish,
**   2) Wait on any existing writer, and then block all new writers,
**   3) Do the checkpoint,
**   4) Wait on any new readers that started during steps 2 and 3. Writers
**      are still blocked during this step.
**
** This means that in order to avoid the wal file growing indefinitely 
** in a busy system, writers must periodically pause to allow a checkpoint
** to complete. In a system with long running readers, such pauses may be
** for a non-trivial amount of time.
**
** OVERVIEW OF SOLUTION
**
** Wal2 mode uses two wal files. After writers have grown the first wal 
** file to a pre-configured size, they begin appending transactions to 
** the second wal file. Once all existing readers are reading snapshots
** new enough to include the entire first wal file, a checkpointer can
** checkpoint it.
**
** Meanwhile, writers are writing transactions to the second wal file.
** Once that wal file has grown larger than the pre-configured size, each
** new writer checks if:
**
**    * the first wal file has been checkpointed, and if so, if
**    * there are no readers still reading from the first wal file (once
**      it has been checkpointed, new readers read only from the second
**      wal file).
**
** If both these conditions are true, the writer may switch back to the
** first wal file. Eventually, a checkpointer can checkpoint the second
** wal file, and so on.
**
** The wal file that writers are currently appending to (the one they
** don't have to check the above two criteria before writing to) is called
** the "current" wal file.
**
** The first wal file takes the same name as the wal file in legacy wal
** mode systems - "<db>-wal". The second is named "<db>-wal2".

**
** CHECKPOINTS
**
** The "pre-configured size" mentioned above is the value set by 
** "PRAGMA journal_size_limit". Or, if journal_size_limit is not set, 
** 1000 pages.
**
** There is only a single type of checkpoint in wal2 mode (no "truncate",
** "restart" etc.), and it always checkpoints the entire contents of a single
** wal file. A wal file cannot be checkpointed until after a writer has written
** the first transaction into the other wal file and all readers are reading a
** snapshot that includes at least one transaction from the other wal file.
**
** The wal-hook, if one is registered, is invoked after a write-transaction
** is committed, just as it is in legacy wal mode. The integer parameter
** passed to the wal-hook is the total number of uncheckpointed frames in both
** wal files. Except, the parameter is set to zero if there is no frames 
** that may be checkpointed. This happens in two scenarios:
**
**   1. The "other" wal file (the one that the writer did not just append to)
**      is completely empty, or
**
**   2. The "other" wal file (the one that the writer did not just append to)
**      has already been checkpointed.
**
**
** WAL FILE FORMAT
**
** The file format used for each wal file in wal2 mode is the same as for
** legacy wal mode.  Except, the file format field is set to 3021000 
** instead of 3007000.
**
** WAL-INDEX FORMAT
**
** The wal-index format is also very similar. Even though there are two
** wal files, there is still a single wal-index shared-memory area (*-shm
** file with the default unix or win32 VFS). The wal-index header is the
** same size, with the following exceptions it has the same format:
**
**   * The version field is set to 3021000 instead of 3007000.
**
**   * An unused 32-bit field in the legacy wal-index header is
**     now used to store (a) a single bit indicating which of the
**     two wal files writers should append to and (b) the number
**     of frames in the second wal file (31 bits).
**
** The first hash table in the wal-index contains entries corresponding
** to the first HASHTABLE_NPAGE_ONE frames stored in the first wal file.
** The second hash table in the wal-index contains entries indexing the
** first HASHTABLE_NPAGE frames in the second wal file. The third hash
** table contains the next HASHTABLE_NPAGE frames in the first wal file,
** and so on.
**
** LOCKS
**
** Read-locks are simpler than for legacy wal mode. There are no locking
** slots that contain frame numbers. Instead, there are four distinct
** combinations of read locks a reader may hold:
**
**   WAL_LOCK_PART1:       "part" lock on first wal, none of second.
**   WAL_LOCK_PART1_FULL2: "part" lock on first wal, "full" of second.
**   WAL_LOCK_PART2: no lock on first wal, "part" lock on second.
**   WAL_LOCK_PART2_FULL1: "full" lock on first wal, "part" lock on second.
**
** When a reader reads the wal-index header as part of opening a read
** transaction, it takes a "part" lock on the current wal file. "Part" 
** because the wal file may grow while the read transaction is active, in 
** which case the reader would be reading only part of the wal file. 
** A part lock prevents a checkpointer from checkpointing the wal file 
** on which it is held.
**
** If there is data in the non-current wal file that has not been 
** checkpointed, the reader takes a "full" lock on that wal file. A 
** "full" lock indicates that the reader is using the entire wal file.
** A full lock prevents a writer from overwriting the wal file on which
** it is held, but does not prevent a checkpointer from checkpointing 
** it.
**
** There is still a single WRITER and a single CHECKPOINTER lock. The
** recovery procedure still takes the same exclusive lock on the entire
** range of SQLITE_SHM_NLOCK shm-locks. This works because the read-locks
** above use four of the six read-locking slots used by legacy wal mode.
**
** STARTUP/RECOVERY
**
** The read and write version fields of the database header in a wal2
** database are set to 0x03, instead of 0x02 as in legacy wal mode.
**
** The wal file format used in wal2 mode is the same as the format used
** in legacy wal mode. However, in order to support recovery, there are two
** differences in the way wal file header fields are populated, as follows:
**
**   * When the first wal file is first created, the "nCkpt" field in
**     the wal file header is set to 0. Thereafter, each time the writer
**     switches wal file, it sets the nCkpt field in the new wal file
**     header to ((nCkpt0 + 1) & 0x0F), where nCkpt0 is the value in
**     the previous wal file header. This means that the first wal file
**     always has an even value in the nCkpt field, and the second wal
**     file always has an odd value.
**
**   * When a writer switches wal file, it sets the salt values in the
**     new wal file to a copy of the checksum for the final frame in
**     the previous wal file.
**
** Recovery proceeds as follows:
**
** 1. Each wal file is recovered separately. Except, if the first wal 
**    file does not exist or is zero bytes in size, the second wal file
**    is truncated to zero bytes before it is "recovered".
**
** 2. If both wal files contain valid headers, then the nCkpt fields
**    are compared to see which of the two wal files is older. If the
**    salt keys in the second wal file match the final frame checksum 
**    in the older wal file, then both wal files are used. Otherwise,
**    the newer wal file is ignored.
**
** 3. Or, if only one or neither of the wal files has a valid header, 
**    then only a single or no wal files are recovered into the 
**    reconstructed wal-index.
**
** Refer to header comments for walIndexRecover() for further details.
*/

#ifndef SQLITE_OMIT_WAL

#include "wal.h"

/*
** Trace output macros
*/
267
268
269
270
271
272
273
274
275
276
277
278
279






280
281
282


283
284

285
286
287


288
289
290
291
292
293
294
452
453
454
455
456
457
458






459
460
461
462
463
464
465


466
467


468
469


470
471
472
473
474
475
476
477
478







-
-
-
-
-
-
+
+
+
+
+
+

-
-
+
+
-
-
+

-
-
+
+







# define AtomicStore(PTR,VAL)  __atomic_store_n((PTR),(VAL),__ATOMIC_RELAXED)
#else
# define AtomicLoad(PTR)       (*(PTR))
# define AtomicStore(PTR,VAL)  (*(PTR) = (VAL))
#endif

/*
** The maximum (and only) versions of the wal and wal-index formats
** that may be interpreted by this version of SQLite.
**
** If a client begins recovering a WAL file and finds that (a) the checksum
** values in the wal-header are correct and (b) the version field is not
** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
** Both the wal-file and the wal-index contain version fields 
** indicating the current version of the system. If a client
** reads the header of a wal file (as part of recovery), or the
** wal-index (as part of opening a read transaction) and (a) the
** header checksum is correct but (b) the version field is not
** recognized, the operation fails with SQLITE_CANTOPEN.
**
** Similarly, if a client successfully reads a wal-index header (i.e. the 
** checksum test is successful) and finds that the version field is not
** Currently, clients support both version-1 ("journal_mode=wal") and
** version-2 ("journal_mode=wal2"). Legacy clients may support version-1
** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
** returns SQLITE_CANTOPEN.
** only.
*/
#define WAL_MAX_VERSION      3007000
#define WALINDEX_MAX_VERSION 3007000
#define WAL_VERSION1 3007000      /* For "journal_mode=wal" */
#define WAL_VERSION2 3021000      /* For "journal_mode=wal2" */

/*
** Index numbers for various locking bytes.   WAL_NREADER is the number
** of available reader locks and should be at least 3.  The default
** is SQLITE_SHM_NLOCK==8 and  WAL_NREADER==5.
**
** Technically, the various VFSes are free to implement these locks however
303
304
305
306
307
308
309

































310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328






329
330
331
332

333
334
335
336
337

338
339
340
341
342
343





































344
345
346
347
348
349
350
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554

555
556
557
558
559

560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610







+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+



















+
+
+
+
+
+



-
+




-
+






+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+







#define WAL_WRITE_LOCK         0
#define WAL_ALL_BUT_WRITE      1
#define WAL_CKPT_LOCK          1
#define WAL_RECOVER_LOCK       2
#define WAL_READ_LOCK(I)       (3+(I))
#define WAL_NREADER            (SQLITE_SHM_NLOCK-3)

/*
** Values that may be stored in Wal.readLock in wal2 mode.
**
** In wal mode, the Wal.readLock member is set to -1 when no read-lock
** is held, or else is the index of the read-mark on which a lock is
** held.
**
** In wal2 mode, a value of -1 still indicates that no read-lock is held.
** And a non-zero value still represents the index of the read-mark on
** which a lock is held. There are two differences:
**
**   1. wal2 mode never uses read-mark 0.
**
**   2. locks on each read-mark have a different interpretation, as 
**      indicated by the symbolic names below.
*/
#define WAL_LOCK_NONE        -1
#define WAL_LOCK_PART1        1
#define WAL_LOCK_PART1_FULL2  2
#define WAL_LOCK_PART2_FULL1  3
#define WAL_LOCK_PART2        4

/* 
** This constant is used in wal2 mode only.
**
** In wal2 mode, when committing a transaction, if the current wal file 
** is sufficiently large and there are no conflicting locks held, the
** writer writes the new transaction into the start of the other wal
** file. Usually, "sufficiently large" is defined by the value configured
** using "PRAGMA journal_size_limit". However, if no such value has been
** configured, sufficiently large defaults to WAL_DEFAULT_WALSIZE frames.
*/
#define WAL_DEFAULT_WALSIZE 1000

/* Object declarations */
typedef struct WalIndexHdr WalIndexHdr;
typedef struct WalIterator WalIterator;
typedef struct WalCkptInfo WalCkptInfo;


/*
** The following object holds a copy of the wal-index header content.
**
** The actual header in the wal-index consists of two copies of this
** object followed by one instance of the WalCkptInfo object.
** For all versions of SQLite through 3.10.0 and probably beyond,
** the locking bytes (WalCkptInfo.aLock) start at offset 120 and
** the total header size is 136 bytes.
**
** The szPage value can be any power of 2 between 512 and 32768, inclusive.
** Or it can be 1 to represent a 65536-byte page.  The latter case was
** added in 3.7.1 when support for 64K pages was added.  
**
** WAL2 mode notes: Member variable mxFrame2 is only used in wal2 mode
** (when iVersion is set to WAL_VERSION2). The lower 31 bits store
** the maximum frame number in file *-wal2. The most significant bit
** is a flag - set if clients are currently appending to *-wal2, clear
** otherwise.
*/
struct WalIndexHdr {
  u32 iVersion;                   /* Wal-index version */
  u32 unused;                     /* Unused (padding) field */
  u32 mxFrame2;                   /* See "WAL2 mode notes" above */
  u32 iChange;                    /* Counter incremented each transaction */
  u8 isInit;                      /* 1 when initialized */
  u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
  u16 szPage;                     /* Database page size in bytes. 1==64K */
  u32 mxFrame;                    /* Index of last valid frame in the WAL */
  u32 mxFrame;                    /* Index of last valid frame in each WAL */
  u32 nPage;                      /* Size of database in pages */
  u32 aFrameCksum[2];             /* Checksum of last frame in log */
  u32 aSalt[2];                   /* Two salt values copied from WAL header */
  u32 aCksum[2];                  /* Checksum over all prior fields */
};

/*
** The following macros and functions are get/set methods for the maximum
** frame numbers and current wal file values stored in the WalIndexHdr
** structure. These are helpful because of the unorthodox way in which
** the values are stored in wal2 mode (see above). They are equivalent
** to functions with the following signatures.
**
**   u32  walidxGetMxFrame(WalIndexHdr*, int iWal);          // get mxFrame
**   void walidxSetMxFrame(WalIndexHdr*, int iWal, u32 val); // set mxFrame
**   int  walidxGetFile(WalIndexHdr*)                        // get file
**   void walidxSetFile(WalIndexHdr*, int val);              // set file
*/
#define walidxGetMxFrame(pHdr, iWal) \
  ((iWal) ? ((pHdr)->mxFrame2 & 0x7FFFFFFF) : (pHdr)->mxFrame)

static void walidxSetMxFrame(WalIndexHdr *pHdr, int iWal, u32 mxFrame){
  if( iWal ){
    pHdr->mxFrame2 = (pHdr->mxFrame2 & 0x80000000) | mxFrame;
  }else{
    pHdr->mxFrame = mxFrame;
  }
  assert( walidxGetMxFrame(pHdr, iWal)==mxFrame );
}

#define walidxGetFile(pHdr) ((pHdr)->mxFrame2 >> 31)

#define walidxSetFile(pHdr, iWal) (                                   \
    (pHdr)->mxFrame2 = ((pHdr)->mxFrame2 & 0x7FFFFFFF) | ((iWal)<<31) \
)

/*
** Argument is a pointer to a Wal structure. Return true if the current
** cache of the wal-index header indicates "journal_mode=wal2" mode, or
** false otherwise.
*/
#define isWalMode2(pWal) ((pWal)->hdr.iVersion==WAL_VERSION2)

/*
** A copy of the following object occurs in the wal-index immediately
** following the second copy of the WalIndexHdr.  This object stores
** information used by checkpoint.
**
** nBackfill is the number of frames in the WAL that have been written
** back into the database. (We call the act of moving content from WAL to
447
448
449
450
451
452
453
454

455
456
457
458
459
460
461
707
708
709
710
711
712
713

714
715
716
717
718
719
720
721







-
+







/*
** An open write-ahead log file is represented by an instance of the
** following object.
*/
struct Wal {
  sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */
  sqlite3_file *pDbFd;       /* File handle for the database file */
  sqlite3_file *pWalFd;      /* File handle for WAL file */
  sqlite3_file *apWalFd[2];  /* File handle for "*-wal" and "*-wal2" */
  u32 iCallback;             /* Value to pass to log callback (or 0) */
  i64 mxWalSize;             /* Truncate WAL to this size upon reset */
  int nWiData;               /* Size of array apWiData */
  int szFirstBlock;          /* Size of first block written to WAL file */
  volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
  u32 szPage;                /* Database page size */
  i16 readLock;              /* Which read lock is being held.  -1 for none */
469
470
471
472
473
474
475

476
477
478
479
480
481
482

483
484
485
486
487
488
489
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751







+







+







  u8 padToSectorBoundary;    /* Pad transactions out to the next sector */
  u8 bShmUnreliable;         /* SHM content is read-only and unreliable */
  WalIndexHdr hdr;           /* Wal-index header for current transaction */
  u32 minFrame;              /* Ignore wal frames before this one */
  u32 iReCksum;              /* On commit, recalculate checksums from here */
  u32 nPriorFrame;           /* For sqlite3WalInfo() */
  const char *zWalName;      /* Name of WAL file */
  char *zWalName2;           /* Name of second WAL file */
  u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
#ifdef SQLITE_DEBUG
  u8 lockError;              /* True if a locking error has occurred */
#endif
#ifdef SQLITE_ENABLE_SNAPSHOT
  WalIndexHdr *pSnapshot;    /* Start transaction here if not NULL */
#endif
  int bWal2;                 /* bWal2 flag passed to WalOpen() */
};

/*
** Candidate values for Wal.exclusiveMode.
*/
#define WAL_NORMAL_MODE     0
#define WAL_EXCLUSIVE_MODE  1     
711
712
713
714
715
716
717
718

719
720
721
722
723
724
725
973
974
975
976
977
978
979

980
981
982
983
984
985
986
987







-
+







*/
static void walIndexWriteHdr(Wal *pWal){
  volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
  const int nCksum = offsetof(WalIndexHdr, aCksum);

  assert( pWal->writeLock );
  pWal->hdr.isInit = 1;
  pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
  assert( pWal->hdr.iVersion==WAL_VERSION1||pWal->hdr.iVersion==WAL_VERSION2 );
  walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
  memcpy((void*)&aHdr[1], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
  walShmBarrier(pWal);
  memcpy((void*)&aHdr[0], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
}

/*
789
790
791
792
793
794
795
796

797
798
799
800
801
802
803
1051
1052
1053
1054
1055
1056
1057

1058
1059
1060
1061
1062
1063
1064
1065







-
+







  */
  pgno = sqlite3Get4byte(&aFrame[0]);
  if( pgno==0 ){
    return 0;
  }

  /* A frame is only valid if a checksum of the WAL header,
  ** all prior frams, the first 16 bytes of this frame-header, 
  ** all prior frames, the first 16 bytes of this frame-header, 
  ** and the frame-data matches the checksum in the last 8 
  ** bytes of this frame-header.
  */
  nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  if( aCksum[0]!=sqlite3Get4byte(&aFrame[16]) 
937
938
939
940
941
942
943
































944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
















961
962
963
964
965
966
967
968
969
970
971




972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989


990








991
992
993
994



995
996

997
998
999

1000
1001
1002
1003
1004



1005
1006
1007
1008
1009

1010
1011
1012
1013
1014
1015
1016
1017
1018

1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045

1046
1047

1048
1049









1050
1051
1052
1053
1054
1055
1056
1057
1058
1059

1060
1061
1062
1063
1064
1065
1066
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315



1316
1317
1318
1319

1320
1321
1322

1323





1324
1325
1326
1327
1328
1329
1330

1331
1332
1333
1334
1335
1336
1337
1338
1339

1340

1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360

1361
1362
1363
1364

1365
1366
1367
1368


1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386

1387
1388
1389
1390
1391
1392
1393
1394







+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

















+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+











+
+
+
+


















+
+

+
+
+
+
+
+
+
+

-
-
-
+
+
+

-
+


-
+
-
-
-
-
-
+
+
+




-
+








-
+
-




















-




-
+


+
-
-
+
+
+
+
+
+
+
+
+









-
+







    }else{
      pLoc->iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
    }
    pLoc->aPgno = &pLoc->aPgno[-1];
  }
  return rc;
}

static u32 walExternalEncode(int iWal, u32 iFrame){
  u32 iRet;
  if( iWal ){
    iRet = HASHTABLE_NPAGE_ONE + iFrame;
    iRet += ((iFrame-1) / HASHTABLE_NPAGE) * HASHTABLE_NPAGE;
  }else{
    iRet = iFrame;
    iFrame += HASHTABLE_NPAGE - HASHTABLE_NPAGE_ONE;
    iRet += ((iFrame-1) / HASHTABLE_NPAGE) * HASHTABLE_NPAGE;
  }
  return iRet;
}

/*
** Parameter iExternal is an external frame identifier. This function
** transforms it to a wal file number (0 or 1) and frame number within
** this wal file (reported via output parameter *piRead).
*/
static int walExternalDecode(u32 iExternal, u32 *piRead){
  int iHash = (iExternal+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1)/HASHTABLE_NPAGE;

  if( 0==(iHash & 0x01) ){
    /* A frame in wal file 0 */
    *piRead = (iExternal <= HASHTABLE_NPAGE_ONE) ? iExternal :
      iExternal - (iHash/2) * HASHTABLE_NPAGE;
    return 0;
  }

  *piRead = iExternal - HASHTABLE_NPAGE_ONE - ((iHash-1)/2) * HASHTABLE_NPAGE;
  return 1;
}

/*
** Return the number of the wal-index page that contains the hash-table
** and page-number array that contain entries corresponding to WAL frame
** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages 
** are numbered starting from 0.
*/
static int walFramePage(u32 iFrame){
  int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
  assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
       && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
       && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
       && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
       && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
  );
  return iHash;
}

/*
** Return the index of the hash-table corresponding to frame iFrame of wal
** file iWal.
*/
static int walFramePage2(int iWal, u32 iFrame){
  int iRet;
  assert( iWal==0 || iWal==1 );
  assert( iFrame>0 );
  if( iWal==0 ){
    iRet = 2*((iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1)/HASHTABLE_NPAGE);
  }else{
    iRet = 1 + 2 * ((iFrame-1) / HASHTABLE_NPAGE);
  }
  return iRet;
}

/*
** Return the page number associated with frame iFrame in this WAL.
*/
static u32 walFramePgno(Wal *pWal, u32 iFrame){
  int iHash = walFramePage(iFrame);
  if( iHash==0 ){
    return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
  }
  return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
}

static u32 walFramePgno2(Wal *pWal, int iWal, u32 iFrame){
  return walFramePgno(pWal, walExternalEncode(iWal, iFrame));
}

/*
** Remove entries from the hash table that point to WAL slots greater
** than pWal->hdr.mxFrame.
**
** This function is called whenever pWal->hdr.mxFrame is decreased due
** to a rollback or savepoint.
**
** At most only the hash table containing pWal->hdr.mxFrame needs to be
** updated.  Any later hash tables will be automatically cleared when
** pWal->hdr.mxFrame advances to the point where those hash tables are
** actually needed.
*/
static void walCleanupHash(Wal *pWal){
  WalHashLoc sLoc;                /* Hash table location */
  int iLimit = 0;                 /* Zero values greater than this */
  int nByte;                      /* Number of bytes to zero in aPgno[] */
  int i;                          /* Used to iterate through aHash[] */
  int iWal = walidxGetFile(&pWal->hdr);
  u32 mxFrame = walidxGetMxFrame(&pWal->hdr, iWal);

  u32 iExternal;
  if( isWalMode2(pWal) ){
    iExternal = walExternalEncode(iWal, mxFrame);
  }else{
    assert( iWal==0 );
    iExternal = mxFrame;
  }

  assert( pWal->writeLock );
  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
  testcase( mxFrame==HASHTABLE_NPAGE_ONE-1 );
  testcase( mxFrame==HASHTABLE_NPAGE_ONE );
  testcase( mxFrame==HASHTABLE_NPAGE_ONE+1 );

  if( pWal->hdr.mxFrame==0 ) return;
  if( mxFrame==0 ) return;

  /* Obtain pointers to the hash-table and page-number array containing 
  ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
  ** the entry that corresponds to frame pWal->hdr.mxFrame.  */
  ** that the page said hash-table and array reside on is already mapped.
  */
  assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
  assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
  walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &sLoc);
  assert( pWal->nWiData>walFramePage(iExternal) );
  assert( pWal->apWiData[walFramePage(iExternal)] );
  walHashGet(pWal, walFramePage(iExternal), &sLoc);

  /* Zero all hash-table entries that correspond to frame numbers greater
  ** than pWal->hdr.mxFrame.
  */
  iLimit = pWal->hdr.mxFrame - sLoc.iZero;
  iLimit = iExternal - sLoc.iZero;
  assert( iLimit>0 );
  for(i=0; i<HASHTABLE_NSLOT; i++){
    if( sLoc.aHash[i]>iLimit ){
      sLoc.aHash[i] = 0;
    }
  }
  
  /* Zero the entries in the aPgno array that correspond to frames with
  ** frame numbers greater than pWal->hdr.mxFrame. 
  ** frame numbers greater than pWal->hdr.mxFrame.  */
  */
  nByte = (int)((char *)sLoc.aHash - (char *)&sLoc.aPgno[iLimit+1]);
  memset((void *)&sLoc.aPgno[iLimit+1], 0, nByte);

#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  /* Verify that the every entry in the mapping region is still reachable
  ** via the hash table even after the cleanup.
  */
  if( iLimit ){
    int j;           /* Loop counter */
    int iKey;        /* Hash key */
    for(j=1; j<=iLimit; j++){
      for(iKey=walHash(sLoc.aPgno[j]);sLoc.aHash[iKey];iKey=walNextHash(iKey)){
        if( sLoc.aHash[iKey]==j ) break;
      }
      assert( sLoc.aHash[iKey]==j );
    }
  }
#endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
}


/*
** Set an entry in the wal-index that will map database page number
** pPage into WAL frame iFrame.
*/
static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
static int walIndexAppend(Wal *pWal, int iWal, u32 iFrame, u32 iPage){
  int rc;                         /* Return code */
  WalHashLoc sLoc;                /* Wal-index hash table location */
  u32 iExternal;

  rc = walHashGet(pWal, walFramePage(iFrame), &sLoc);
  
  if( isWalMode2(pWal) ){
    iExternal = walExternalEncode(iWal, iFrame);
  }else{
    assert( iWal==0 );
    iExternal = iFrame;
  }

  rc = walHashGet(pWal, walFramePage(iExternal), &sLoc);

  /* Assuming the wal-index file was successfully mapped, populate the
  ** page number array and hash table entry.
  */
  if( rc==SQLITE_OK ){
    int iKey;                     /* Hash table key */
    int idx;                      /* Value to write to hash-table slot */
    int nCollide;                 /* Number of hash collisions */

    idx = iFrame - sLoc.iZero;
    idx = iExternal - sLoc.iZero;
    assert( idx <= HASHTABLE_NSLOT/2 + 1 );
    
    /* If this is the first entry to be added to this hash-table, zero the
    ** entire hash table and aPgno[] array before proceeding. 
    */
    if( idx==1 ){
      int nByte = (int)((u8 *)&sLoc.aHash[HASHTABLE_NSLOT]
1117
1118
1119
1120
1121
1122
1123














































































































































1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139




1140
1141
1142
1143
1144
1145
1146
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606


1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618







+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+













-
-

+
+
+
+







#endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  }


  return rc;
}

/*
** Recover a single wal file - *-wal if iWal==0, or *-wal2 if iWal==1.
*/
static int walIndexRecoverOne(Wal *pWal, int iWal, u32 *pnCkpt, int *pbZero){
  i64 nSize;                      /* Size of log file */
  u32 aFrameCksum[2] = {0, 0};
  int rc;
  sqlite3_file *pWalFd = pWal->apWalFd[iWal];

  assert( iWal==0 || iWal==1 );

  memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  sqlite3_randomness(8, pWal->hdr.aSalt);

  rc = sqlite3OsFileSize(pWalFd, &nSize);
  if( rc==SQLITE_OK ){
    if( nSize>WAL_HDRSIZE ){
      u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
      u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
      int szFrame;                  /* Number of bytes in buffer aFrame[] */
      u8 *aData;                    /* Pointer to data part of aFrame buffer */
      int iFrame;                   /* Index of last frame read */
      i64 iOffset;                  /* Next offset to read from log file */
      int szPage;                   /* Page size according to the log */
      u32 magic;                    /* Magic value read from WAL header */
      u32 version;                  /* Magic value read from WAL header */
      int isValid;                  /* True if this frame is valid */
  
      /* Read in the WAL header. */
      rc = sqlite3OsRead(pWalFd, aBuf, WAL_HDRSIZE, 0);
      if( rc!=SQLITE_OK ){
        return rc;
      }
  
      /* If the database page size is not a power of two, or is greater than
      ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid 
      ** data. Similarly, if the 'magic' value is invalid, ignore the whole
      ** WAL file.
      */
      magic = sqlite3Get4byte(&aBuf[0]);
      szPage = sqlite3Get4byte(&aBuf[8]);
      if( (magic&0xFFFFFFFE)!=WAL_MAGIC 
       || szPage&(szPage-1) 
       || szPage>SQLITE_MAX_PAGE_SIZE 
       || szPage<512 
      ){
        return SQLITE_OK;
      }
      pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
      pWal->szPage = szPage;
  
      /* Verify that the WAL header checksum is correct */
      walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN, 
          aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
      );
      if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
       || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
      ){
        return SQLITE_OK;
      }
  
      memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
      *pnCkpt = sqlite3Get4byte(&aBuf[12]);
  
      /* Verify that the version number on the WAL format is one that
      ** are able to understand */
      version = sqlite3Get4byte(&aBuf[4]);
      if( version!=WAL_VERSION1 && version!=WAL_VERSION2 ){
        return SQLITE_CANTOPEN_BKPT;
      }
      pWal->hdr.iVersion = version;
  
      /* Malloc a buffer to read frames into. */
      szFrame = szPage + WAL_FRAME_HDRSIZE;
      aFrame = (u8 *)sqlite3_malloc64(szFrame);
      if( !aFrame ){
        return SQLITE_NOMEM_BKPT;
      }
      aData = &aFrame[WAL_FRAME_HDRSIZE];
  
      /* Read all frames from the log file. */
      iFrame = 0;
      for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
        u32 pgno;                   /* Database page number for frame */
        u32 nTruncate;              /* dbsize field from frame header */
  
        /* Read and decode the next log frame. */
        iFrame++;
        rc = sqlite3OsRead(pWalFd, aFrame, szFrame, iOffset);
        if( rc!=SQLITE_OK ) break;
        isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
        if( !isValid ) break;
        rc = walIndexAppend(pWal, iWal, iFrame, pgno);
        if( rc!=SQLITE_OK ) break;
  
        /* If nTruncate is non-zero, this is a commit record. */
        if( nTruncate ){
          pWal->hdr.mxFrame = iFrame;
          pWal->hdr.nPage = nTruncate;
          pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
          testcase( szPage<=32768 );
          testcase( szPage>=65536 );
          aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
          aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
        }
      }
  
      sqlite3_free(aFrame);
    }else if( pbZero ){
      *pbZero = 1;
    }
  }

  pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
  pWal->hdr.aFrameCksum[1] = aFrameCksum[1];

  return rc;
}

static int walOpenWal2(Wal *pWal){
  int rc = SQLITE_OK;
  if( !isOpen(pWal->apWalFd[1]) ){
    int f = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
    rc = sqlite3OsOpen(pWal->pVfs, pWal->zWalName2, pWal->apWalFd[1], f, &f);
  }
  return rc;
}

static int walTruncateWal2(Wal *pWal){
  int bIs;
  int rc;
  assert( !isOpen(pWal->apWalFd[1]) );
  rc = sqlite3OsAccess(pWal->pVfs, pWal->zWalName2, SQLITE_ACCESS_EXISTS, &bIs);
  if( rc==SQLITE_OK && bIs ){
    rc = walOpenWal2(pWal);
    if( rc==SQLITE_OK ){
      rc = sqlite3OsTruncate(pWal->apWalFd[1], 0);
      sqlite3OsClose(pWal->apWalFd[1]);
    }
  }
  return rc;
}

/*
** Recover the wal-index by reading the write-ahead log file. 
**
** This routine first tries to establish an exclusive lock on the
** wal-index to prevent other threads/processes from doing anything
** with the WAL or wal-index while recovery is running.  The
** WAL_RECOVER_LOCK is also held so that other threads will know
** that this thread is running recovery.  If unable to establish
** the necessary locks, this routine returns SQLITE_BUSY.
*/
static int walIndexRecover(Wal *pWal){
  int rc;                         /* Return Code */
  i64 nSize;                      /* Size of log file */
  u32 aFrameCksum[2] = {0, 0};
  int iLock;                      /* Lock offset to lock for checkpoint */
  u32 nCkpt1 = 0xFFFFFFFF;
  u32 nCkpt2 = 0xFFFFFFFF;
  int bZero = 0;
  WalIndexHdr hdr;

  /* Obtain an exclusive lock on all byte in the locking range not already
  ** locked by the caller. The caller is guaranteed to have locked the
  ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
  ** If successful, the same bytes that are locked here are concurrent before
  ** this function returns.
  */
1158
1159
1160
1161
1162
1163
1164
1165
1166


1167
1168
1169



1170
1171

1172
1173
1174
1175

1176
1177
1178
1179
1180
1181





1182
1183

1184
1185
1186
1187
1188
1189

1190
1191
1192
1193
1194



1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205

1206
1207
1208


1209
1210
1211
1212


1213
1214
1215
1216
1217
1218

1219
1220
1221
1222
1223

1224
1225
1226


1227
1228
1229
1230



1231
1232
1233
1234
1235

1236
1237
1238
1239
1240
1241

1242
1243
1244
1245

1246
1247
1248
1249


1250
1251
1252
1253
1254


1255
1256
1257
1258
1259
1260
1261
1262

1263
1264

1265
1266
1267
1268
1269
1270
1271










































1272
1273
1274
1275
1276

1277
1278
1279
1280
1281
1282
1283








1284
1285
1286
1287
1288

1289
1290

1291
1292
1293
1294











1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306

1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318


1319
1320
1321
1322
1323
1324
1325
1630
1631
1632
1633
1634
1635
1636


1637
1638



1639
1640
1641


1642




1643






1644
1645
1646
1647
1648


1649






1650





1651
1652
1653











1654



1655
1656




1657
1658






1659





1660



1661
1662




1663
1664
1665





1666






1667




1668




1669
1670





1671
1672





1673
1674

1675


1676


1677
1678



1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724

1725

1726





1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738

1739

1740
1741




1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755

1756
1757
1758
1759
1760
1761
1762

1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784







-
-
+
+
-
-
-
+
+
+
-
-
+
-
-
-
-
+
-
-
-
-
-
-
+
+
+
+
+
-
-
+
-
-
-
-
-
-
+
-
-
-
-
-
+
+
+
-
-
-
-
-
-
-
-
-
-
-
+
-
-
-
+
+
-
-
-
-
+
+
-
-
-
-
-
-
+
-
-
-
-
-
+
-
-
-
+
+
-
-
-
-
+
+
+
-
-
-
-
-
+
-
-
-
-
-
-
+
-
-
-
-
+
-
-
-
-
+
+
-
-
-
-
-
+
+
-
-
-
-
-


-
+
-
-
+
-
-


-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+




-
+
-

-
-
-
-
-
+
+
+
+
+
+
+
+




-
+
-

+
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+



-







-
+












+
+







  }
  if( rc ){
    return rc;
  }

  WALTRACE(("WAL%p: recovery begin...\n", pWal));

  memset(&pWal->hdr, 0, sizeof(WalIndexHdr));

  /* Recover the *-wal file. If a valid version-1 header is recovered
  ** from it, do not open the *-wal2 file. Even if it exists.
  rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
  if( rc!=SQLITE_OK ){
    goto recovery_error;
  **
  ** Otherwise, if the *-wal2 file exists or if the "wal2" flag was 
  ** specified when sqlite3WalOpen() was called, open and recover
  }

  ** the *-wal2 file. Except, if the *-wal file was zero bytes in size,
  if( nSize>WAL_HDRSIZE ){
    u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
    u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
    int szFrame;                  /* Number of bytes in buffer aFrame[] */
  ** truncate the *-wal2 to zero bytes in size.
    u8 *aData;                    /* Pointer to data part of aFrame buffer */
    int iFrame;                   /* Index of last frame read */
    i64 iOffset;                  /* Next offset to read from log file */
    int szPage;                   /* Page size according to the log */
    u32 magic;                    /* Magic value read from WAL header */
    u32 version;                  /* Magic value read from WAL header */
  **
  ** After this block has run, if the *-wal2 file is open the system
  ** starts up in VERSION2 mode. In this case pWal->hdr contains the 
  ** wal-index header considering only *-wal2. Stack variable hdr
  ** contains the wal-index header considering only *-wal. The hash 
    int isValid;                  /* True if this frame is valid */

  ** tables are populated for both.  
    /* Read in the WAL header. */
    rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
    if( rc!=SQLITE_OK ){
      goto recovery_error;
    }

  **
    /* If the database page size is not a power of two, or is greater than
    ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid 
    ** data. Similarly, if the 'magic' value is invalid, ignore the whole
    ** WAL file.
    */
  ** Or, if the *-wal2 file is not open, start up in VERSION1 mode.
  ** pWal->hdr is already populated.
  */
    magic = sqlite3Get4byte(&aBuf[0]);
    szPage = sqlite3Get4byte(&aBuf[8]);
    if( (magic&0xFFFFFFFE)!=WAL_MAGIC 
     || szPage&(szPage-1) 
     || szPage>SQLITE_MAX_PAGE_SIZE 
     || szPage<512 
    ){
      goto finished;
    }
    pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
    pWal->szPage = szPage;
  rc = walIndexRecoverOne(pWal, 0, &nCkpt1, &bZero);
    pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
    memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);

  assert( pWal->hdr.iVersion==0 
      || pWal->hdr.iVersion==WAL_VERSION1 
    /* Verify that the WAL header checksum is correct */
    walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN, 
        aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
    );
      || pWal->hdr.iVersion==WAL_VERSION2 
  );
    if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
     || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
    ){
      goto finished;
    }

  if( rc==SQLITE_OK && bZero ){
    /* Verify that the version number on the WAL format is one that
    ** are able to understand */
    version = sqlite3Get4byte(&aBuf[4]);
    if( version!=WAL_MAX_VERSION ){
      rc = SQLITE_CANTOPEN_BKPT;
    rc = walTruncateWal2(pWal);
      goto finished;
    }

  }
  if( rc==SQLITE_OK && pWal->hdr.iVersion!=WAL_VERSION1 ){
    /* Malloc a buffer to read frames into. */
    szFrame = szPage + WAL_FRAME_HDRSIZE;
    aFrame = (u8 *)sqlite3_malloc64(szFrame);
    if( !aFrame ){
    int bOpen = 1;
    sqlite3_vfs *pVfs = pWal->pVfs;
    if( pWal->hdr.iVersion==0 && pWal->bWal2==0 ){
      rc = SQLITE_NOMEM_BKPT;
      goto recovery_error;
    }
    aData = &aFrame[WAL_FRAME_HDRSIZE];

      rc = sqlite3OsAccess(pVfs, pWal->zWalName2, SQLITE_ACCESS_EXISTS, &bOpen);
    /* Read all frames from the log file. */
    iFrame = 0;
    for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
      u32 pgno;                   /* Database page number for frame */
      u32 nTruncate;              /* dbsize field from frame header */

    }
      /* Read and decode the next log frame. */
      iFrame++;
      rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
      if( rc!=SQLITE_OK ) break;
    if( rc==SQLITE_OK && bOpen ){
      isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
      if( !isValid ) break;
      rc = walIndexAppend(pWal, iFrame, pgno);
      if( rc!=SQLITE_OK ) break;
      rc = walOpenWal2(pWal);
      if( rc==SQLITE_OK ){

      /* If nTruncate is non-zero, this is a commit record. */
      if( nTruncate ){
        pWal->hdr.mxFrame = iFrame;
        pWal->hdr.nPage = nTruncate;
        hdr = pWal->hdr;
        rc = walIndexRecoverOne(pWal, 1, &nCkpt2, 0);
        pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
        testcase( szPage<=32768 );
        testcase( szPage>=65536 );
        aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
        aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
      }
    }

  }
    sqlite3_free(aFrame);
  }


finished:
  if( rc==SQLITE_OK ){
    volatile WalCkptInfo *pInfo;
    int i;
    pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
    pWal->hdr.aFrameCksum[1] = aFrameCksum[1];

    if( isOpen(pWal->apWalFd[1]) ){
      /* The case where *-wal2 may follow *-wal */
      if( nCkpt2<=0x0F && nCkpt2==nCkpt1+1 ){
        if( sqlite3Get4byte((u8*)(&pWal->hdr.aSalt[0]))==hdr.aFrameCksum[0]
         && sqlite3Get4byte((u8*)(&pWal->hdr.aSalt[1]))==hdr.aFrameCksum[1]
        ){
          walidxSetFile(&pWal->hdr, 1);
          walidxSetMxFrame(&pWal->hdr, 1, pWal->hdr.mxFrame);
          walidxSetMxFrame(&pWal->hdr, 0, hdr.mxFrame);
        }else{
          pWal->hdr = hdr;
        }
      }else

      /* When *-wal may follow *-wal2 */
      if( (nCkpt2==0x0F && nCkpt1==0) || (nCkpt2<0x0F && nCkpt2==nCkpt1-1) ){
        if( sqlite3Get4byte((u8*)(&hdr.aSalt[0]))==pWal->hdr.aFrameCksum[0]
         && sqlite3Get4byte((u8*)(&hdr.aSalt[1]))==pWal->hdr.aFrameCksum[1]
        ){
          SWAP(WalIndexHdr, pWal->hdr, hdr);
          walidxSetMxFrame(&pWal->hdr, 1, hdr.mxFrame);
        }else{
          walidxSetFile(&pWal->hdr, 1);
          walidxSetMxFrame(&pWal->hdr, 1, pWal->hdr.mxFrame);
          walidxSetMxFrame(&pWal->hdr, 0, 0);
        }
      }else

      /* Fallback */
      if( nCkpt1<=nCkpt2 ){
        pWal->hdr = hdr;
      }else{
        walidxSetFile(&pWal->hdr, 1);
        walidxSetMxFrame(&pWal->hdr, 1, pWal->hdr.mxFrame);
        walidxSetMxFrame(&pWal->hdr, 0, 0);
      }
      pWal->hdr.iVersion = WAL_VERSION2;
    }else{
      pWal->hdr.iVersion = WAL_VERSION1;
    }

    walIndexWriteHdr(pWal);

    /* Reset the checkpoint-header. This is safe because this thread is 
    ** currently holding locks that exclude all other readers, writers and
    ** checkpointers.
    ** checkpointers.  */
    */
    pInfo = walCkptInfo(pWal);
    pInfo->nBackfill = 0;
    pInfo->nBackfillAttempted = pWal->hdr.mxFrame;
    pInfo->aReadMark[0] = 0;
    for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
    if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
    memset((void*)pInfo, 0, sizeof(WalCkptInfo));
    if( 0==isWalMode2(pWal) ){
      int i;
      pInfo->nBackfillAttempted = pWal->hdr.mxFrame;
      pInfo->aReadMark[0] = 0;
      for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
      if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
    }

    /* If more than one frame was recovered from the log file, report an
    ** event via sqlite3_log(). This is to help with identifying performance
    ** problems caused by applications routinely shutting down without
    ** checkpointing the log file.
    ** checkpointing the log file.  */
    */
    if( pWal->hdr.nPage ){
      if( isWalMode2(pWal) ){
      sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
          "recovered %d frames from WAL file %s",
          pWal->hdr.mxFrame, pWal->zWalName
      );
        sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
            "recovered (%d,%d) frames from WAL files %s[2] (wal2 mode)",
            walidxGetMxFrame(&pWal->hdr, 0), walidxGetMxFrame(&pWal->hdr, 1), 
            pWal->zWalName
        );
      }else{
        sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
            "recovered %d frames from WAL file %s",
            pWal->hdr.mxFrame, pWal->zWalName
        );
      }
    }
  }

recovery_error:
  WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
  walUnlockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock);
  walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  return rc;
}

/*
** Close an open wal-index.
** Close an open wal-index and wal files.
*/
static void walIndexClose(Wal *pWal, int isDelete){
  if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE || pWal->bShmUnreliable ){
    int i;
    for(i=0; i<pWal->nWiData; i++){
      sqlite3_free((void *)pWal->apWiData[i]);
      pWal->apWiData[i] = 0;
    }
  }
  if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
    sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
  }
  sqlite3OsClose(pWal->apWalFd[0]);
  sqlite3OsClose(pWal->apWalFd[1]);
}

/* 
** Open a connection to the WAL file zWalName. The database file must 
** already be opened on connection pDbFd. The buffer that zWalName points
** to must remain valid for the lifetime of the returned Wal* handle.
**
1335
1336
1337
1338
1339
1340
1341

1342
1343
1344
1345
1346


1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365


1366
1367
1368
1369

1370
1371
1372
1373
1374
1375


1376
1377

1378
1379
1380
1381
1382

1383





1384

1385
1386

1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832

1833
1834
1835
1836
1837
1838

1839
1840
1841

1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854

1855
1856

1857
1858
1859
1860
1861
1862
1863

1864
1865
1866
1867
1868
1869
1870







+





+
+



















+
+



-
+





-
+
+

-
+





+

+
+
+
+
+
-
+

-
+






-







*/
int sqlite3WalOpen(
  sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */
  sqlite3_file *pDbFd,            /* The open database file */
  const char *zWalName,           /* Name of the WAL file */
  int bNoShm,                     /* True to run in heap-memory mode */
  i64 mxWalSize,                  /* Truncate WAL to this size on reset */
  int bWal2,                      /* True to open in wal2 mode */
  Wal **ppWal                     /* OUT: Allocated Wal handle */
){
  int rc;                         /* Return Code */
  Wal *pRet;                      /* Object to allocate and return */
  int flags;                      /* Flags passed to OsOpen() */
  int nWalName;                   /* Length of zWalName in bytes */
  int nByte;                      /* Bytes of space to allocate */

  assert( zWalName && zWalName[0] );
  assert( pDbFd );

  /* In the amalgamation, the os_unix.c and os_win.c source files come before
  ** this source file.  Verify that the #defines of the locking byte offsets
  ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
  ** For that matter, if the lock offset ever changes from its initial design
  ** value of 120, we need to know that so there is an assert() to check it.
  */
  assert( 120==WALINDEX_LOCK_OFFSET );
  assert( 136==WALINDEX_HDR_SIZE );
#ifdef WIN_SHM_BASE
  assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
#endif
#ifdef UNIX_SHM_BASE
  assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
#endif

  nWalName = sqlite3Strlen30(zWalName);
  nByte = sizeof(Wal) + pVfs->szOsFile*2 + nWalName+2;

  /* Allocate an instance of struct Wal to return. */
  *ppWal = 0;
  pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
  pRet = (Wal*)sqlite3MallocZero(nByte);
  if( !pRet ){
    return SQLITE_NOMEM_BKPT;
  }

  pRet->pVfs = pVfs;
  pRet->pWalFd = (sqlite3_file *)&pRet[1];
  pRet->apWalFd[0] = (sqlite3_file*)((char*)pRet+sizeof(Wal));
  pRet->apWalFd[1] = (sqlite3_file*)((char*)pRet+sizeof(Wal)+pVfs->szOsFile);
  pRet->pDbFd = pDbFd;
  pRet->readLock = -1;
  pRet->readLock = WAL_LOCK_NONE;
  pRet->mxWalSize = mxWalSize;
  pRet->zWalName = zWalName;
  pRet->syncHeader = 1;
  pRet->padToSectorBoundary = 1;
  pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
  pRet->bWal2 = bWal2;

  pRet->zWalName2 = (char*)pRet + sizeof(Wal) + 2*pVfs->szOsFile;
  memcpy(pRet->zWalName2, zWalName, nWalName);
  pRet->zWalName2[nWalName] = '2';
  pRet->zWalName2[nWalName+1] = '\0';

  /* Open file handle on the write-ahead log file. */
  /* Open a file handle on the first write-ahead log file. */
  flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
  rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
  rc = sqlite3OsOpen(pVfs, zWalName, pRet->apWalFd[0], flags, &flags);
  if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
    pRet->readOnly = WAL_RDONLY;
  }

  if( rc!=SQLITE_OK ){
    walIndexClose(pRet, 0);
    sqlite3OsClose(pRet->pWalFd);
    sqlite3_free(pRet);
  }else{
    int iDC = sqlite3OsDeviceCharacteristics(pDbFd);
    if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
    if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
      pRet->padToSectorBoundary = 0;
    }
1596
1597
1598
1599
1600
1601
1602
1603

1604
1605
1606
1607
1608
1609



1610
1611
1612
1613
1614






1615
1616
1617
1618
1619

1620
1621




1622
1623
1624
1625

1626
1627
1628









1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651


1652
1653
1654
1655
1656
1657
1658

1659








1660
1661
1662


1663
1664
1665
1666
1667


1668
1669
1670
1671
1672
1673
1674
1675
1676





1677
1678
1679
1680
1681
1682
1683
2066
2067
2068
2069
2070
2071
2072

2073
2074
2075
2076



2077
2078
2079
2080
2081
2082
2083

2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106



2107
2108
2109
2110
2111
2112
2113
2114
2115
2116

2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136

2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156


2157
2158
2159
2160
2161


2162
2163
2164
2165
2166
2167





2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179







-
+



-
-
-
+
+
+




-
+
+
+
+
+
+





+


+
+
+
+




+
-
-
-
+
+
+
+
+
+
+
+
+

-




















-
+
+







+

+
+
+
+
+
+
+
+

-
-
+
+



-
-
+
+




-
-
-
-
-
+
+
+
+
+







*/
static void walIteratorFree(WalIterator *p){
  sqlite3_free(p);
}

/*
** Construct a WalInterator object that can be used to loop over all 
** pages in the WAL following frame nBackfill in ascending order. Frames
** pages in wal file iWal following frame nBackfill in ascending order. Frames
** nBackfill or earlier may be included - excluding them is an optimization
** only. The caller must hold the checkpoint lock.
**
** On success, make *pp point to the newly allocated WalInterator object
** return SQLITE_OK. Otherwise, return an error code. If this routine
** returns an error, the value of *pp is undefined.
** On success, make *pp point to the newly allocated WalIterator object
** and return SQLITE_OK. Otherwise, return an error code. If this routine
** returns an error, the final value of *pp is undefined.
**
** The calling routine should invoke walIteratorFree() to destroy the
** WalIterator object when it has finished with it.
*/
static int walIteratorInit(Wal *pWal, u32 nBackfill, WalIterator **pp){
static int walIteratorInit(
  Wal *pWal, 
  int iWal, 
  u32 nBackfill, 
  WalIterator **pp
){
  WalIterator *p;                 /* Return value */
  int nSegment;                   /* Number of segments to merge */
  u32 iLast;                      /* Last frame in log */
  int nByte;                      /* Number of bytes to allocate */
  int i;                          /* Iterator variable */
  int iLastSeg;                   /* Last hash table to iterate though */
  ht_slot *aTmp;                  /* Temp space used by merge-sort */
  int rc = SQLITE_OK;             /* Return Code */
  int iMode = isWalMode2(pWal) ? 2 : 1;

  assert( isWalMode2(pWal) || iWal==0 );
  assert( 0==isWalMode2(pWal) || nBackfill==0 );

  /* This routine only runs while holding the checkpoint lock. And
  ** it only runs if there is actually content in the log (mxFrame>0).
  */
  iLast = walidxGetMxFrame(&pWal->hdr, iWal);
  assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
  iLast = pWal->hdr.mxFrame;

  assert( pWal->ckptLock && iLast>0 );

  if( iMode==2 ){
    iLastSeg = walFramePage2(iWal, iLast);
  }else{
    iLastSeg = walFramePage(iLast);
  }
  nSegment = 1 + (iLastSeg/iMode);

  /* Allocate space for the WalIterator object. */
  nSegment = walFramePage(iLast) + 1;
  nByte = sizeof(WalIterator) 
        + (nSegment-1)*sizeof(struct WalSegment)
        + iLast*sizeof(ht_slot);
  p = (WalIterator *)sqlite3_malloc64(nByte);
  if( !p ){
    return SQLITE_NOMEM_BKPT;
  }
  memset(p, 0, nByte);
  p->nSegment = nSegment;

  /* Allocate temporary space used by the merge-sort routine. This block
  ** of memory will be freed before this function returns.
  */
  aTmp = (ht_slot *)sqlite3_malloc64(
      sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
  );
  if( !aTmp ){
    rc = SQLITE_NOMEM_BKPT;
  }

  for(i=walFramePage(nBackfill+1); rc==SQLITE_OK && i<nSegment; i++){
  i = iMode==2 ? iWal : walFramePage(nBackfill+1);
  for(; rc==SQLITE_OK && i<=iLastSeg; i+=iMode){
    WalHashLoc sLoc;

    rc = walHashGet(pWal, i, &sLoc);
    if( rc==SQLITE_OK ){
      int j;                      /* Counter variable */
      int nEntry;                 /* Number of entries in this segment */
      ht_slot *aIndex;            /* Sorted index for this segment */
      u32 iZero;

      if( iMode==2 ){
        walExternalDecode(sLoc.iZero+1, &iZero);
        iZero--;
        assert( iZero==0 || i>=2 );
      }else{
        iZero = sLoc.iZero;
      }

      sLoc.aPgno++;
      if( (i+1)==nSegment ){
        nEntry = (int)(iLast - sLoc.iZero);
      if( i==iLastSeg ){
        nEntry = (int)(iLast - iZero);
      }else{
        nEntry = (int)((u32*)sLoc.aHash - (u32*)sLoc.aPgno);
      }
      aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[sLoc.iZero];
      sLoc.iZero++;
      aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
      iZero++;
  
      for(j=0; j<nEntry; j++){
        aIndex[j] = (ht_slot)j;
      }
      walMergesort((u32 *)sLoc.aPgno, aTmp, aIndex, &nEntry);
      p->aSegment[i].iZero = sLoc.iZero;
      p->aSegment[i].nEntry = nEntry;
      p->aSegment[i].aIndex = aIndex;
      p->aSegment[i].aPgno = (u32 *)sLoc.aPgno;
      walMergesort((u32*)sLoc.aPgno, aTmp, aIndex, &nEntry);
      p->aSegment[i/iMode].iZero = iZero;
      p->aSegment[i/iMode].nEntry = nEntry;
      p->aSegment[i/iMode].aIndex = aIndex;
      p->aSegment[i/iMode].aPgno = (u32*)sLoc.aPgno;
    }
  }
  sqlite3_free(aTmp);

  if( rc!=SQLITE_OK ){
    walIteratorFree(p);
    p = 0;
1731
1732
1733
1734
1735
1736
1737

1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748






























































1749
1750
1751
1752
1753
1754
1755
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314







+











+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+







** new wal-index header. It should be passed a pseudo-random value (i.e. 
** one obtained from sqlite3_randomness()).
*/
static void walRestartHdr(Wal *pWal, u32 salt1){
  volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  int i;                          /* Loop counter */
  u32 *aSalt = pWal->hdr.aSalt;   /* Big-endian salt values */
  assert( isWalMode2(pWal)==0 );
  pWal->nCkpt++;
  pWal->hdr.mxFrame = 0;
  sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
  memcpy(&pWal->hdr.aSalt[1], &salt1, 4);
  walIndexWriteHdr(pWal);
  pInfo->nBackfill = 0;
  pInfo->nBackfillAttempted = 0;
  pInfo->aReadMark[1] = 0;
  for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  assert( pInfo->aReadMark[0]==0 );
}

/*
** This function is used in wal2 mode.
**
** This function is called when writer pWal is just about to start 
** writing out frames. Parameter iApp is the current wal file. The "other" wal
** file (wal file !iApp) has been fully checkpointed. This function returns
** SQLITE_OK if there are no readers preventing the writer from switching to
** the other wal file. Or SQLITE_BUSY if there are.
*/
static int wal2RestartOk(Wal *pWal, int iApp){
  /* The other wal file (wal file !iApp) can be overwritten if there
  ** are no readers reading from it - no "full" or "partial" locks.
  ** Technically speaking it is not possible for any reader to hold
  ** a "part" lock, as this would have prevented the file from being
  ** checkpointed. But checking anyway doesn't hurt. The following
  ** is equivalent to:
  **
  **   if( iApp==0 ) eLock = WAL_LOCK_PART1_FULL2;
  **   if( iApp==1 ) eLock = WAL_LOCK_PART1;
  */
  int eLock = 1 + (iApp==0);

  assert( WAL_LOCK_PART1==1 );
  assert( WAL_LOCK_PART1_FULL2==2 );
  assert( WAL_LOCK_PART2_FULL1==3 );
  assert( WAL_LOCK_PART2==4 );

  assert( iApp!=0 || eLock==WAL_LOCK_PART1_FULL2 );
  assert( iApp!=1 || eLock==WAL_LOCK_PART1 );

  return walLockExclusive(pWal, WAL_READ_LOCK(eLock), 3);
}
static void wal2RestartFinished(Wal *pWal, int iApp){
  walUnlockExclusive(pWal, WAL_READ_LOCK(1 + (iApp==0)), 3);
}

/*
** This function is used in wal2 mode.
**
** This function is called when a checkpointer wishes to checkpoint wal
** file iCkpt. It takes the required lock and, if successful, returns
** SQLITE_OK. Otherwise, an SQLite error code (e.g. SQLITE_BUSY). If this
** function returns SQLITE_OK, it is the responsibility of the caller
** to invoke wal2CheckpointFinished() to release the lock.
*/
static int wal2CheckpointOk(Wal *pWal, int iCkpt){
  int eLock = 1 + (iCkpt*2);

  assert( WAL_LOCK_PART1==1 );
  assert( WAL_LOCK_PART1_FULL2==2 );
  assert( WAL_LOCK_PART2_FULL1==3 );
  assert( WAL_LOCK_PART2==4 );

  assert( iCkpt!=0 || eLock==WAL_LOCK_PART1 );
  assert( iCkpt!=1 || eLock==WAL_LOCK_PART2_FULL1 );

  return walLockExclusive(pWal, WAL_READ_LOCK(eLock), 2);
}
static void wal2CheckpointFinished(Wal *pWal, int iCkpt){
  walUnlockExclusive(pWal, WAL_READ_LOCK(1 + (iCkpt*2)), 2);
}

/*
** Copy as much content as we can from the WAL back into the database file
** in response to an sqlite3_wal_checkpoint() request or the equivalent.
**
** The amount of information copies from WAL to database might be limited
** by active readers.  This routine will never overwrite a database page
1792
1793
1794
1795
1796
1797
1798


1799

1800
1801
1802
1803

1804












1805
1806
1807
1808
1809
1810
1811
1812
1813




1814

1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
























1838
1839
1840
1841
1842
1843
1844



1845
1846
1847
1848
1849
1850



1851
1852

1853
1854
1855
1856


1857
1858
1859

1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873

1874



1875
1876
1877
1878
1879

1880
1881
1882



1883
1884

1885
1886
1887
1888
1889
1890
1891
1892
1893
1894




1895
1896
1897

1898
1899
1900
1901
1902
1903
1904
1905








1906
1907

1908


1909
1910
1911
1912
1913
1914
1915

1916
1917
1918
1919
1920
1921
1922
1923

1924
1925
1926
1927
1928
1929
1930
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366

2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383




2384
2385
2386
2387
2388
2389























2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418


2419
2420
2421
2422
2423
2424



2425
2426
2427
2428
2429
2430
2431
2432


2433
2434
2435
2436

2437

2438
2439
2440
2441
2442
2443
2444
2445
2446

2447
2448
2449
2450

2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466

2467
2468
2469
2470
2471
2472
2473
2474



2475
2476
2477
2478
2479
2480
2481
2482








2483
2484
2485
2486
2487
2488
2489
2490

2491
2492

2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509

2510
2511
2512
2513
2514
2515
2516
2517







+
+

+




+
-
+
+
+
+
+
+
+
+
+
+
+
+





-
-
-
-
+
+
+
+

+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+





-
-
+
+
+



-
-
-
+
+
+


+


-
-
+
+


-
+
-









-



+
-
+
+
+





+



+
+
+

-
+







-
-
-
+
+
+
+



+
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
-

+
-
+
+







+







-
+







  WalIterator *pIter = 0;         /* Wal iterator context */
  u32 iDbpage = 0;                /* Next database page to write */
  u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
  u32 mxSafeFrame;                /* Max frame that can be backfilled */
  u32 mxPage;                     /* Max database page to write */
  int i;                          /* Loop counter */
  volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
  int bWal2 = isWalMode2(pWal);   /* True for wal2 connections */
  int iCkpt = bWal2 ? !walidxGetFile(&pWal->hdr) : 0;

  mxSafeFrame = walidxGetMxFrame(&pWal->hdr, iCkpt);
  szPage = walPagesize(pWal);
  testcase( szPage<=32768 );
  testcase( szPage>=65536 );
  pInfo = walCkptInfo(pWal);
  if( (bWal2==1 && pInfo->nBackfill==0 && mxSafeFrame) 
  if( pInfo->nBackfill<pWal->hdr.mxFrame ){
   || (bWal2==0 && pInfo->nBackfill<mxSafeFrame)
  ){
    sqlite3_file *pWalFd = pWal->apWalFd[iCkpt];
    mxPage = pWal->hdr.nPage;

    /* If this is a wal2 system, check for a reader holding a lock 
    ** preventing this checkpoint operation. If one is found, return
    ** early.  */
    if( bWal2 ){
      rc = wal2CheckpointOk(pWal, iCkpt);
      if( rc!=SQLITE_OK ) return rc;
    }

    /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
    ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
    assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );

    /* Compute in mxSafeFrame the index of the last frame of the WAL that is
    ** safe to write into the database.  Frames beyond mxSafeFrame might
    ** overwrite database pages that are in use by active readers and thus
    ** cannot be backfilled from the WAL.
    /* If this is a wal system (not wal2), compute in mxSafeFrame the index 
    ** of the last frame of the WAL that is safe to write into the database.
    ** Frames beyond mxSafeFrame might overwrite database pages that are in 
    ** use by active readers and thus cannot be backfilled from the WAL.
    */
    if( bWal2==0 ){
    mxSafeFrame = pWal->hdr.mxFrame;
    mxPage = pWal->hdr.nPage;
    for(i=1; i<WAL_NREADER; i++){
      /* Thread-sanitizer reports that the following is an unsafe read,
      ** as some other thread may be in the process of updating the value
      ** of the aReadMark[] slot. The assumption here is that if that is
      ** happening, the other client may only be increasing the value,
      ** not decreasing it. So assuming either that either the "old" or
      ** "new" version of the value is read, and not some arbitrary value
      ** that would never be written by a real client, things are still 
      ** safe.  */
      u32 y = pInfo->aReadMark[i];
      if( mxSafeFrame>y ){
        assert( y<=pWal->hdr.mxFrame );
        rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
        if( rc==SQLITE_OK ){
          pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
          walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
        }else if( rc==SQLITE_BUSY ){
          mxSafeFrame = y;
          xBusy = 0;
        }else{
          goto walcheckpoint_out;
      mxSafeFrame = pWal->hdr.mxFrame;
      mxPage = pWal->hdr.nPage;
      for(i=1; i<WAL_NREADER; i++){
        /* Thread-sanitizer reports that the following is an unsafe read,
        ** as some other thread may be in the process of updating the value
        ** of the aReadMark[] slot. The assumption here is that if that is
        ** happening, the other client may only be increasing the value,
        ** not decreasing it. So assuming either that either the "old" or
        ** "new" version of the value is read, and not some arbitrary value
        ** that would never be written by a real client, things are still 
        ** safe.  */
        u32 y = pInfo->aReadMark[i];
        if( mxSafeFrame>y ){
          assert( y<=pWal->hdr.mxFrame );
          rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
          if( rc==SQLITE_OK ){
            pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
            walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
          }else if( rc==SQLITE_BUSY ){
            mxSafeFrame = y;
            xBusy = 0;
          }else{
            goto walcheckpoint_out;
          }
        }
      }
    }

    /* Allocate the iterator */
    if( pInfo->nBackfill<mxSafeFrame ){
      rc = walIteratorInit(pWal, pInfo->nBackfill, &pIter);
    if( bWal2 || pInfo->nBackfill<mxSafeFrame ){
      assert( bWal2==0 || pInfo->nBackfill==0 );
      rc = walIteratorInit(pWal, iCkpt, pInfo->nBackfill, &pIter);
      assert( rc==SQLITE_OK || pIter==0 );
    }

    if( pIter
     && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0),1))==SQLITE_OK
    ){
    if( pIter && (bWal2 
     || (rc = walBusyLock(pWal, xBusy, pBusyArg,WAL_READ_LOCK(0),1))==SQLITE_OK
    )){
      u32 nBackfill = pInfo->nBackfill;

      assert( bWal2==0 || nBackfill==0 );
      pInfo->nBackfillAttempted = mxSafeFrame;

      /* Sync the WAL to disk */
      rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags));
      /* Sync the wal file being checkpointed to disk */
      rc = sqlite3OsSync(pWalFd, CKPT_SYNC_FLAGS(sync_flags));

      /* If the database may grow as a result of this checkpoint, hint
      ** about the eventual size of the db file to the VFS layer.
      ** about the eventual size of the db file to the VFS layer.  */
      */
      if( rc==SQLITE_OK ){
        i64 nReq = ((i64)mxPage * szPage);
        i64 nSize;                    /* Current size of database file */
        rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
        if( rc==SQLITE_OK && nSize<nReq ){
          sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
        }
      }


      /* Iterate through the contents of the WAL, copying data to the db file */
      while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
        i64 iOffset;

        assert( walFramePgno(pWal, iFrame)==iDbpage );
        assert( bWal2==1 || walFramePgno(pWal, iFrame)==iDbpage );
        assert( bWal2==0 || walFramePgno2(pWal, iCkpt, iFrame)==iDbpage );

        if( db->u1.isInterrupted ){
          rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
          break;
        }
        if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ){
          assert( bWal2==0 || iDbpage>mxPage );
          continue;
        }
        iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
        WALTRACE(("WAL%p: checkpoint frame %d of wal %d to db page %d\n",
              pWal, (int)iFrame, iCkpt, (int)iDbpage
        ));
        /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
        rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
        rc = sqlite3OsRead(pWalFd, zBuf, szPage, iOffset);
        if( rc!=SQLITE_OK ) break;
        iOffset = (iDbpage-1)*(i64)szPage;
        testcase( IS_BIG_INT(iOffset) );
        rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
        if( rc!=SQLITE_OK ) break;
      }

      /* If work was actually accomplished... */
      if( rc==SQLITE_OK ){
        if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
      /* If work was actually accomplished, truncate the db file, sync the wal
      ** file and set WalCkptInfo.nBackfill to indicate so. */
      if( rc==SQLITE_OK && (bWal2 || mxSafeFrame==walIndexHdr(pWal)->mxFrame) ){
        if( !bWal2 ){
          i64 szDb = pWal->hdr.nPage*(i64)szPage;
          testcase( IS_BIG_INT(szDb) );
          rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
        }
          if( rc==SQLITE_OK ){
            rc = sqlite3OsSync(pWal->pDbFd, CKPT_SYNC_FLAGS(sync_flags));
          }
        }
        if( rc==SQLITE_OK ){
          pInfo->nBackfill = mxSafeFrame;
        }
      }
        if( rc==SQLITE_OK ){
          rc = sqlite3OsSync(pWal->pDbFd, CKPT_SYNC_FLAGS(sync_flags));
        }
      }
      if( rc==SQLITE_OK ){
        pInfo->nBackfill = bWal2 ? 1 : mxSafeFrame;
      }


      /* Release the reader lock held while backfilling */
      if( bWal2==0 ){
      walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
        walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
      }
    }

    if( rc==SQLITE_BUSY ){
      /* Reset the return code so as not to report a checkpoint failure
      ** just because there are active readers.  */
      rc = SQLITE_OK;
    }
    if( bWal2 ) wal2CheckpointFinished(pWal, iCkpt);
  }

  /* If this is an SQLITE_CHECKPOINT_RESTART or TRUNCATE operation, and the
  ** entire wal file has been copied into the database file, then block 
  ** until all readers have finished using the wal file. This ensures that 
  ** the next process to write to the database restarts the wal file.
  */
  if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  if( bWal2==0 && rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
    assert( pWal->writeLock );
    if( pInfo->nBackfill<pWal->hdr.mxFrame ){
      rc = SQLITE_BUSY;
    }else if( eMode>=SQLITE_CHECKPOINT_RESTART ){
      u32 salt1;
      sqlite3_randomness(4, &salt1);
      assert( pInfo->nBackfill==pWal->hdr.mxFrame );
1941
1942
1943
1944
1945
1946
1947
1948

1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964

1965
1966
1967
1968
1969
1970
1971
1972
1973
1974











1975
1976
1977
1978
1979
1980
1981
2528
2529
2530
2531
2532
2533
2534

2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552










2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570







-
+
















+
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+







          ** writer clients should see that the entire log file has been
          ** checkpointed and behave accordingly. This seems unsafe though,
          ** as it would leave the system in a state where the contents of
          ** the wal-index header do not match the contents of the 
          ** file-system. To avoid this, update the wal-index header to
          ** indicate that the log file contains zero valid frames.  */
          walRestartHdr(pWal, salt1);
          rc = sqlite3OsTruncate(pWal->pWalFd, 0);
          rc = sqlite3OsTruncate(pWal->apWalFd[0], 0);
        }
        walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
      }
    }
  }

 walcheckpoint_out:
  walIteratorFree(pIter);
  return rc;
}

/*
** If the WAL file is currently larger than nMax bytes in size, truncate
** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
*/
static void walLimitSize(Wal *pWal, i64 nMax){
  if( isWalMode2(pWal)==0 ){
  i64 sz;
  int rx;
  sqlite3BeginBenignMalloc();
  rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
  if( rx==SQLITE_OK && (sz > nMax ) ){
    rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
  }
  sqlite3EndBenignMalloc();
  if( rx ){
    sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
    i64 sz;
    int rx;
    sqlite3BeginBenignMalloc();
    rx = sqlite3OsFileSize(pWal->apWalFd[0], &sz);
    if( rx==SQLITE_OK && (sz > nMax ) ){
      rx = sqlite3OsTruncate(pWal->apWalFd[0], nMax);
    }
    sqlite3EndBenignMalloc();
    if( rx ){
      sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
    }
  }
}

/*
** Close a connection to a log file.
*/
int sqlite3WalClose(
1996
1997
1998
1999
2000
2001
2002

2003
2004
2005

2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029

























2030








2031
2032
2033
2034
2035

2036
2037
2038
2039
2040
2041
2042
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
























2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631

2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642







+



+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

+
+
+
+
+
+
+
+

-



+







    ** the wal and wal-index files.
    **
    ** The EXCLUSIVE lock is not released before returning.
    */
    if( zBuf!=0
     && SQLITE_OK==(rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE))
    ){
      int i;
      if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
        pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
      }
      for(i=0; rc==SQLITE_OK && i<2; i++){
      rc = sqlite3WalCheckpoint(pWal, db, 
          SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
      );
      if( rc==SQLITE_OK ){
        int bPersist = -1;
        sqlite3OsFileControlHint(
            pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
        );
        if( bPersist!=1 ){
          /* Try to delete the WAL file if the checkpoint completed and
          ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
          ** mode (!bPersist) */
          isDelete = 1;
        }else if( pWal->mxWalSize>=0 ){
          /* Try to truncate the WAL file to zero bytes if the checkpoint
          ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
          ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
          ** non-negative value (pWal->mxWalSize>=0).  Note that we truncate
          ** to zero bytes as truncating to the journal_size_limit might
          ** leave a corrupt WAL file on disk. */
          walLimitSize(pWal, 0);
        }
      }
    }
        rc = sqlite3WalCheckpoint(pWal, db, 
            SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
        );
        if( rc==SQLITE_OK ){
          int bPersist = -1;
          sqlite3OsFileControlHint(
              pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
          );
          if( bPersist!=1 ){
            /* Try to delete the WAL file if the checkpoint completed and
            ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
            ** mode (!bPersist) */
            isDelete = 1;
          }else if( pWal->mxWalSize>=0 ){
            /* Try to truncate the WAL file to zero bytes if the checkpoint
            ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
            ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
            ** non-negative value (pWal->mxWalSize>=0).  Note that we truncate
            ** to zero bytes as truncating to the journal_size_limit might
            ** leave a corrupt WAL file on disk. */
            walLimitSize(pWal, 0);
          }
        }

        if( isWalMode2(pWal)==0 ) break;

        walCkptInfo(pWal)->nBackfill = 0;
        walidxSetFile(&pWal->hdr, !walidxGetFile(&pWal->hdr));
        pWal->writeLock = 1;
        walIndexWriteHdr(pWal);
        pWal->writeLock = 0;
      }
    }

    walIndexClose(pWal, isDelete);
    sqlite3OsClose(pWal->pWalFd);
    if( isDelete ){
      sqlite3BeginBenignMalloc();
      sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
      sqlite3OsDelete(pWal->pVfs, pWal->zWalName2, 0);
      sqlite3EndBenignMalloc();
    }
    WALTRACE(("WAL%p: closed\n", pWal));
    sqlite3_free((void *)pWal->apWiData);
    sqlite3_free(pWal);
  }
  return rc;
2209
2210
2211
2212
2213
2214
2215
2216



2217
2218
2219
2220
2221
2222
2223
2809
2810
2811
2812
2813
2814
2815

2816
2817
2818
2819
2820
2821
2822
2823
2824
2825







-
+
+
+







    }
  }

  /* If the header is read successfully, check the version number to make
  ** sure the wal-index was not constructed with some future format that
  ** this version of SQLite cannot understand.
  */
  if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
  if( badHdr==0 
   && pWal->hdr.iVersion!=WAL_VERSION1 && pWal->hdr.iVersion!=WAL_VERSION2
  ){
    rc = SQLITE_CANTOPEN_BKPT;
  }
  if( pWal->bShmUnreliable ){
    if( rc!=SQLITE_OK ){
      walIndexClose(pWal, 0);
      pWal->bShmUnreliable = 0;
      assert( pWal->nWiData>0 && pWal->apWiData[0]==0 );
2301
2302
2303
2304
2305
2306
2307
2308

2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325

2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342

2343
2344
2345
2346
2347
2348
2349
2903
2904
2905
2906
2907
2908
2909

2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926

2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943

2944
2945
2946
2947
2948
2949
2950
2951







-
+
















-
+
















-
+







  **
  ** Once sqlite3OsShmMap() has been called for an sqlite3_file and has
  ** returned any SQLITE_READONLY value, it must return only SQLITE_READONLY
  ** or SQLITE_READONLY_CANTINIT or some error for all subsequent invocations,
  ** even if some external agent does a "chmod" to make the shared-memory
  ** writable by us, until sqlite3OsShmUnmap() has been called.
  ** This is a requirement on the VFS implementation.
   */
  */
  rc = sqlite3OsShmMap(pWal->pDbFd, 0, WALINDEX_PGSZ, 0, &pDummy);
  assert( rc!=SQLITE_OK ); /* SQLITE_OK not possible for read-only connection */
  if( rc!=SQLITE_READONLY_CANTINIT ){
    rc = (rc==SQLITE_READONLY ? WAL_RETRY : rc);
    goto begin_unreliable_shm_out;
  }

  /* We reach this point only if the real shared-memory is still unreliable.
  ** Assume the in-memory WAL-index substitute is correct and load it
  ** into pWal->hdr.
  */
  memcpy(&pWal->hdr, (void*)walIndexHdr(pWal), sizeof(WalIndexHdr));

  /* Make sure some writer hasn't come in and changed the WAL file out
  ** from under us, then disconnected, while we were not looking.
  */
  rc = sqlite3OsFileSize(pWal->pWalFd, &szWal);
  rc = sqlite3OsFileSize(pWal->apWalFd[0], &szWal);
  if( rc!=SQLITE_OK ){
    goto begin_unreliable_shm_out;
  }
  if( szWal<WAL_HDRSIZE ){
    /* If the wal file is too small to contain a wal-header and the
    ** wal-index header has mxFrame==0, then it must be safe to proceed
    ** reading the database file only. However, the page cache cannot
    ** be trusted, as a read/write connection may have connected, written
    ** the db, run a checkpoint, truncated the wal file and disconnected
    ** since this client's last read transaction.  */
    *pChanged = 1;
    rc = (pWal->hdr.mxFrame==0 ? SQLITE_OK : WAL_RETRY);
    goto begin_unreliable_shm_out;
  }

  /* Check the salt keys at the start of the wal file still match. */
  rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
  rc = sqlite3OsRead(pWal->apWalFd[0], aBuf, WAL_HDRSIZE, 0);
  if( rc!=SQLITE_OK ){
    goto begin_unreliable_shm_out;
  }
  if( memcmp(&pWal->hdr.aSalt, &aBuf[16], 8) ){
    /* Some writer has wrapped the WAL file while we were not looking.
    ** Return WAL_RETRY which will cause the in-memory WAL-index to be
    ** rebuilt. */
2370
2371
2372
2373
2374
2375
2376
2377

2378
2379
2380
2381
2382
2383
2384
2972
2973
2974
2975
2976
2977
2978

2979
2980
2981
2982
2983
2984
2985
2986







-
+







      iOffset+szFrame<=szWal; 
      iOffset+=szFrame
  ){
    u32 pgno;                   /* Database page number for frame */
    u32 nTruncate;              /* dbsize field from frame header */

    /* Read and decode the next log frame. */
    rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
    rc = sqlite3OsRead(pWal->apWalFd[0], aFrame, szFrame, iOffset);
    if( rc!=SQLITE_OK ) break;
    if( !walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame) ) break;

    /* If nTruncate is non-zero, then a complete transaction has been
    ** appended to this wal file. Set rc to WAL_RETRY and break out of
    ** the loop.  */
    if( nTruncate ){
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465

2466
2467
2468
2469
2470
2471
2472
3054
3055
3056
3057
3058
3059
3060



3061

3062

3063
3064
3065
3066
3067
3068
3069
3070







-
-
-

-

-
+







** checkpoint process do as much work as possible.  This routine might
** update values of the aReadMark[] array in the header, but if it does
** so it takes care to hold an exclusive lock on the corresponding
** WAL_READ_LOCK() while changing values.
*/
static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
  volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
  u32 mxReadMark;                 /* Largest aReadMark[] value */
  int mxI;                        /* Index of largest aReadMark[] value */
  int i;                          /* Loop counter */
  int rc = SQLITE_OK;             /* Return code  */
  u32 mxFrame;                    /* Wal frame to lock to */

  assert( pWal->readLock<0 );     /* Not currently locked */
  assert( pWal->readLock==WAL_LOCK_NONE );     /* Not currently locked */

  /* useWal may only be set for read/write connections */
  assert( (pWal->readOnly & WAL_SHM_RDONLY)==0 || useWal==0 );

  /* Take steps to avoid spinning forever if there is a protocol error.
  **
  ** Circumstances that cause a RETRY should only last for the briefest
2531
2532
2533
2534
2535
2536
2537
































2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661





























































































































2662
2663
2664
2665
2666
2667
2668
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167




























































































































3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299







+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+







      return walBeginShmUnreliable(pWal, pChanged);
    }
  }

  assert( pWal->nWiData>0 );
  assert( pWal->apWiData[0]!=0 );
  pInfo = walCkptInfo(pWal);
  if( isWalMode2(pWal) ){
    /* This connection needs a "part" lock on the current wal file and, 
    ** unless pInfo->nBackfill is set to indicate that it has already been
    ** checkpointed, a "full" lock on the other wal file.  */
    int iWal = walidxGetFile(&pWal->hdr);
    int nBackfill = pInfo->nBackfill || walidxGetMxFrame(&pWal->hdr, !iWal)==0;
    int eLock = 1 + (iWal*2) + (nBackfill==iWal);

    assert( nBackfill==0 || nBackfill==1 );
    assert( iWal==0 || iWal==1 );
    assert( iWal!=0 || nBackfill!=1 || eLock==WAL_LOCK_PART1 );
    assert( iWal!=0 || nBackfill!=0 || eLock==WAL_LOCK_PART1_FULL2 );
    assert( iWal!=1 || nBackfill!=1 || eLock==WAL_LOCK_PART2 );
    assert( iWal!=1 || nBackfill!=0 || eLock==WAL_LOCK_PART2_FULL1 );

    rc = walLockShared(pWal, WAL_READ_LOCK(eLock));
    if( rc!=SQLITE_OK ){
      return (rc==SQLITE_BUSY ? WAL_RETRY : rc);
    }
    walShmBarrier(pWal);
    if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
      walUnlockShared(pWal, WAL_READ_LOCK(eLock));
      return WAL_RETRY;
    }else{
      pWal->readLock = eLock;
    }
    assert( pWal->minFrame==0 && walFramePage(pWal->minFrame)==0 );
  }else{
    u32 mxReadMark;               /* Largest aReadMark[] value */
    int mxI;                      /* Index of largest aReadMark[] value */
    int i;                        /* Loop counter */
    u32 mxFrame;                  /* Wal frame to lock to */
  if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame
#ifdef SQLITE_ENABLE_SNAPSHOT
   && (pWal->pSnapshot==0 || pWal->hdr.mxFrame==0)
#endif
  ){
    /* The WAL has been completely backfilled (or it is empty).
    ** and can be safely ignored.
    */
    rc = walLockShared(pWal, WAL_READ_LOCK(0));
    walShmBarrier(pWal);
    if( rc==SQLITE_OK ){
      if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
        /* It is not safe to allow the reader to continue here if frames
        ** may have been appended to the log before READ_LOCK(0) was obtained.
        ** When holding READ_LOCK(0), the reader ignores the entire log file,
        ** which implies that the database file contains a trustworthy
        ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from
        ** happening, this is usually correct.
        **
        ** However, if frames have been appended to the log (or if the log 
        ** is wrapped and written for that matter) before the READ_LOCK(0)
        ** is obtained, that is not necessarily true. A checkpointer may
        ** have started to backfill the appended frames but crashed before
        ** it finished. Leaving a corrupt image in the database file.
        */
        walUnlockShared(pWal, WAL_READ_LOCK(0));
        return WAL_RETRY;
      }
      pWal->readLock = 0;
      return SQLITE_OK;
    }else if( rc!=SQLITE_BUSY ){
      return rc;
    }
  }

  /* If we get this far, it means that the reader will want to use
  ** the WAL to get at content from recent commits.  The job now is
  ** to select one of the aReadMark[] entries that is closest to
  ** but not exceeding pWal->hdr.mxFrame and lock that entry.
  */
  mxReadMark = 0;
  mxI = 0;
  mxFrame = pWal->hdr.mxFrame;
#ifdef SQLITE_ENABLE_SNAPSHOT
  if( pWal->pSnapshot && pWal->pSnapshot->mxFrame<mxFrame ){
    mxFrame = pWal->pSnapshot->mxFrame;
  }
#endif
  for(i=1; i<WAL_NREADER; i++){
    u32 thisMark = AtomicLoad(pInfo->aReadMark+i);
    if( mxReadMark<=thisMark && thisMark<=mxFrame ){
      assert( thisMark!=READMARK_NOT_USED );
      mxReadMark = thisMark;
      mxI = i;
    }
  }
  if( (pWal->readOnly & WAL_SHM_RDONLY)==0
   && (mxReadMark<mxFrame || mxI==0)
  ){
    for(i=1; i<WAL_NREADER; i++){
      rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
      if( rc==SQLITE_OK ){
        mxReadMark = AtomicStore(pInfo->aReadMark+i,mxFrame);
        mxI = i;
        walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
        break;
      }else if( rc!=SQLITE_BUSY ){
        return rc;
      }
    }
  }
  if( mxI==0 ){
    assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
    return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTINIT;
  }

  rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
  if( rc ){
    return rc==SQLITE_BUSY ? WAL_RETRY : rc;
  }
  /* Now that the read-lock has been obtained, check that neither the
  ** value in the aReadMark[] array or the contents of the wal-index
  ** header have changed.
  **
  ** It is necessary to check that the wal-index header did not change
  ** between the time it was read and when the shared-lock was obtained
  ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
  ** that the log file may have been wrapped by a writer, or that frames
  ** that occur later in the log than pWal->hdr.mxFrame may have been
  ** copied into the database by a checkpointer. If either of these things
  ** happened, then reading the database with the current value of
  ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
  ** instead.
  **
  ** Before checking that the live wal-index header has not changed
  ** since it was read, set Wal.minFrame to the first frame in the wal
  ** file that has not yet been checkpointed. This client will not need
  ** to read any frames earlier than minFrame from the wal file - they
  ** can be safely read directly from the database file.
  **
  ** Because a ShmBarrier() call is made between taking the copy of 
  ** nBackfill and checking that the wal-header in shared-memory still
  ** matches the one cached in pWal->hdr, it is guaranteed that the 
  ** checkpointer that set nBackfill was not working with a wal-index
  ** header newer than that cached in pWal->hdr. If it were, that could
  ** cause a problem. The checkpointer could omit to checkpoint
  ** a version of page X that lies before pWal->minFrame (call that version
  ** A) on the basis that there is a newer version (version B) of the same
  ** page later in the wal file. But if version B happens to like past
  ** frame pWal->hdr.mxFrame - then the client would incorrectly assume
  ** that it can read version A from the database file. However, since
  ** we can guarantee that the checkpointer that set nBackfill could not
  ** see any pages past pWal->hdr.mxFrame, this problem does not come up.
  */
  pWal->minFrame = AtomicLoad(&pInfo->nBackfill)+1;
  walShmBarrier(pWal);
  if( AtomicLoad(pInfo->aReadMark+mxI)!=mxReadMark
   || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
  ){
    walUnlockShared(pWal, WAL_READ_LOCK(mxI));
    return WAL_RETRY;
  }else{
    assert( mxReadMark<=pWal->hdr.mxFrame );
    pWal->readLock = (i16)mxI;
    if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame
  #ifdef SQLITE_ENABLE_SNAPSHOT
     && (pWal->pSnapshot==0 || pWal->hdr.mxFrame==0)
  #endif
    ){
      /* The WAL has been completely backfilled (or it is empty).
      ** and can be safely ignored.
      */
      rc = walLockShared(pWal, WAL_READ_LOCK(0));
      walShmBarrier(pWal);
      if( rc==SQLITE_OK ){
        if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr,sizeof(WalIndexHdr)) ){
          /* It is not safe to allow the reader to continue here if frames
          ** may have been appended to the log before READ_LOCK(0) was obtained.
          ** When holding READ_LOCK(0), the reader ignores the entire log file,
          ** which implies that the database file contains a trustworthy
          ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from
          ** happening, this is usually correct.
          **
          ** However, if frames have been appended to the log (or if the log 
          ** is wrapped and written for that matter) before the READ_LOCK(0)
          ** is obtained, that is not necessarily true. A checkpointer may
          ** have started to backfill the appended frames but crashed before
          ** it finished. Leaving a corrupt image in the database file.
          */
          walUnlockShared(pWal, WAL_READ_LOCK(0));
          return WAL_RETRY;
        }
        pWal->readLock = 0;
        return SQLITE_OK;
      }else if( rc!=SQLITE_BUSY ){
        return rc;
      }
    }
  
    /* If we get this far, it means that the reader will want to use
    ** the WAL to get at content from recent commits.  The job now is
    ** to select one of the aReadMark[] entries that is closest to
    ** but not exceeding pWal->hdr.mxFrame and lock that entry.
    */
    mxReadMark = 0;
    mxI = 0;
    mxFrame = pWal->hdr.mxFrame;
  #ifdef SQLITE_ENABLE_SNAPSHOT
    if( pWal->pSnapshot && pWal->pSnapshot->mxFrame<mxFrame ){
      mxFrame = pWal->pSnapshot->mxFrame;
    }
  #endif
    for(i=1; i<WAL_NREADER; i++){
      u32 thisMark = AtomicLoad(pInfo->aReadMark+i);
      if( mxReadMark<=thisMark && thisMark<=mxFrame ){
        assert( thisMark!=READMARK_NOT_USED );
        mxReadMark = thisMark;
        mxI = i;
      }
    }
    if( (pWal->readOnly & WAL_SHM_RDONLY)==0
     && (mxReadMark<mxFrame || mxI==0)
    ){
      for(i=1; i<WAL_NREADER; i++){
        rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
        if( rc==SQLITE_OK ){
          mxReadMark = AtomicStore(pInfo->aReadMark+i,mxFrame);
          mxI = i;
          walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
          break;
        }else if( rc!=SQLITE_BUSY ){
          return rc;
        }
      }
    }
    if( mxI==0 ){
      assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
      return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTINIT;
    }
  
    rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
    if( rc ){
      return rc==SQLITE_BUSY ? WAL_RETRY : rc;
    }
    /* Now that the read-lock has been obtained, check that neither the
    ** value in the aReadMark[] array or the contents of the wal-index
    ** header have changed.
    **
    ** It is necessary to check that the wal-index header did not change
    ** between the time it was read and when the shared-lock was obtained
    ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
    ** that the log file may have been wrapped by a writer, or that frames
    ** that occur later in the log than pWal->hdr.mxFrame may have been
    ** copied into the database by a checkpointer. If either of these things
    ** happened, then reading the database with the current value of
    ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
    ** instead.
    **
    ** Before checking that the live wal-index header has not changed
    ** since it was read, set Wal.minFrame to the first frame in the wal
    ** file that has not yet been checkpointed. This client will not need
    ** to read any frames earlier than minFrame from the wal file - they
    ** can be safely read directly from the database file.
    **
    ** Because a ShmBarrier() call is made between taking the copy of 
    ** nBackfill and checking that the wal-header in shared-memory still
    ** matches the one cached in pWal->hdr, it is guaranteed that the 
    ** checkpointer that set nBackfill was not working with a wal-index
    ** header newer than that cached in pWal->hdr. If it were, that could
    ** cause a problem. The checkpointer could omit to checkpoint
    ** a version of page X that lies before pWal->minFrame (call that version
    ** A) on the basis that there is a newer version (version B) of the same
    ** page later in the wal file. But if version B happens to like past
    ** frame pWal->hdr.mxFrame - then the client would incorrectly assume
    ** that it can read version A from the database file. However, since
    ** we can guarantee that the checkpointer that set nBackfill could not
    ** see any pages past pWal->hdr.mxFrame, this problem does not come up.
    */
    pWal->minFrame = AtomicLoad(&pInfo->nBackfill)+1;
    walShmBarrier(pWal);
    if( AtomicLoad(pInfo->aReadMark+mxI)!=mxReadMark
     || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
    ){
      walUnlockShared(pWal, WAL_READ_LOCK(mxI));
      return WAL_RETRY;
    }else{
      assert( mxReadMark<=pWal->hdr.mxFrame );
      pWal->readLock = (i16)mxI;
    }
  }
  return rc;
}

#ifdef SQLITE_ENABLE_SNAPSHOT
/*
** Attempt to reduce the value of the WalCkptInfo.nBackfillAttempted 
2681
2682
2683
2684
2685
2686
2687



2688
2689
2690
2691
2692
2693
2694
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328







+
+
+







**
** SQLITE_OK is returned if successful, or an SQLite error code if an
** error occurs. It is not an error if nBackfillAttempted cannot be
** decreased at all.
*/
int sqlite3WalSnapshotRecover(Wal *pWal){
  int rc;

  /* Snapshots may not be used with wal2 mode databases. */
  if( isWalMode2(pWal) ) return SQLITE_ERROR;

  assert( pWal->readLock>=0 );
  rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
  if( rc==SQLITE_OK ){
    volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
    int szPage = (int)pWal->szPage;
    i64 szDb;                   /* Size of db file in bytes */
2710
2711
2712
2713
2714
2715
2716
2717

2718
2719
2720
2721
2722
2723
2724
3344
3345
3346
3347
3348
3349
3350

3351
3352
3353
3354
3355
3356
3357
3358







-
+







          rc = walHashGet(pWal, walFramePage(i), &sLoc);
          if( rc!=SQLITE_OK ) break;
          pgno = sLoc.aPgno[i-sLoc.iZero];
          iDbOff = (i64)(pgno-1) * szPage;

          if( iDbOff+szPage<=szDb ){
            iWalOff = walFrameOffset(i, szPage) + WAL_FRAME_HDRSIZE;
            rc = sqlite3OsRead(pWal->pWalFd, pBuf1, szPage, iWalOff);
            rc = sqlite3OsRead(pWal->apWalFd[0], pBuf1, szPage, iWalOff);

            if( rc==SQLITE_OK ){
              rc = sqlite3OsRead(pWal->pDbFd, pBuf2, szPage, iDbOff);
            }

            if( rc!=SQLITE_OK || 0==memcmp(pBuf1, pBuf2, szPage) ){
              break;
2756
2757
2758
2759
2760
2761
2762

2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774




2775
2776
2777
2778
2779
2780
2781
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420







+












+
+
+
+







int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
  int rc;                         /* Return code */
  int cnt = 0;                    /* Number of TryBeginRead attempts */

#ifdef SQLITE_ENABLE_SNAPSHOT
  int bChanged = 0;
  WalIndexHdr *pSnapshot = pWal->pSnapshot;
  if( pSnapshot && isWalMode2(pWal) ) return SQLITE_ERROR;
  if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
    bChanged = 1;
  }
#endif

  do{
    rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
  }while( rc==WAL_RETRY );
  testcase( (rc&0xff)==SQLITE_BUSY );
  testcase( (rc&0xff)==SQLITE_IOERR );
  testcase( rc==SQLITE_PROTOCOL );
  testcase( rc==SQLITE_OK );
  
  if( rc==SQLITE_OK && pWal->hdr.iVersion==WAL_VERSION2 ){
    rc = walOpenWal2(pWal);
  }

  pWal->nPriorFrame = pWal->hdr.mxFrame;
#ifdef SQLITE_ENABLE_SNAPSHOT
  if( rc==SQLITE_OK ){
    if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
      /* At this point the client has a lock on an aReadMark[] slot holding
      ** a value equal to or smaller than pSnapshot->mxFrame, but pWal->hdr
2843
2844
2845
2846
2847
2848
2849
2850

2851
2852

2853




















































































2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868



2869
2870
2871
2872
2873
2874
2875




2876
2877

2878
2879









2880
2881
2882
2883











2884
2885
2886
2887

2888
2889
2890





2891
2892
2893
2894
2895
2896
2897
2898
2899







2900
2901
2902


2903
2904
2905
2906
2907
2908
2909
2910
2911

2912
2913
2914
2915
2916
2917
2918
2919
2920


2921
2922
2923
2924
2925

2926
2927
2928
2929
2930



2931
2932
2933


2934
2935

2936
2937
2938
2939
2940
2941

2942




2943
2944
2945
2946
2947
2948
2949
3482
3483
3484
3485
3486
3487
3488

3489
3490

3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595



3596


3597
3598
3599
3600
3601

3602


3603
3604
3605
3606
3607
3608
3609
3610
3611




3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627



3628
3629
3630
3631
3632









3633
3634
3635
3636
3637
3638
3639



3640
3641









3642






3643


3644
3645





3646





3647
3648
3649



3650
3651


3652

3653
3654
3655
3656

3657

3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668







-
+

-
+

+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+















+
+
+

-
-
-

-
-
+
+
+
+

-
+
-
-
+
+
+
+
+
+
+
+
+
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+




+
-
-
-
+
+
+
+
+
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
-
-
-
+
+
-
-
-
-
-
-
-
-
-
+
-
-
-
-
-
-

-
-
+
+
-
-
-
-
-
+
-
-
-
-
-
+
+
+
-
-
-
+
+
-
-
+
-




-
+
-
+
+
+
+








/*
** Finish with a read transaction.  All this does is release the
** read-lock.
*/
void sqlite3WalEndReadTransaction(Wal *pWal){
  sqlite3WalEndWriteTransaction(pWal);
  if( pWal->readLock>=0 ){
  if( pWal->readLock!=WAL_LOCK_NONE ){
    walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
    pWal->readLock = -1;
    pWal->readLock = WAL_LOCK_NONE;
  }
}

/* Search hash table iHash for an entry matching page number
** pgno. Each call to this function searches a single hash table
** (each hash table indexes up to HASHTABLE_NPAGE frames).
**
** This code might run concurrently to the code in walIndexAppend()
** that adds entries to the wal-index (and possibly to this hash 
** table). This means the value just read from the hash 
** slot (aHash[iKey]) may have been added before or after the 
** current read transaction was opened. Values added after the
** read transaction was opened may have been written incorrectly -
** i.e. these slots may contain garbage data. However, we assume
** that any slots written before the current read transaction was
** opened remain unmodified.
**
** For the reasons above, the if(...) condition featured in the inner
** loop of the following block is more stringent that would be required 
** if we had exclusive access to the hash-table:
**
**   (aPgno[iFrame]==pgno): 
**     This condition filters out normal hash-table collisions.
**
**   (iFrame<=iLast): 
**     This condition filters out entries that were added to the hash
**     table after the current read-transaction had started.
*/
static int walSearchHash(
  Wal *pWal, 
  u32 iLast,
  int iHash, 
  Pgno pgno, 
  u32 *piRead
){
  WalHashLoc sLoc;                /* Hash table location */
  int iKey;                       /* Hash slot index */
  int nCollide;                   /* Number of hash collisions remaining */
  int rc;                         /* Error code */

  rc = walHashGet(pWal, iHash, &sLoc);
  if( rc!=SQLITE_OK ){
    return rc;
  }
  nCollide = HASHTABLE_NSLOT;
  for(iKey=walHash(pgno); sLoc.aHash[iKey]; iKey=walNextHash(iKey)){
    u32 iFrame = sLoc.aHash[iKey] + sLoc.iZero;
    if( iFrame<=iLast 
     && iFrame>=pWal->minFrame 
     && sLoc.aPgno[sLoc.aHash[iKey]]==pgno 
    ){
      assert( iFrame>*piRead || CORRUPT_DB );
      *piRead = iFrame;
    }
    if( (nCollide--)==0 ){
      return SQLITE_CORRUPT_BKPT;
    }
  }

  return SQLITE_OK;
}

static int walSearchWal(
  Wal *pWal, 
  int iWal, 
  Pgno pgno, 
  u32 *piRead
){
  int rc = SQLITE_OK;
  int bWal2 = isWalMode2(pWal);
  u32 iLast = walidxGetMxFrame(&pWal->hdr, iWal);
  if( iLast ){
    int iHash;
    int iMinHash = walFramePage(pWal->minFrame);
    u32 iExternal = bWal2 ? walExternalEncode(iWal, iLast) : iLast;
    assert( bWal2==0 || pWal->minFrame==0 );
    for(iHash=walFramePage(iExternal); 
        iHash>=iMinHash && *piRead==0; 
        iHash-=(1+bWal2)
    ){
      rc = walSearchHash(pWal, iExternal, iHash, pgno, piRead);
      if( rc!=SQLITE_OK ) break;
    }
  }
  return rc;
}

/*
** Search the wal file for page pgno. If found, set *piRead to the frame that
** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
** to zero.
**
** Return SQLITE_OK if successful, or an error code if an error occurs. If an
** error does occur, the final value of *piRead is undefined.
*/
int sqlite3WalFindFrame(
  Wal *pWal,                      /* WAL handle */
  Pgno pgno,                      /* Database page number to read data for */
  u32 *piRead                     /* OUT: Frame number (or zero) */
){
  int bWal2 = isWalMode2(pWal);
  int iApp = walidxGetFile(&pWal->hdr);
  int rc = SQLITE_OK;
  u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
  u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
  int iHash;                      /* Used to loop through N hash tables */
  int iMinHash;

  /* This routine is only be called from within a read transaction. */
  assert( pWal->readLock>=0 || pWal->lockError );
  /* This routine is only be called from within a read transaction. Or,
  ** sometimes, as part of a rollback that occurs after an error reaquiring
  ** a read-lock in walRestartLog().  */
  assert( pWal->readLock!=WAL_LOCK_NONE || pWal->writeLock );

  /* If the "last page" field of the wal-index header snapshot is 0, then
  /* If this is a regular wal system, then iApp must be set to 0 (there is
  ** no data will be read from the wal under any circumstances. Return early
  ** in this case as an optimization.  Likewise, if pWal->readLock==0, 
  ** only one wal file, after all). Or, if this is a wal2 system and the
  ** write-lock is not held, the client must have a partial-wal lock on wal 
  ** file iApp. This is not always true if the write-lock is held and this
  ** function is being called after WalLockForCommit() as part of committing
  ** a CONCURRENT transaction.  */
#ifdef SQLITE_DEBUG
  if( bWal2 ){
    if( pWal->writeLock==0 ){
      int l = pWal->readLock;
  ** then the WAL is ignored by the reader so return early, as if the 
  ** WAL were empty.
  */
  if( iLast==0 || (pWal->readLock==0 && pWal->bShmUnreliable==0) ){
      assert( iApp==1 || l==WAL_LOCK_PART1 || l==WAL_LOCK_PART1_FULL2 );
      assert( iApp==0 || l==WAL_LOCK_PART2 || l==WAL_LOCK_PART2_FULL1 );
    }
  }else{
    assert( iApp==0 );
  }
#endif

  /* Return early if read-lock 0 is held. */
  if( (pWal->readLock==0 && pWal->bShmUnreliable==0) ){
    assert( !bWal2 );
    *piRead = 0;
    return SQLITE_OK;
  }

  /* Search the wal file that the client holds a partial lock on first. */
  /* Each iteration of the following for() loop searches one
  ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
  **
  rc = walSearchWal(pWal, iApp, pgno, &iRead);

  /* If the requested page was not found, no error has occured, and 
  ** the client holds a full-wal lock on the other wal file, search it
  ** too.  */
  ** This code might run concurrently to the code in walIndexAppend()
  ** that adds entries to the wal-index (and possibly to this hash 
  ** table). This means the value just read from the hash 
  ** slot (aHash[iKey]) may have been added before or after the 
  ** current read transaction was opened. Values added after the
  ** read transaction was opened may have been written incorrectly -
  ** i.e. these slots may contain garbage data. However, we assume
  ** that any slots written before the current read transaction was
  ** opened remain unmodified.
  if( rc==SQLITE_OK && bWal2 && iRead==0 && (
        pWal->readLock==WAL_LOCK_PART1_FULL2 
     || pWal->readLock==WAL_LOCK_PART2_FULL1
#ifndef SQLITE_OMIT_CONCURRENT
     || (pWal->readLock==WAL_LOCK_PART1 && iApp==1)
     || (pWal->readLock==WAL_LOCK_PART2 && iApp==0)
#endif
  **
  ** For the reasons above, the if(...) condition featured in the inner
  ** loop of the following block is more stringent that would be required 
  )){
    rc = walSearchWal(pWal, !iApp, pgno, &iRead);
  ** if we had exclusive access to the hash-table:
  **
  **   (aPgno[iFrame]==pgno): 
  **     This condition filters out normal hash-table collisions.
  **
  **   (iFrame<=iLast): 
  **     This condition filters out entries that were added to the hash
  **     table after the current read-transaction had started.
  */
  }
  iMinHash = walFramePage(pWal->minFrame);
  for(iHash=walFramePage(iLast); iHash>=iMinHash; iHash--){
    WalHashLoc sLoc;              /* Hash table location */
    int iKey;                     /* Hash slot index */
    int nCollide;                 /* Number of hash collisions remaining */
    int rc;                       /* Error code */

    rc = walHashGet(pWal, iHash, &sLoc);
    if( rc!=SQLITE_OK ){
#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  if( iRead ){ 
      return rc;
    }
    nCollide = HASHTABLE_NSLOT;
    for(iKey=walHash(pgno); sLoc.aHash[iKey]; iKey=walNextHash(iKey)){
      u32 iFrame = sLoc.aHash[iKey] + sLoc.iZero;
    u32 iFrame;
      if( iFrame<=iLast && iFrame>=pWal->minFrame
       && sLoc.aPgno[sLoc.aHash[iKey]]==pgno ){
        assert( iFrame>iRead || CORRUPT_DB );
        iRead = iFrame;
      }
    int iWal = walExternalDecode(iRead, &iFrame);
    WALTRACE(("WAL%p: page %d @ frame %d wal %d\n",pWal,(int)pgno,iFrame,iWal));
  }else{
      if( (nCollide--)==0 ){
        return SQLITE_CORRUPT_BKPT;
      }
    WALTRACE(("WAL%p: page %d not found\n", pWal, (int)pgno));
  }
    }
    if( iRead ) break;
#endif
  }

#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  /* If expensive assert() statements are available, do a linear search
  ** of the wal-index file content. Make sure the results agree with the
  ** result obtained using the hash indexes above.  */
  ** result obtained using the hash indexes above.  
  {
  **
  ** TODO: This is broken for wal2.
  */
  if( rc==SQLITE_OK ){
    u32 iRead2 = 0;
    u32 iTest;
    assert( pWal->bShmUnreliable || pWal->minFrame>0 );
    for(iTest=iLast; iTest>=pWal->minFrame && iTest>0; iTest--){
      if( walFramePgno(pWal, iTest)==pgno ){
        iRead2 = iTest;
        break;
2960
2961
2962
2963
2964
2965
2966
2967

2968
2969
2970
2971


2972


2973
2974
2975
2976










2977
2978
2979

2980
2981
2982
2983
2984
2985
2986

2987
2988
2989
2990
2991
2992
2993
3679
3680
3681
3682
3683
3684
3685

3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711

3712
3713
3714
3715
3716
3717
3718

3719
3720
3721
3722
3723
3724
3725
3726







-
+




+
+

+
+




+
+
+
+
+
+
+
+
+
+


-
+






-
+







/*
** Read the contents of frame iRead from the wal file into buffer pOut
** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
** error code otherwise.
*/
int sqlite3WalReadFrame(
  Wal *pWal,                      /* WAL handle */
  u32 iRead,                      /* Frame to read */
  u32 iExternal,                  /* Frame to read */
  int nOut,                       /* Size of buffer pOut in bytes */
  u8 *pOut                        /* Buffer to write page data to */
){
  int sz;
  int iWal = 0;
  u32 iRead;
  i64 iOffset;

  /* Figure out the page size */
  sz = pWal->hdr.szPage;
  sz = (sz&0xfe00) + ((sz&0x0001)<<16);
  testcase( sz<=32768 );
  testcase( sz>=65536 );

  if( isWalMode2(pWal) ){
    /* Figure out which of the two wal files, and the frame within, that 
    ** iExternal refers to.  */
    iWal = walExternalDecode(iExternal, &iRead);
  }else{
    iRead = iExternal;
  }

  WALTRACE(("WAL%p: reading frame %d wal %d\n", pWal, iRead, iWal));
  iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
  /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
  return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
  return sqlite3OsRead(pWal->apWalFd[iWal], pOut, (nOut>sz?sz:nOut), iOffset);
}

/* 
** Return the size of the database in pages (or zero, if unknown).
*/
Pgno sqlite3WalDbsize(Wal *pWal){
  if( pWal && ALWAYS(pWal->readLock>=0) ){
  if( pWal && ALWAYS(pWal->readLock!=WAL_LOCK_NONE) ){
    return pWal->hdr.nPage;
  }
  return 0;
}

/*
** Take the WRITER lock on the WAL file. Return SQLITE_OK if successful,
3055
3056
3057
3058
3059
3060
3061

3062
3063
3064
3065
3066
3067
3068
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802







+







**
** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
*/
static int walUpgradeReadlock(Wal *pWal){
  int cnt;
  int rc;
  assert( pWal->writeLock && pWal->readLock==0 );
  assert( isWalMode2(pWal)==0 );
  walUnlockShared(pWal, WAL_READ_LOCK(0));
  pWal->readLock = -1;
  cnt = 0;
  do{
    int notUsed;
    rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
  }while( rc==WAL_RETRY );
3128
3129
3130
3131
3132
3133
3134

3135

3136
3137
3138
3139
3140
3141
3142
3143








































3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195


























































3196
3197
3198
3199
3200
3201
3202
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871








3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912



















































3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977







+

+
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+







    if( walIndexLoadHdr(pWal, &head) ){
      /* This branch is taken if the wal-index header is corrupted. This 
      ** occurs if some other writer has crashed while committing a 
      ** transaction to this database since the current concurrent transaction
      ** was opened.  */
      rc = SQLITE_BUSY_SNAPSHOT;
    }else if( memcmp(&pWal->hdr, (void*)&head, sizeof(WalIndexHdr))!=0 ){
      int bWal2 = isWalMode2(pWal);
      int iHash;
      int nLoop = 1+(bWal2 && walidxGetFile(&head)!=walidxGetFile(&pWal->hdr));
      int iLastHash = walFramePage(head.mxFrame);
      u32 iFirst = pWal->hdr.mxFrame+1;     /* First wal frame to check */
      if( memcmp(pWal->hdr.aSalt, (u32*)head.aSalt, sizeof(u32)*2) ){
        assert( pWal->readLock==0 );
        iFirst = 1;
      }
      for(iHash=walFramePage(iFirst); iHash<=iLastHash; iHash++){
        WalHashLoc sLoc;
      int iLoop;
      

      assert( nLoop==1 || nLoop==2 );
      for(iLoop=0; rc==SQLITE_OK && iLoop<nLoop; iLoop++){
        u32 iFirst;               /* First (external) wal frame to check */
        u32 iLastHash;            /* Last hash to check this loop */
        u32 mxFrame;              /* Last (external) wal frame to check */

        if( bWal2==0 ){
          assert( iLoop==0 );
          /* Special case for wal mode. If this concurrent transaction was
          ** opened after the entire wal file had been checkpointed, and
          ** another connection has since wrapped the wal file, then we wish to
          ** iterate through every frame in the new wal file - not just those
          ** that follow the current value of pWal->hdr.mxFrame (which will be
          ** set to the size of the old, now overwritten, wal file). This
          ** doesn't come up in wal2 mode, as in wal2 mode the client always
          ** has a PART lock on one of the wal files, preventing it from being
          ** checkpointed or overwritten. */
          iFirst = pWal->hdr.mxFrame+1;
          if( memcmp(pWal->hdr.aSalt, (u32*)head.aSalt, sizeof(u32)*2) ){
            assert( pWal->readLock==0 );
            iFirst = 1;
          }
          mxFrame = head.mxFrame;
        }else{
          int iA = walidxGetFile(&pWal->hdr);
          if( iLoop==0 ){
            iFirst = walExternalEncode(iA, 1+walidxGetMxFrame(&pWal->hdr, iA));
            mxFrame = walExternalEncode(iA, walidxGetMxFrame(&head, iA));
          }else{
            iFirst = walExternalEncode(!iA, 1);
            mxFrame = walExternalEncode(!iA, walidxGetMxFrame(&head, !iA));
          }
        }
        iLastHash = walFramePage(mxFrame);

        for(iHash=walFramePage(iFirst); iHash<=iLastHash; iHash += (1+bWal2)){
          WalHashLoc sLoc;

        rc = walHashGet(pWal, iHash, &sLoc);
        if( rc==SQLITE_OK ){
          u32 i, iMin, iMax;
          assert( head.mxFrame>=sLoc.iZero );
          iMin = (sLoc.iZero >= iFirst) ? 1 : (iFirst - sLoc.iZero);
          iMax = (iHash==0) ? HASHTABLE_NPAGE_ONE : HASHTABLE_NPAGE;
          if( iMax>(head.mxFrame-sLoc.iZero) ) iMax = (head.mxFrame-sLoc.iZero);
          for(i=iMin; rc==SQLITE_OK && i<=iMax; i++){
            PgHdr *pPg;
            if( sLoc.aPgno[i]==1 ){
              /* Check that the schema cookie has not been modified. If
              ** it has not, the commit can proceed. */
              u8 aNew[4];
              u8 *aOld = &((u8*)pPage1->pData)[40];
              int sz;
              i64 iOffset;
              sz = pWal->hdr.szPage;
              sz = (sz&0xfe00) + ((sz&0x0001)<<16);
              iOffset = walFrameOffset(i+sLoc.iZero, sz) + WAL_FRAME_HDRSIZE+40;
              rc = sqlite3OsRead(pWal->pWalFd, aNew, sizeof(aNew), iOffset);
              if( rc==SQLITE_OK && memcmp(aOld, aNew, sizeof(aNew)) ){
                rc = SQLITE_BUSY_SNAPSHOT;
              }
            }else if( sqlite3BitvecTestNotNull(pAllRead, sLoc.aPgno[i]) ){
              *piConflict = sLoc.aPgno[i];
              rc = SQLITE_BUSY_SNAPSHOT;
            }else if( (pPg = sqlite3PagerLookup(pPager, sLoc.aPgno[i])) ){
              /* Page aPgno[i], which is present in the pager cache, has been
              ** modified since the current CONCURRENT transaction was started.
              ** However it was not read by the current transaction, so is not
              ** a conflict. There are two possibilities: (a) the page was
              ** allocated at the of the file by the current transaction or 
              ** (b) was present in the cache at the start of the transaction.
              **
              ** For case (a), do nothing. This page will be moved within the
              ** database file by the commit code to avoid the conflict. The
              ** call to PagerUnref() is to release the reference grabbed by
              ** the sqlite3PagerLookup() above.  
              **
              ** In case (b), drop the page from the cache - otherwise
              ** following the snapshot upgrade the cache would be inconsistent
              ** with the database as stored on disk. */
              if( sqlite3PagerIswriteable(pPg) ){
                sqlite3PagerUnref(pPg);
              }else{
                sqlite3PcacheDrop(pPg);
              }
            }
          }
        }
        if( rc!=SQLITE_OK ) break;
          rc = walHashGet(pWal, iHash, &sLoc);
          if( rc==SQLITE_OK ){
            u32 i, iMin, iMax;
            assert( mxFrame>=sLoc.iZero );
            iMin = (sLoc.iZero >= iFirst) ? 1 : (iFirst - sLoc.iZero);
            iMax = (iHash==0) ? HASHTABLE_NPAGE_ONE : HASHTABLE_NPAGE;
            if( iMax>(mxFrame-sLoc.iZero) ) iMax = (mxFrame-sLoc.iZero);
            for(i=iMin; rc==SQLITE_OK && i<=iMax; i++){
              PgHdr *pPg;
              if( sLoc.aPgno[i]==1 ){
                /* Check that the schema cookie has not been modified. If
                ** it has not, the commit can proceed. */
                u8 aNew[4];
                u8 *aOld = &((u8*)pPage1->pData)[40];
                int sz;
                i64 iOff;
                u32 iFrame = sLoc.iZero + i;
                int iWal = 0;
                if( bWal2 ){
                  iWal = walExternalDecode(iFrame, &iFrame);
                }
                sz = pWal->hdr.szPage;
                sz = (sz&0xfe00) + ((sz&0x0001)<<16);
                iOff = walFrameOffset(iFrame, sz) + WAL_FRAME_HDRSIZE + 40;
                rc = sqlite3OsRead(pWal->apWalFd[iWal],aNew,sizeof(aNew),iOff);
                if( rc==SQLITE_OK && memcmp(aOld, aNew, sizeof(aNew)) ){
                  rc = SQLITE_BUSY_SNAPSHOT;
                }
              }else if( sqlite3BitvecTestNotNull(pAllRead, sLoc.aPgno[i]) ){
                *piConflict = sLoc.aPgno[i];
                rc = SQLITE_BUSY_SNAPSHOT;
              }else if( (pPg = sqlite3PagerLookup(pPager, sLoc.aPgno[i])) ){
                /* Page aPgno[i], which is present in the pager cache, has been
                ** modified since the current CONCURRENT transaction was
                ** started.  However it was not read by the current
                ** transaction, so is not a conflict. There are two
                ** possibilities: (a) the page was allocated at the of the file
                ** by the current transaction or (b) was present in the cache
                ** at the start of the transaction.
                **
                ** For case (a), do nothing. This page will be moved within the
                ** database file by the commit code to avoid the conflict. The
                ** call to PagerUnref() is to release the reference grabbed by
                ** the sqlite3PagerLookup() above.  
                **
                ** In case (b), drop the page from the cache - otherwise
                ** following the snapshot upgrade the cache would be
                ** inconsistent with the database as stored on disk. */
                if( sqlite3PagerIswriteable(pPg) ){
                  sqlite3PagerUnref(pPg);
                }else{
                  sqlite3PcacheDrop(pPg);
                }
              }
            }
          }
          if( rc!=SQLITE_OK ) break;
        }
      }
    }
  }

  pWal->nPriorFrame = pWal->hdr.mxFrame;
  return rc;
}
3220
3221
3222
3223
3224
3225
3226

3227
3228
3229
3230
3231
3232
3233
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009







+







  memcpy(&pWal->hdr, (void*)walIndexHdr(pWal), sizeof(WalIndexHdr));

  /* If this client has its read-lock on slot aReadmark[0] and the entire
  ** wal has not been checkpointed, switch it to a different slot. Otherwise
  ** any reads performed between now and committing the transaction will
  ** read from the old snapshot - not the one just upgraded to.  */
  if( pWal->readLock==0 && pWal->hdr.mxFrame!=walCkptInfo(pWal)->nBackfill ){
    assert( isWalMode2(pWal)==0 );
    rc = walUpgradeReadlock(pWal);
  }
  return rc;
}
#endif   /* SQLITE_OMIT_CONCURRENT */

/*
3260
3261
3262
3263
3264
3265
3266


3267

3268
3269



3270
3271
3272
3273
















3274
3275
3276
3277
3278
3279




3280

3281
3282
3283

3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296




3297
3298




3299
3300

3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311


3312

3313
3314
3315

3316
3317
3318
3319
3320
3321
3322
3323
3324
3325


3326
3327

3328

3329
3330

3331
3332
3333
3334
3335
3336

3337
3338
3339
3340


3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355




3356
3357
3358

3359
3360
3361
3362
3363
































3364

3365
3366
3367
3368
3369
3370
3371
4036
4037
4038
4039
4040
4041
4042
4043
4044

4045
4046

4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073


4074
4075
4076
4077
4078
4079
4080


4081


4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096


4097
4098
4099
4100
4101

4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115

4116
4117
4118

4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134

4135
4136

4137
4138
4139
4140
4141
4142

4143
4144
4145


4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158




4159
4160
4161
4162
4163
4164

4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202

4203
4204
4205
4206
4207
4208
4209
4210







+
+
-
+

-
+
+
+




+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+




-
-
+
+
+
+

+

-
-
+
-
-











+
+
+
+
-
-
+
+
+
+

-
+











+
+
-
+


-
+










+
+


+
-
+

-
+





-
+


-
-
+
+











-
-
-
-
+
+
+
+


-
+





+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
+







  Wal *pWal, 
  int (*xUndo)(void *, Pgno), 
  void *pUndoCtx,
  int bConcurrent                 /* True if this is a CONCURRENT transaction */
){
  int rc = SQLITE_OK;
  if( pWal->writeLock ){
    int iWal = walidxGetFile(&pWal->hdr);
    Pgno iMax = walidxGetMxFrame(&pWal->hdr, iWal);
    Pgno iMax = pWal->hdr.mxFrame;
    Pgno iNew;
    Pgno iFrame;
  

    assert( isWalMode2(pWal) || iWal==0 );

    /* Restore the clients cache of the wal-index header to the state it
    ** was in before the client began writing to the database. 
    */
    memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
    iNew = walidxGetMxFrame(&pWal->hdr, walidxGetFile(&pWal->hdr));

    /* BEGIN CONCURRENT transactions are different, as the header just
    ** memcpy()d into pWal->hdr may not be the same as the current header 
    ** when the transaction was started. Instead, pWal->hdr now contains
    ** the header written by the most recent successful COMMIT. Because
    ** Wal.writeLock is set, if this is a BEGIN CONCURRENT transaction,
    ** the rollback must be taking place because an error occurred during
    ** a COMMIT.
    **
    ** The code below is still valid. All frames between (iNew+1) and iMax 
    ** must have been written by this transaction before the error occurred.
    ** The exception is in wal2 mode - if the current wal file at the time
    ** of the last COMMIT is not wal file iWal, then the error must have
    ** occurred in WalLockForCommit(), before any pages were written
    ** to the database file. In this case return early.  */
#ifndef SQLITE_OMIT_CONCURRENT
    if( bConcurrent ){
      pWal->hdr.aCksum[0]++;
    }
#else
    UNUSED_PARAMETER(bConcurrent);
    if( walidxGetFile(&pWal->hdr)!=iWal ){
      assert( bConcurrent && isWalMode2(pWal) );
      return SQLITE_OK;
    }
#endif
    assert( walidxGetFile(&pWal->hdr)==iWal );

    for(iFrame=pWal->hdr.mxFrame+1; 
        ALWAYS(rc==SQLITE_OK) && iFrame<=iMax; 
    for(iFrame=iNew+1; ALWAYS(rc==SQLITE_OK) && iFrame<=iMax; iFrame++){
        iFrame++
    ){
      /* This call cannot fail. Unless the page for which the page number
      ** is passed as the second argument is (a) in the cache and 
      ** (b) has an outstanding reference, then xUndo is either a no-op
      ** (if (a) is false) or simply expels the page from the cache (if (b)
      ** is false).
      **
      ** If the upper layer is doing a rollback, it is guaranteed that there
      ** are no outstanding references to any page other than page 1. And
      ** page 1 is never written to the log until the transaction is
      ** committed. As a result, the call to xUndo may not fail.
      */
      Pgno pgno;
      if( isWalMode2(pWal) ){
        pgno = walFramePgno2(pWal, iWal, iFrame);
      }else{
      assert( walFramePgno(pWal, iFrame)!=1 );
      rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
        pgno = walFramePgno(pWal, iFrame);
      }
      assert( pgno!=1 );
      rc = xUndo(pUndoCtx, pgno);
    }
    if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
    if( iMax!=iNew ) walCleanupHash(pWal);
  }
  return rc;
}

/* 
** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32 
** values. This function populates the array with values required to 
** "rollback" the write position of the WAL handle back to the current 
** point in the event of a savepoint rollback (via WalSavepointUndo()).
*/
void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
  int iWal = walidxGetFile(&pWal->hdr);
  assert( isWalMode2(pWal) || iWal==0 );
  aWalData[0] = pWal->hdr.mxFrame;
  aWalData[0] = walidxGetMxFrame(&pWal->hdr, iWal);
  aWalData[1] = pWal->hdr.aFrameCksum[0];
  aWalData[2] = pWal->hdr.aFrameCksum[1];
  aWalData[3] = pWal->nCkpt;
  aWalData[3] = isWalMode2(pWal) ? iWal : pWal->nCkpt;
}

/* 
** Move the write position of the WAL back to the point identified by
** the values in the aWalData[] array. aWalData must point to an array
** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
** by a call to WalSavepoint().
*/
int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
  int rc = SQLITE_OK;
  int iWal = walidxGetFile(&pWal->hdr);
  int iCmp = isWalMode2(pWal) ? iWal : pWal->nCkpt;

  assert( pWal->writeLock || aWalData[0]==pWal->hdr.mxFrame );
  assert( isWalMode2(pWal) || iWal==0 );
  assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
  assert( aWalData[3]!=iCmp || aWalData[0]<=walidxGetMxFrame(&pWal->hdr,iWal) );

  if( aWalData[3]!=pWal->nCkpt ){
  if( aWalData[3]!=iCmp ){
    /* This savepoint was opened immediately after the write-transaction
    ** was started. Right after that, the writer decided to wrap around
    ** to the start of the log. Update the savepoint values to match.
    */
    aWalData[0] = 0;
    aWalData[3] = pWal->nCkpt;
    aWalData[3] = iCmp;
  }

  if( aWalData[0]<pWal->hdr.mxFrame ){
    pWal->hdr.mxFrame = aWalData[0];
  if( aWalData[0]<walidxGetMxFrame(&pWal->hdr, iWal) ){
    walidxSetMxFrame(&pWal->hdr, iWal, aWalData[0]);
    pWal->hdr.aFrameCksum[0] = aWalData[1];
    pWal->hdr.aFrameCksum[1] = aWalData[2];
    walCleanupHash(pWal);
  }

  return rc;
}

/*
** This function is called just before writing a set of frames to the log
** file (see sqlite3WalFrames()). It checks to see if, instead of appending
** to the current log file, it is possible to overwrite the start of the
** existing log file with the new frames (i.e. "reset" the log). If so,
** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
** unchanged.
** to the current log file, it is possible and desirable to switch to the
** other log file and write the new transaction to the start of it.
** If so, the wal-index header is updated accordingly - both in heap memory
** and in the *-shm file.
**
** SQLITE_OK is returned if no error is encountered (regardless of whether
** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
** or not the wal-index header is modified). An SQLite error code is returned
** if an error occurs.
*/
static int walRestartLog(Wal *pWal){
  int rc = SQLITE_OK;

  if( isWalMode2(pWal) ){
    int iApp = walidxGetFile(&pWal->hdr);
    int nWalSize = WAL_DEFAULT_WALSIZE;
    if( pWal->mxWalSize>0 ){
      nWalSize = (pWal->mxWalSize-WAL_HDRSIZE+pWal->szPage+WAL_FRAME_HDRSIZE-1) 
        / (pWal->szPage+WAL_FRAME_HDRSIZE);
      nWalSize = MAX(nWalSize, 1);
    }

    if( walidxGetMxFrame(&pWal->hdr, iApp)>=nWalSize ){
      volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
      u32 mxFrame = walidxGetMxFrame(&pWal->hdr, !iApp);
      if( mxFrame==0 || pInfo->nBackfill ){
        rc = wal2RestartOk(pWal, iApp);
        if( rc==SQLITE_OK ){
          int iNew = !iApp;
          pWal->nCkpt++;
          walidxSetFile(&pWal->hdr, iNew);
          walidxSetMxFrame(&pWal->hdr, iNew, 0);
          sqlite3Put4byte((u8*)&pWal->hdr.aSalt[0], pWal->hdr.aFrameCksum[0]);
          sqlite3Put4byte((u8*)&pWal->hdr.aSalt[1], pWal->hdr.aFrameCksum[1]);
          walIndexWriteHdr(pWal);
          pInfo->nBackfill = 0;
          wal2RestartFinished(pWal, iApp);
          walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
          pWal->readLock = iNew ? WAL_LOCK_PART2_FULL1 : WAL_LOCK_PART1_FULL2;
          rc = walLockShared(pWal, WAL_READ_LOCK(pWal->readLock));
        }else if( rc==SQLITE_BUSY ){
          rc = SQLITE_OK;
        }
      }
    }
  if( pWal->readLock==0 ){
  }else if( pWal->readLock==0 ){
    volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
    assert( pInfo->nBackfill==pWal->hdr.mxFrame );
    if( pInfo->nBackfill>0 ){
      u32 salt1;
      sqlite3_randomness(4, &salt1);
      rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
      if( rc==SQLITE_OK ){
3392
3393
3394
3395
3396
3397
3398

3399
3400
3401
3402
3403
3404
3405
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245







+







    ** only - never from the wal file. This means that if a writer holding
    ** a lock on aReadmark[0] were to commit a transaction but not close the
    ** read-transaction, subsequent read operations would read directly from
    ** the database file - ignoring the new pages just appended
    ** to the wal file. */
    rc = walUpgradeReadlock(pWal);
  }

  return rc;
}

/*
** Information about the current state of the WAL file and where
** the next fsync should occur - passed from sqlite3WalFrames() into
** walWriteToLog().
3450
3451
3452
3453
3454
3455
3456












3457
3458
3459
3460
3461
3462
3463
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315







+
+
+
+
+
+
+
+
+
+
+
+







  PgHdr *pPage,               /* The page of the frame to be written */
  int nTruncate,              /* The commit flag.  Usually 0.  >0 for commit */
  sqlite3_int64 iOffset       /* Byte offset at which to write */
){
  int rc;                         /* Result code from subfunctions */
  void *pData;                    /* Data actually written */
  u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */

#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  { 
    int iWal = walidxGetFile(&p->pWal->hdr);
    int iFrame = 1 + (iOffset / (WAL_FRAME_HDRSIZE + p->pWal->szPage));
    assert( p->pWal->apWalFd[iWal]==p->pFd );
    WALTRACE(("WAL%p: page %d written to frame %d of wal %d\n",
          p->pWal, (int)pPage->pgno, iFrame, iWal
    ));
  }
#endif

#if defined(SQLITE_HAS_CODEC)
  if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM_BKPT;
#else
  pData = pPage->pData;
#endif
  walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
  rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
3472
3473
3474
3475
3476
3477
3478
3479
3480

3481
3482
3483
3484

3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500

3501
3502
3503
3504
3505
3506
3507
3508

3509
3510
3511
3512
3513
3514
3515

3516
3517
3518
3519
3520
3521
3522
4324
4325
4326
4327
4328
4329
4330

4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352

4353
4354
4355
4356
4357
4358
4359
4360

4361
4362
4363
4364
4365
4366
4367

4368
4369
4370
4371
4372
4373
4374
4375







-

+




+















-
+







-
+






-
+







** one or more frames have been overwritten. It updates the checksums for
** all frames written to the wal file by the current transaction starting
** with the earliest to have been overwritten.
**
** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
*/
static int walRewriteChecksums(Wal *pWal, u32 iLast){
  const int szPage = pWal->szPage;/* Database page size */
  int rc = SQLITE_OK;             /* Return code */
  const int szPage = pWal->szPage;/* Database page size */
  u8 *aBuf;                       /* Buffer to load data from wal file into */
  u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-headers in */
  u32 iRead;                      /* Next frame to read from wal file */
  i64 iCksumOff;
  sqlite3_file *pWalFd = pWal->apWalFd[walidxGetFile(&pWal->hdr)];

  aBuf = sqlite3_malloc(szPage + WAL_FRAME_HDRSIZE);
  if( aBuf==0 ) return SQLITE_NOMEM_BKPT;

  /* Find the checksum values to use as input for the recalculating the
  ** first checksum. If the first frame is frame 1 (implying that the current
  ** transaction restarted the wal file), these values must be read from the
  ** wal-file header. Otherwise, read them from the frame header of the
  ** previous frame.  */
  assert( pWal->iReCksum>0 );
  if( pWal->iReCksum==1 ){
    iCksumOff = 24;
  }else{
    iCksumOff = walFrameOffset(pWal->iReCksum-1, szPage) + 16;
  }
  rc = sqlite3OsRead(pWal->pWalFd, aBuf, sizeof(u32)*2, iCksumOff);
  rc = sqlite3OsRead(pWalFd, aBuf, sizeof(u32)*2, iCksumOff);
  pWal->hdr.aFrameCksum[0] = sqlite3Get4byte(aBuf);
  pWal->hdr.aFrameCksum[1] = sqlite3Get4byte(&aBuf[sizeof(u32)]);

  iRead = pWal->iReCksum;
  pWal->iReCksum = 0;
  for(; rc==SQLITE_OK && iRead<=iLast; iRead++){
    i64 iOff = walFrameOffset(iRead, szPage);
    rc = sqlite3OsRead(pWal->pWalFd, aBuf, szPage+WAL_FRAME_HDRSIZE, iOff);
    rc = sqlite3OsRead(pWalFd, aBuf, szPage+WAL_FRAME_HDRSIZE, iOff);
    if( rc==SQLITE_OK ){
      u32 iPgno, nDbSize;
      iPgno = sqlite3Get4byte(aBuf);
      nDbSize = sqlite3Get4byte(&aBuf[4]);

      walEncodeFrame(pWal, iPgno, nDbSize, &aBuf[WAL_FRAME_HDRSIZE], aFrame);
      rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOff);
      rc = sqlite3OsWrite(pWalFd, aFrame, sizeof(aFrame), iOff);
    }
  }

  sqlite3_free(aBuf);
  return rc;
}

3538
3539
3540
3541
3542
3543
3544


3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561

3562

3563
3564
3565
3566
3567
3568

3569
3570
3571
3572
3573
3574
3575



3576








3577

3578
3579
3580
3581
3582

3583












3584

3585
3586
3587
3588
3589
3590

3591
3592
3593
3594
3595
3596
3597

3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611

3612
3613
3614
3615
3616
3617
3618
3619

3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636

3637



3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649

3650
3651
3652
3653
3654
3655
3656
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407







4408
4409
4410

4411
4412
4413
4414
4415
4416

4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427

4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441

4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455

4456

4457
4458
4459
4460

4461
4462
4463
4464
4465
4466
4467

4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481

4482
4483
4484
4485
4486
4487
4488
4489

4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506

4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522

4523
4524
4525
4526
4527
4528
4529
4530







+
+








-
-
-
-
-
-
-


+
-
+





-
+







+
+
+
-
+
+
+
+
+
+
+
+

+




-
+

+
+
+
+
+
+
+
+
+
+
+
+
-
+
-




-
+






-
+













-
+







-
+
















-
+

+
+
+











-
+







  PgHdr *pLast = 0;               /* Last frame in list */
  int nExtra = 0;                 /* Number of extra copies of last page */
  int szFrame;                    /* The size of a single frame */
  i64 iOffset;                    /* Next byte to write in WAL file */
  WalWriter w;                    /* The writer */
  u32 iFirst = 0;                 /* First frame that may be overwritten */
  WalIndexHdr *pLive;             /* Pointer to shared header */
  int iApp;
  int bWal2 = isWalMode2(pWal);

  assert( pList );
  assert( pWal->writeLock );

  /* If this frame set completes a transaction, then nTruncate>0.  If
  ** nTruncate==0 then this frame set does not complete the transaction. */
  assert( (isCommit!=0)==(nTruncate!=0) );

#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
    WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
              pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
  }
#endif

  pLive = (WalIndexHdr*)walIndexHdr(pWal);
  if( memcmp(&pWal->hdr, (void *)pLive, sizeof(WalIndexHdr))!=0 ){
    /* if( isWalMode2(pWal)==0 ) */
    iFirst = pLive->mxFrame+1;
    iFirst = walidxGetMxFrame(pLive, walidxGetFile(pLive))+1;
  }

  /* See if it is possible to write these frames into the start of the
  ** log file, instead of appending to it at pWal->hdr.mxFrame.
  */
  if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
  else if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
    return rc;
  }

  /* If this is the first frame written into the log, write the WAL
  ** header to the start of the WAL file. See comments at the top of
  ** this source file for a description of the WAL header format.
  */
  iApp = walidxGetFile(&pWal->hdr);
  iFrame = walidxGetMxFrame(&pWal->hdr, iApp);
  assert( iApp==0 || bWal2 );
  iFrame = pWal->hdr.mxFrame;

#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
    WALTRACE(("WAL%p: frame write begin. %d frames. iWal=%d. mxFrame=%d. %s\n",
              pWal, cnt, iApp, iFrame, isCommit ? "Commit" : "Spill"));
  }
#endif

  if( iFrame==0 ){
    u32 iCkpt = 0;
    u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
    u32 aCksum[2];                /* Checksum for wal-header */

    sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
    sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
    sqlite3Put4byte(&aWalHdr[4], pWal->hdr.iVersion);
    sqlite3Put4byte(&aWalHdr[8], szPage);
    if( bWal2 ){
      if( walidxGetMxFrame(&pWal->hdr, !iApp)>0 ){
        u8 aPrev[4];
        rc = sqlite3OsRead(pWal->apWalFd[!iApp], aPrev, 4, 12);
        if( rc!=SQLITE_OK ){
          return rc;
        }
        iCkpt = (sqlite3Get4byte(aPrev) + 1) & 0x0F;
      }
    }else{
      iCkpt = pWal->nCkpt;
    }
    sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
    sqlite3Put4byte(&aWalHdr[12], iCkpt);
    if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
    memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
    walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
    sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
    sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
    

    pWal->szPage = szPage;
    pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
    pWal->hdr.aFrameCksum[0] = aCksum[0];
    pWal->hdr.aFrameCksum[1] = aCksum[1];
    pWal->truncateOnCommit = 1;

    rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
    rc = sqlite3OsWrite(pWal->apWalFd[iApp], aWalHdr, sizeof(aWalHdr), 0);
    WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
    if( rc!=SQLITE_OK ){
      return rc;
    }

    /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
    ** all syncing is turned off by PRAGMA synchronous=OFF).  Otherwise
    ** an out-of-order write following a WAL restart could result in
    ** database corruption.  See the ticket:
    **
    **     https://sqlite.org/src/info/ff5be73dee
    */
    if( pWal->syncHeader ){
      rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags));
      rc = sqlite3OsSync(pWal->apWalFd[iApp], CKPT_SYNC_FLAGS(sync_flags));
      if( rc ) return rc;
    }
  }
  assert( (int)pWal->szPage==szPage );

  /* Setup information needed to write frames into the WAL */
  w.pWal = pWal;
  w.pFd = pWal->pWalFd;
  w.pFd = pWal->apWalFd[iApp];
  w.iSyncPoint = 0;
  w.syncFlags = sync_flags;
  w.szPage = szPage;
  iOffset = walFrameOffset(iFrame+1, szPage);
  szFrame = szPage + WAL_FRAME_HDRSIZE;

  /* Write all frames into the log file exactly once */
  for(p=pList; p; p=p->pDirty){
    int nDbSize;   /* 0 normally.  Positive == commit flag */

    /* Check if this page has already been written into the wal file by
    ** the current transaction. If so, overwrite the existing frame and
    ** set Wal.writeLock to WAL_WRITELOCK_RECKSUM - indicating that 
    ** checksums must be recomputed when the transaction is committed.  */
    if( iFirst && (p->pDirty || isCommit==0) ){
      u32 iWrite = 0;
      VVA_ONLY(rc =) sqlite3WalFindFrame(pWal, p->pgno, &iWrite);
      VVA_ONLY(rc =) walSearchWal(pWal, iApp, p->pgno, &iWrite);
      assert( rc==SQLITE_OK || iWrite==0 );
      if( iWrite && bWal2 ){
        walExternalDecode(iWrite, &iWrite);
      }
      if( iWrite>=iFirst ){
        i64 iOff = walFrameOffset(iWrite, szPage) + WAL_FRAME_HDRSIZE;
        void *pData;
        if( pWal->iReCksum==0 || iWrite<pWal->iReCksum ){
          pWal->iReCksum = iWrite;
        }
#if defined(SQLITE_HAS_CODEC)
        if( (pData = sqlite3PagerCodec(p))==0 ) return SQLITE_NOMEM;
#else
        pData = p->pData;
#endif
        rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOff);
        rc = sqlite3OsWrite(pWal->apWalFd[iApp], pData, szPage, iOff);
        if( rc ) return rc;
        p->flags &= ~PGHDR_WAL_APPEND;
        continue;
      }
    }

    iFrame++;
3683
3684
3685
3686
3687
3688
3689
3690

3691
3692
3693
3694
3695
3696
3697
4557
4558
4559
4560
4561
4562
4563

4564
4565
4566
4567
4568
4569
4570
4571







-
+







  ** boundary is crossed.  Only the part of the WAL prior to the last
  ** sector boundary is synced; the part of the last frame that extends
  ** past the sector boundary is written after the sync.
  */
  if( isCommit && WAL_SYNC_FLAGS(sync_flags)!=0 ){
    int bSync = 1;
    if( pWal->padToSectorBoundary ){
      int sectorSize = sqlite3SectorSize(pWal->pWalFd);
      int sectorSize = sqlite3SectorSize(w.pFd);
      w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
      bSync = (w.iSyncPoint==iOffset);
      testcase( bSync );
      while( iOffset<w.iSyncPoint ){
        rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
        if( rc ) return rc;
        iOffset += szFrame;
3718
3719
3720
3721
3722
3723
3724
3725

3726
3727
3728
3729

3730
3731
3732
3733
3734

3735
3736
3737
3738
3739
3740
3741
3742

3743
3744
3745
3746
3747
3748
3749









3750


3751
3752
3753
3754
3755
3756
3757
4592
4593
4594
4595
4596
4597
4598

4599
4600
4601
4602

4603
4604
4605
4606
4607

4608
4609
4610
4611
4612
4613
4614
4615

4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632

4633
4634
4635
4636
4637
4638
4639
4640
4641







-
+



-
+




-
+







-
+







+
+
+
+
+
+
+
+
+
-
+
+







  }

  /* Append data to the wal-index. It is not necessary to lock the 
  ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
  ** guarantees that there are no other writers, and no data that may
  ** be in use by existing readers is being overwritten.
  */
  iFrame = pWal->hdr.mxFrame;
  iFrame = walidxGetMxFrame(&pWal->hdr, iApp);
  for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
    if( (p->flags & PGHDR_WAL_APPEND)==0 ) continue;
    iFrame++;
    rc = walIndexAppend(pWal, iFrame, p->pgno);
    rc = walIndexAppend(pWal, iApp, iFrame, p->pgno);
  }
  while( rc==SQLITE_OK && nExtra>0 ){
    iFrame++;
    nExtra--;
    rc = walIndexAppend(pWal, iFrame, pLast->pgno);
    rc = walIndexAppend(pWal, iApp, iFrame, pLast->pgno);
  }

  if( rc==SQLITE_OK ){
    /* Update the private copy of the header. */
    pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
    testcase( szPage<=32768 );
    testcase( szPage>=65536 );
    pWal->hdr.mxFrame = iFrame;
    walidxSetMxFrame(&pWal->hdr, iApp, iFrame);
    if( isCommit ){
      pWal->hdr.iChange++;
      pWal->hdr.nPage = nTruncate;
    }
    /* If this is a commit, update the wal-index header too. */
    if( isCommit ){
      walIndexWriteHdr(pWal);
      if( bWal2 ){
        int iOther = !walidxGetFile(&pWal->hdr);
        if( walidxGetMxFrame(&pWal->hdr, iOther) 
            && !walCkptInfo(pWal)->nBackfill 
        ){
          pWal->iCallback = walidxGetMxFrame(&pWal->hdr, 0);
          pWal->iCallback += walidxGetMxFrame(&pWal->hdr, 1);
        }
      }else{
      pWal->iCallback = iFrame;
        pWal->iCallback = iFrame;
      }
    }
  }

  WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
  return rc;
}

3834
3835
3836
3837
3838
3839
3840
3841



3842
3843
3844
3845
3846
3847
3848
3849
3850














3851
3852
3853
3854
3855
3856
3857
4718
4719
4720
4721
4722
4723
4724

4725
4726
4727
4728
4729
4730
4731
4732
4733
4734


4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755







-
+
+
+







-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+







    if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
      sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
    }
  }

  /* Copy data from the log to the database file. */
  if( rc==SQLITE_OK ){
    if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
    if( (walPagesize(pWal)!=nBuf) 
     && ((pWal->hdr.mxFrame2 & 0x7FFFFFFF) || pWal->hdr.mxFrame)
    ){
      rc = SQLITE_CORRUPT_BKPT;
    }else{
      rc = walCheckpoint(pWal, db, eMode2, xBusy2, pBusyArg, sync_flags, zBuf);
    }

    /* If no error occurred, set the output variables. */
    if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
      if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
      if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
      if( pnLog ){
        *pnLog = walidxGetMxFrame(&pWal->hdr,0)+walidxGetMxFrame(&pWal->hdr,1);
      }
      if( pnCkpt ){
        if( isWalMode2(pWal) ){
          if( (int)(walCkptInfo(pWal)->nBackfill) ){
            *pnCkpt = walidxGetMxFrame(&pWal->hdr, !walidxGetFile(&pWal->hdr));
          }else{
            *pnCkpt = 0;
          }
        }else{
          *pnCkpt = walCkptInfo(pWal)->nBackfill;
        }
      }
    }
  }

  if( isChanged ){
    /* If a new wal-index header was loaded before the checkpoint was 
    ** performed, then the pager-cache associated with pWal is now
    ** out of date. So zero the cached wal-index header to ensure that
3905
3906
3907
3908
3909
3910
3911

3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922


3923
3924
3925

3926
3927


3928
3929
3930
3931
3932
3933
3934
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819


4820
4821
4822
4823

4824
4825

4826
4827
4828
4829
4830
4831
4832
4833
4834







+









-
-
+
+


-
+

-
+
+







** If op is negative, then do a dry-run of the op==1 case but do
** not actually change anything. The pager uses this to see if it
** should acquire the database exclusive lock prior to invoking
** the op==1 case.
*/
int sqlite3WalExclusiveMode(Wal *pWal, int op){
  int rc;

  assert( pWal->writeLock==0 );
  assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );

  /* pWal->readLock is usually set, but might be -1 if there was a 
  ** prior error while attempting to acquire are read-lock. This cannot 
  ** happen if the connection is actually in exclusive mode (as no xShmLock
  ** locks are taken in this case). Nor should the pager attempt to
  ** upgrade to exclusive-mode following such an error.
  */
  assert( pWal->readLock>=0 || pWal->lockError );
  assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
  assert( pWal->readLock!=WAL_LOCK_NONE || pWal->lockError );
  assert( pWal->readLock!=WAL_LOCK_NONE || (op<=0 && pWal->exclusiveMode==0) );

  if( op==0 ){
    if( pWal->exclusiveMode!=WAL_NORMAL_MODE ){
    if( pWal->exclusiveMode ){
      pWal->exclusiveMode = WAL_NORMAL_MODE;
      if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
      rc = walLockShared(pWal, WAL_READ_LOCK(pWal->readLock));
      if( rc!=SQLITE_OK ){
        pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
      }
      rc = pWal->exclusiveMode==WAL_NORMAL_MODE;
    }else{
      /* Already in locking_mode=NORMAL */
      rc = 0;
    }
3958
3959
3960
3961
3962
3963
3964



3965
3966
3967
3968

3969
3970
3971
3972
3973
3974
3975
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870

4871
4872
4873
4874
4875
4876
4877
4878







+
+
+



-
+







** every other subsystem, so the WAL module can put whatever it needs
** in the object.
*/
int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot){
  int rc = SQLITE_OK;
  WalIndexHdr *pRet;
  static const u32 aZero[4] = { 0, 0, 0, 0 };

  /* Snapshots may not be used with wal2 mode databases. */
  if( isWalMode2(pWal) ) return SQLITE_ERROR;

  assert( pWal->readLock>=0 && pWal->writeLock==0 );

  if( memcmp(&pWal->hdr.aFrameCksum[0],aZero,16)==0 ){
  if( memcmp(&pWal->hdr.aFrameCksum[0],aZero,8)==0 ){
    *ppSnapshot = 0;
    return SQLITE_ERROR;
  }
  pRet = (WalIndexHdr*)sqlite3_malloc(sizeof(WalIndexHdr));
  if( pRet==0 ){
    rc = SQLITE_NOMEM_BKPT;
  }else{
4012
4013
4014
4015
4016
4017
4018




4019
4020
4021
4022
4023
4024
4025
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932







+
+
+
+







** If the snapshot is not available, SQLITE_ERROR is returned. Or, if
** the CHECKPOINTER lock cannot be obtained, SQLITE_BUSY. If any error
** occurs (any value other than SQLITE_OK is returned), the CHECKPOINTER
** lock is released before returning.
*/
int sqlite3WalSnapshotCheck(Wal *pWal, sqlite3_snapshot *pSnapshot){
  int rc;

  /* Snapshots may not be used with wal2 mode databases. */
  if( isWalMode2(pWal) ) return SQLITE_ERROR;

  rc = walLockShared(pWal, WAL_CKPT_LOCK);
  if( rc==SQLITE_OK ){
    WalIndexHdr *pNew = (WalIndexHdr*)pSnapshot;
    if( memcmp(pNew->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))
     || pNew->mxFrame<walCkptInfo(pWal)->nBackfillAttempted
    ){
      rc = SQLITE_ERROR_SNAPSHOT;
4052
4053
4054
4055
4056
4057
4058
4059

4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073








4074
4959
4960
4961
4962
4963
4964
4965

4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989







-
+














+
+
+
+
+
+
+
+

  return (pWal ? pWal->szPage : 0);
}
#endif

/* Return the sqlite3_file object for the WAL file
*/
sqlite3_file *sqlite3WalFile(Wal *pWal){
  return pWal->pWalFd;
  return pWal->apWalFd[0];
}

/* 
** Return the values required by sqlite3_wal_info().
*/
int sqlite3WalInfo(Wal *pWal, u32 *pnPrior, u32 *pnFrame){
  int rc = SQLITE_OK;
  if( pWal ){
    *pnFrame = pWal->hdr.mxFrame;
    *pnPrior = pWal->nPriorFrame;
  }
  return rc;
}

/* 
** Return the journal mode used by this Wal object.
*/
int sqlite3WalJournalMode(Wal *pWal){
  assert( pWal );
  return (isWalMode2(pWal) ? PAGER_JOURNALMODE_WAL2 : PAGER_JOURNALMODE_WAL);
}

#endif /* #ifndef SQLITE_OMIT_WAL */

Changes to src/wal.h.

22
23
24
25
26
27
28
29

30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

48
49
50
51
52
53
54
55
56
57
58

59
60
61
62
63
64
65
22
23
24
25
26
27
28

29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58

59
60
61
62
63
64
65
66







-
+


















+










-
+







/* Macros for extracting appropriate sync flags for either transaction
** commits (WAL_SYNC_FLAGS(X)) or for checkpoint ops (CKPT_SYNC_FLAGS(X)):
*/
#define WAL_SYNC_FLAGS(X)   ((X)&0x03)
#define CKPT_SYNC_FLAGS(X)  (((X)>>2)&0x03)

#ifdef SQLITE_OMIT_WAL
# define sqlite3WalOpen(x,y,z)                   0
# define sqlite3WalOpen(w,x,y,z)                 0
# define sqlite3WalLimit(x,y)
# define sqlite3WalClose(v,w,x,y,z)              0
# define sqlite3WalBeginReadTransaction(y,z)     0
# define sqlite3WalEndReadTransaction(z)
# define sqlite3WalDbsize(y)                     0
# define sqlite3WalBeginWriteTransaction(y)      0
# define sqlite3WalEndWriteTransaction(x)        0
# define sqlite3WalUndo(w,x,y,z)                 0
# define sqlite3WalSavepoint(y,z)
# define sqlite3WalSavepointUndo(y,z)            0
# define sqlite3WalFrames(u,v,w,x,y,z)           0
# define sqlite3WalCheckpoint(q,r,s,t,u,v,w,x,y,z) 0
# define sqlite3WalCallback(z)                   0
# define sqlite3WalExclusiveMode(y,z)            0
# define sqlite3WalHeapMemory(z)                 0
# define sqlite3WalFramesize(z)                  0
# define sqlite3WalFindFrame(x,y,z)              0
# define sqlite3WalFile(x)                       0
# define sqlite3WalJournalMode(x)                0
#else

#define WAL_SAVEPOINT_NDATA 4

/* Connection to a write-ahead log (WAL) file. 
** There is one object of this type for each pager. 
*/
typedef struct Wal Wal;

/* Open and close a connection to a write-ahead log. */
int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *,int,i64,int,Wal**);
int sqlite3WalClose(Wal *pWal, sqlite3*, int sync_flags, int, u8 *);

/* Set the limiting size of a WAL file. */
void sqlite3WalLimit(Wal*, i64);

/* Used by readers to open (lock) and close (unlock) a snapshot.  A 
** snapshot is like a read-transaction.  It is the state of the database
150
151
152
153
154
155
156






157
158
159
160
161
162
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169







+
+
+
+
+
+






** stored in each frame (i.e. the db page-size when the WAL was created).
*/
int sqlite3WalFramesize(Wal *pWal);
#endif

/* Return the sqlite3_file object for the WAL file */
sqlite3_file *sqlite3WalFile(Wal *pWal);

/* Return the journal mode (WAL or WAL2) used by this Wal object. */
int sqlite3WalJournalMode(Wal *pWal);

/* sqlite3_wal_info() data */
int sqlite3WalInfo(Wal *pWal, u32 *pnPrior, u32 *pnFrame);

/* sqlite3_wal_info() data */
int sqlite3WalInfo(Wal *pWal, u32 *pnPrior, u32 *pnFrame);

#endif /* ifndef SQLITE_OMIT_WAL */
#endif /* SQLITE_WAL_H */

Changes to test/concfault.test.

78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
78
79
80
81
82
83
84









































85
86







-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-


  }
} -test {
  faultsim_test_result {0 {}} 
  catchsql { ROLLBACK }
  faultsim_integrity_check
}


#-------------------------------------------------------------------------
reset_db

do_execsql_test 2.0 {
  PRAGMA auto_vacuum = 0;
  PRAGMA journal_mode = wal;
  CREATE TABLE t1(a PRIMARY KEY, b);
  CREATE TABLE t2(a PRIMARY KEY, b);
  INSERT INTO t1 VALUES(randomblob(1000), randomblob(100));
  INSERT INTO t1 SELECT randomblob(1000), randomblob(1000) FROM t1;
  INSERT INTO t1 SELECT randomblob(1000), randomblob(1000) FROM t1;
  INSERT INTO t1 SELECT randomblob(1000), randomblob(1000) FROM t1;
  INSERT INTO t1 SELECT randomblob(1000), randomblob(1000) FROM t1;
  DELETE FROM t1 WHERE rowid%2;
} {wal}

faultsim_save_and_close
do_faultsim_test 1 -prep {
  faultsim_restore_and_reopen
  execsql {
    SELECT * FROM t1;
    BEGIN CONCURRENT;
      INSERT INTO t2 VALUES(1, 2);
  }
  sqlite3 db2 test.db
  execsql {
    PRAGMA journal_size_limit = 10000;
    INSERT INTO t1 VALUES(randomblob(1000), randomblob(1000));
  } db2
  db2 close
} -body {
  execsql { COMMIT }
} -test {
  faultsim_test_result {0 {}} 
  catchsql { ROLLBACK }
  set res [catchsql { SELECT count(*) FROM t1 }]
  if {$res!="0 9"} { error "expected {0 9} got {$res}" }
  faultsim_integrity_check
}

finish_test

Added test/concfault2.test.






































































1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
# 2018 Dec 28
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This file contains fault injection tests designed to test the concurrent
# transactions feature.
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl
source $testdir/malloc_common.tcl
set testprefix concfault2

ifcapable !concurrent {
  finish_test
  return
}

do_execsql_test 1.0 {
  PRAGMA auto_vacuum = 0;
  PRAGMA journal_mode = wal2;
  CREATE TABLE t1(a PRIMARY KEY, b);
  CREATE TABLE t2(a PRIMARY KEY, b);
  INSERT INTO t1 VALUES(randomblob(1000), randomblob(100));
  INSERT INTO t1 SELECT randomblob(1000), randomblob(1000) FROM t1;
  INSERT INTO t1 SELECT randomblob(1000), randomblob(1000) FROM t1;
  INSERT INTO t1 SELECT randomblob(1000), randomblob(1000) FROM t1;
  INSERT INTO t1 SELECT randomblob(1000), randomblob(1000) FROM t1;
  DELETE FROM t1 WHERE rowid%2;
} {wal2}

do_test 1.1 {
  list [expr [file size test.db-wal]>75000] [file size test.db-shm]
} {1 32768}

faultsim_save_and_close

do_faultsim_test 1 -prep {
  faultsim_restore_and_reopen
  execsql {
    SELECT * FROM t1;
    BEGIN CONCURRENT;
      INSERT INTO t2 VALUES(1, 2);
  }
  sqlite3 db2 test.db
  execsql {
    PRAGMA journal_size_limit = 10000;
    INSERT INTO t1 VALUES(randomblob(1000), randomblob(1000));
  } db2
  db2 close
} -body {
  execsql { COMMIT }
} -test {
  faultsim_test_result {0 {}} 
  catchsql { ROLLBACK }
  set res [catchsql { SELECT count(*) FROM t1 }]
  if {$res!="0 9"} { error "expected {0 9} got {$res}" }
  faultsim_integrity_check
}

finish_test

Changes to test/concurrent2.test.

18
19
20
21
22
23
24




25
26
27
28
29
30
31
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35







+
+
+
+







source $testdir/wal_common.tcl
set ::testprefix concurrent2

ifcapable !concurrent {
  finish_test
  return
}

do_test 0.1 {
  llength [sqlite3_wal_info db main]
} {2}

do_multiclient_test tn {

  do_test 1.$tn.1 {
    sql1 {
      PRAGMA journal_mode = wal;
      CREATE TABLE t1(x);

Changes to test/corruptA.test.

43
44
45
46
47
48
49
50

51
52
53
54
55
56
57
43
44
45
46
47
48
49

50
51
52
53
54
55
56
57







-
+







# Corrupt the file header in various ways and make sure the corruption
# is detected when opening the database file.
#
db close
forcecopy test.db test.db-template

set unreadable_version 02
ifcapable wal { set unreadable_version 03 }
ifcapable wal { set unreadable_version 04 }
do_test corruptA-2.1 {
  forcecopy test.db-template test.db
  hexio_write test.db 19 $unreadable_version   ;# the read format number
  sqlite3 db test.db
  catchsql {SELECT * FROM t1}  
} {1 {file is not a database}}
 

Changes to test/permutations.test.

426
427
428
429
430
431
432


433
434
435
436
437
438
439
440
441














442

443
444


445
446
447
448
449
450
451
426
427
428
429
430
431
432
433
434









435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461







+
+
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+

+


+
+







# Define the coverage related test suites:
#
#   coverage-wal
#
test_suite "coverage-wal" -description {
  Coverage tests for file wal.c.
} -files {
wal2big.test wal2recover.test wal2rewrite.test
wal2simple.test wal2snapshot.test wal2.test
  wal.test wal2.test wal3.test wal4.test wal5.test
  wal64k.test wal6.test wal7.test wal8.test wal9.test
  walbak.test walbig.test walblock.test walcksum.test walcrash2.test
  walcrash3.test walcrash4.test walcrash.test walfault.test walhook.test
  walmode.test walnoshm.test waloverwrite.test walpersist.test 
  walprotocol2.test walprotocol.test walro2.test walrofault.test 
  walro.test walshared.test walslow.test walvfs.test
  walfault2.test
  nockpt.test
wal3.test wal4.test wal5.test
wal64k.test wal6.test wal7.test wal8.test wal9.test
walbak.test walbig.test walblock.test walcksum.test 
walfault.test walhook.test walmode.test walnoshm.test
waloverwrite.test walpersist.test walprotocol2.test
walprotocol.test walro2.test walrofault.test walro.test
walshared.test walslow.test wal.test
wal2savepoint.test wal2lock.test wal2recover2.test

  wal2concurrent.test
  concurrent.test concurrent2.test concurrent3.test
  concurrent4.test concurrent5.test concurrent6.test
  concurrent7.test
  concfault.test concfault2.test

  walvfs.test walfault2.test nockpt.test
  snapshot2.test snapshot3.test snapshot4.test
  snapshot_fault.test snapshot.test snapshot_up.test
  walcrash2.test walcrash3.test walcrash4.test walcrash.test
  wal2fault.test
} 

test_suite "coverage-pager" -description {
  Coverage tests for file pager.c.
} -files {
  pager1.test    pager2.test  pagerfault.test  pagerfault2.test
  walfault.test  walbak.test  journal2.test    tkt-9d68c883.test
980
981
982
983
984
985
986

















987
988
989
990
991
992
993
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020







+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+







    insert.test   insert2.test  insert3.test rollback.test 
    select1.test  select2.test  select3.test
  }
}

test_suite "wal" -description {
  Run tests with journal_mode=WAL
} -initialize {
  set ::G(savepoint6_iterations) 100
} -shutdown {
  unset -nocomplain ::G(savepoint6_iterations)
} -files {
  savepoint.test     savepoint2.test     savepoint6.test
  trans.test         avtrans.test

  fts3aa.test  fts3ab.test  fts3ac.test  fts3ad.test
  fts3ae.test  fts3af.test  fts3ag.test  fts3ah.test
  fts3ai.test  fts3aj.test  fts3ak.test  fts3al.test
  fts3am.test  fts3an.test  fts3ao.test  fts3b.test
  fts3c.test   fts3d.test   fts3e.test   fts3query.test 
}

test_suite "wal2" -description {
  Run tests with journal_mode=WAL2
} -initialize {
  set ::G(savepoint6_iterations) 100
} -shutdown {
  unset -nocomplain ::G(savepoint6_iterations)
} -files {
  savepoint.test     savepoint2.test     savepoint6.test
  trans.test         avtrans.test

Changes to test/rdonly.test.

37
38
39
40
41
42
43
44

45
46
47
48
49
50
51
52

53
54
55
56
57
58
59
37
38
39
40
41
42
43

44
45
46
47
48
49
50
51

52
53
54
55
56
57
58
59







-
+







-
+







# returns 1 if the database N of connection D is read-only, 0 if it is
# read/write, or -1 if N is not the name of a database on connection D.
#
do_test rdonly-1.1.1 {
  sqlite3_db_readonly db main
} {0}

# Changes the write version from 1 to 3.  Verify that the database
# Changes the write version from 1 to 4.  Verify that the database
# can be read but not written.
#
do_test rdonly-1.2 {
  db close
  hexio_get_int [hexio_read test.db 18 1]
} 1
do_test rdonly-1.3 {
  hexio_write test.db 18 03
  hexio_write test.db 18 04
  sqlite3 db test.db
  execsql {
    SELECT * FROM t1;
  }
} {1}
do_test rdonly-1.3.1 {
  sqlite3_db_readonly db main
79
80
81
82
83
84
85
86

87
88
89
90
91
92
93
94
95
79
80
81
82
83
84
85

86
87
88
89
90
91
92
93
94
95







-
+










# Now, after connection [db] has loaded the database schema, modify the
# write-version of the file (and the change-counter, so that the 
# write-version is reloaded). This way, SQLite does not discover that
# the database is read-only until after it is locked.
#
set ro_version 02
ifcapable wal { set ro_version 03 }
ifcapable wal { set ro_version 04 }
do_test rdonly-1.6 {
  hexio_write test.db 18 $ro_version     ; # write-version
  hexio_write test.db 24 11223344        ; # change-counter
  catchsql {
    INSERT INTO t1 VALUES(2);
  }
} {1 {attempt to write a readonly database}}

finish_test

Changes to test/savepoint.test.

24
25
26
27
28
29
30

31
32
33
34
35
36
37
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38







+







do_test savepoint-1.1 {
  wal_set_journal_mode
  execsql {
    SAVEPOINT sp1;
    RELEASE sp1;
  }
} {}
wal_check_journal_mode savepoint-1.1
do_test savepoint-1.2 {
  execsql {
    SAVEPOINT sp1;
    ROLLBACK TO sp1;
  }
} {}
do_test savepoint-1.3 {
801
802
803
804
805
806
807

808

809
810
811
812
813
814
815
802
803
804
805
806
807
808
809

810
811
812
813
814
815
816
817







+
-
+







    CREATE TABLE t3(a, b, UNIQUE(a, b));
    ROLLBACK TO one;
  }
} {}
integrity_check savepoint-11.7
do_test savepoint-11.8 {
  execsql { ROLLBACK }
  db close
  execsql { PRAGMA wal_checkpoint }
  sqlite3 db test.db
  file size test.db
} {8192}

do_test savepoint-11.9 {
  execsql {
    DROP TABLE IF EXISTS t1;
    DROP TABLE IF EXISTS t2;

Changes to test/savepoint6.test.

11
12
13
14
15
16
17




18
19
20
21
22
23
24
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28







+
+
+
+







#
# $Id: savepoint6.test,v 1.4 2009/06/05 17:09:12 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

proc sql {zSql} {
  if {0 && $::debug_op} {
    puts stderr "$zSql ;"
    flush stderr
  }
  uplevel db eval [list $zSql]
  #puts stderr "$zSql ;"
}

set DATABASE_SCHEMA {
    PRAGMA auto_vacuum = incremental;
    CREATE TABLE t1(x, y);
63
64
65
66
67
68
69

70
71
72
73
74

75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91

92
93
94
95
96
97
98
99
100
101
102
103
104
105
106

107
108
109
110
111
112
113
114
115
116
117
118

119
120
121
122
123
124
125
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134







+





+

















+















+












+







#   rollback  NAME
#   release   NAME
#
#   insert_rows XVALUES
#   delete_rows XVALUES
#
proc savepoint {zName} {
  if {$::debug_op} { puts stderr "savepoint $zName" ; flush stderr }
  catch { sql "SAVEPOINT $zName" }
  lappend ::lSavepoint [list $zName [array get ::aEntry]]
}

proc rollback {zName} {
  if {$::debug_op} { puts stderr "rollback $zName" ; flush stderr }
  catch { sql "ROLLBACK TO $zName" }
  for {set i [expr {[llength $::lSavepoint]-1}]} {$i>=0} {incr i -1} {
    set zSavepoint [lindex $::lSavepoint $i 0]
    if {$zSavepoint eq $zName} {
      unset -nocomplain ::aEntry
      array set ::aEntry [lindex $::lSavepoint $i 1]


      if {$i+1 < [llength $::lSavepoint]} {
        set ::lSavepoint [lreplace $::lSavepoint [expr $i+1] end]
      }
      break
    }
  }
}

proc release {zName} {
  if {$::debug_op} { puts stderr "release $zName" ; flush stderr }
  catch { sql "RELEASE $zName" }
  for {set i [expr {[llength $::lSavepoint]-1}]} {$i>=0} {incr i -1} {
    set zSavepoint [lindex $::lSavepoint $i 0]
    if {$zSavepoint eq $zName} {
      set ::lSavepoint [lreplace $::lSavepoint $i end]
      break
    }
  }

  if {[llength $::lSavepoint] == 0} {
    #puts stderr "-- End of transaction!!!!!!!!!!!!!"
  }
}

proc insert_rows {lX} {
  if {$::debug_op} { puts stderr "insert_rows $lX" ; flush stderr }
  foreach x $lX {
    set y [x_to_y $x]

    # Update database [db]
    sql "INSERT OR REPLACE INTO t1 VALUES($x, '$y')"

    # Update the Tcl database.
    set ::aEntry($x) $y
  }
}

proc delete_rows {lX} {
  if {$::debug_op} { puts stderr "delete_rows $lX" ; flush stderr }
  foreach x $lX {
    # Update database [db]
    sql "DELETE FROM t1 WHERE x = $x"

    # Update the Tcl database.
    unset -nocomplain ::aEntry($x)
  }
159
160
161
162
163
164
165





166
167
168
169
170
171
172
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186







+
+
+
+
+







  set ret [list]
  for {set i 0} {$i<$nRes} {incr i} {
    lappend ret [expr int(rand()*$nRange)]
  }
  return $ret
} 
#-------------------------------------------------------------------------

set ::debug_op 0
proc debug_ops {} {
  set ::debug_op 1
}

proc database_op {} {
  set i [expr int(rand()*2)] 
  if {$i==0} {
    insert_rows [random_integers 100 1000]
  }
  if {$i==1} {
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
195
196
197
198
199
200
201



202
203
204
205
206
207
208







-
-
-







proc savepoint_op {} {
  set names {one two three four five}
  set cmds  {savepoint savepoint savepoint savepoint release rollback}

  set C [lindex $cmds [expr int(rand()*6)]]
  set N [lindex $names [expr int(rand()*5)]]

  #puts stderr "   $C $N ;  "
  #flush stderr

  $C $N
  return ok
}

expr srand(0)

############################################################################

Changes to test/tester.tcl.

587
588
589
590
591
592
593

594
595
596
597
598
599
600
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601







+







# Create a test database
#
proc reset_db {} {
  catch {db close}
  forcedelete test.db
  forcedelete test.db-journal
  forcedelete test.db-wal
  forcedelete test.db-wal2
  sqlite3 db ./test.db
  set ::DB [sqlite3_connection_pointer db]
  if {[info exists ::SETUP_SQL]} {
    db eval $::SETUP_SQL
  }
}
reset_db
2136
2137
2138
2139
2140
2141
2142
2143



2144
2145
2146
2147











2148
2149
2150
2151
2152




2153

2154
2155
2156
2157
2158
2159
2160
2137
2138
2139
2140
2141
2142
2143

2144
2145
2146
2147
2148


2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168

2169
2170
2171
2172
2173
2174
2175
2176







-
+
+
+


-
-
+
+
+
+
+
+
+
+
+
+
+





+
+
+
+
-
+







#     Otherwise (if not running a WAL permutation) this is a no-op.
#
#   wal_is_wal_mode
#
#     Returns true if this test should be run in WAL mode. False otherwise.
#
proc wal_is_wal_mode {} {
  expr {[permutation] eq "wal"}
  if {[permutation] eq "wal"} { return 1 }
  if {[permutation] eq "wal2"} { return 2 }
  return 0
}
proc wal_set_journal_mode {{db db}} {
  if { [wal_is_wal_mode] } {
    $db eval "PRAGMA journal_mode = WAL"
  switch -- [wal_is_wal_mode] {
    0 {
    }

    1 {
      $db eval "PRAGMA journal_mode = WAL"
    }

    2 {
      $db eval "PRAGMA journal_mode = WAL2"
    }
  }
}
proc wal_check_journal_mode {testname {db db}} {
  if { [wal_is_wal_mode] } {
    $db eval { SELECT * FROM sqlite_master }
    set expected "wal"
    if {[wal_is_wal_mode]==2} {
      set expected "wal2"
    }
    do_test $testname [list $db eval "PRAGMA main.journal_mode"] {wal}
    do_test $testname [list $db eval "PRAGMA main.journal_mode"] $expected
  }
}

proc wal_is_capable {} {
  ifcapable !wal { return 0 }
  if {[permutation]=="journaltest"} { return 0 }
  return 1

Changes to test/uri.test.

276
277
278
279
280
281
282
283

284
285
286
287

288
289
290
291
292
293
294
276
277
278
279
280
281
282

283
284
285
286

287
288
289
290
291
292
293
294







-
+



-
+







      CREATE TABLE aux.t2(a, b);
      PRAGMA main.journal_mode = WAL;
      PRAGMA aux.journal_mode = WAL;
      INSERT INTO t1 VALUES('x', 'y');
      INSERT INTO t2 VALUES('x', 'y');
    }
    lsort [array names ::T1]
  } {test.db1 test.db1-journal test.db1-wal}
  } {test.db1 test.db1-journal test.db1-wal test.db1-wal2}
  
  do_test 5.1.2 {
    lsort [array names ::T2]
  } {test.db2 test.db2-journal test.db2-wal}
  } {test.db2 test.db2-journal test.db2-wal test.db2-wal2}
  db close
  
  tvfs1 delete
  tvfs2 delete
}

#-------------------------------------------------------------------------

Changes to test/wal.test.

1170
1171
1172
1173
1174
1175
1176
1177

1178
1179
1180
1181
1182
1183
1184
1185
1186
1187

1188
1189
1190
1191
1192
1193
1194

1195
1196
1197
1198
1199
1200
1201
1170
1171
1172
1173
1174
1175
1176

1177
1178
1179
1180
1181
1182
1183
1184
1185
1186

1187
1188
1189
1190
1191
1192
1193

1194
1195
1196
1197
1198
1199
1200
1201







-
+









-
+






-
+







  5   2048    1
  6   4096    1
  7   8192    1
  8  16384    1
  9  32768    1
 10  65536    1
 11 131072    0
 11   1016    0
 12   1016    0
} {

  if {$::SQLITE_MAX_PAGE_SIZE < $pgsz} {
    set works 0
  }

  for {set pg 1} {$pg <= 3} {incr pg} {
    forcecopy testX.db test.db
    forcedelete test.db-wal
  

    # Check that the database now exists and consists of three pages. And
    # that there is no associated wal file.
    #
    do_test wal-18.2.$tn.$pg.1 { file exists test.db-wal } 0
    do_test wal-18.2.$tn.$pg.2 { file exists test.db } 1
    do_test wal-18.2.$tn.$pg.3 { file size test.db } [expr 1024*3]
  

    do_test wal-18.2.$tn.$pg.4 {

      # Create a wal file that contains a single frame (database page
      # number $pg) with the commit flag set. The frame checksum is
      # correct, but the contents of the database page are corrupt.
      #
      # The page-size in the log file header is set to $pgsz. If the
1219
1220
1221
1222
1223
1224
1225
1226

1227
1228
1229

1230
1231
1232
1233
1234
1235

1236
1237
1238
1239
1240
1241
1242
1219
1220
1221
1222
1223
1224
1225

1226
1227
1228

1229
1230
1231
1232
1233
1234

1235
1236
1237
1238
1239
1240
1241
1242







-
+


-
+





-
+








      set fd [open test.db-wal w]
      fconfigure $fd -encoding binary -translation binary
      puts -nonewline $fd $walhdr
      puts -nonewline $fd $framehdr
      puts -nonewline $fd $framebody
      close $fd
  

      file size test.db-wal
    } [wal_file_size 1 $pgsz]
  

    do_test wal-18.2.$tn.$pg.5 {
      sqlite3 db test.db
      set rc [catch { db one {PRAGMA integrity_check} } msg]
      expr { $rc!=0 || $msg!="ok" }
    } $works
  
 
    db close
  }
}

#-------------------------------------------------------------------------
# The following test - wal-19.* - fixes a bug that was present during
# development.

Added test/wal2big.test.








































































1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
# 2017 September 19
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the operation of the library in
# "PRAGMA journal_mode=WAL2" mode.
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl
source $testdir/lock_common.tcl
source $testdir/malloc_common.tcl
source $testdir/wal_common.tcl

set testprefix wal2big
ifcapable !wal {finish_test ; return }

do_execsql_test 1.0 {
  CREATE TABLE t1(a, b, c);
  CREATE INDEX t1a ON t1(a);
  CREATE INDEX t1b ON t1(b);
  CREATE INDEX t1c ON t1(c);
  PRAGMA journal_mode = wal2;
  PRAGMA journal_size_limit = 10000000;

  WITH s(i) AS (
    SELECT 1 UNION ALL SELECT i+1 FROM s WHERE i<200000
  )
  INSERT INTO t1 SELECT random(), random(), random() FROM s;
} {wal2 10000000}

do_execsql_test 1.1 {
  WITH s(i) AS (
    SELECT 1 UNION ALL SELECT i+1 FROM s WHERE i<200000
  )
  INSERT INTO t1 SELECT random(), random(), random() FROM s;
}

do_test 1.2 {
  list [expr [file size test.db-wal]>10000000] \
       [expr [file size test.db-wal2]>10000000]
} {1 1}

do_test 1.3 {
  sqlite3 db2 test.db
  execsql {
    SELECT count(*) FROM t1;
    PRAGMA integrity_check;
  } db2
} {400000 ok}

do_test 1.4 {
  db2 close
  forcecopy test.db test.db2
  forcecopy test.db-wal test.db2-wal
  forcecopy test.db-wal2 test.db2-wal2
  sqlite3 db2 test.db2
  execsql {
    SELECT count(*) FROM t1;
    PRAGMA integrity_check;
  }
} {400000 ok}

finish_test

Added test/wal2concurrent.test.





































































































































































1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
# 2018 December 6
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl
source $testdir/lock_common.tcl
set ::testprefix wal2concurrent

ifcapable !concurrent {
  finish_test
  return
}


#-------------------------------------------------------------------------
# Warm-body test.
#
foreach tn {1 2} {
  reset_db
  sqlite3 db2 test.db
  do_execsql_test 1.0 {
    PRAGMA page_size = 1024;
    CREATE TABLE t1(x);
    CREATE TABLE t2(y);
    PRAGMA journal_size_limit = 5000;
    PRAGMA journal_mode = wal2;
  } {5000 wal2}
  
  do_execsql_test 1.1 {
    INSERT INTO t1 VALUES(1);
    BEGIN CONCURRENT;
      INSERT INTO t1 VALUES(2);
  } {}
  
  do_test 1.2 {
    execsql { 
      PRAGMA journal_size_limit = 5000;
      INSERT INTO t1 VALUES(3) 
    } db2
    catchsql { COMMIT }
  } {1 {database is locked}}
  
  do_catchsql_test 1.3 { COMMIT   } {1 {database is locked}}
  do_catchsql_test 1.4 { ROLLBACK } {0 {}}
  
  do_test 1.5 {
    list [file size test.db-wal] [file size test.db-wal2]
  } {2128 0}
  
  do_execsql_test 1.6 {
    BEGIN CONCURRENT;
      INSERT INTO t1 VALUES(2);
  } {}
  
  do_test 1.7 {
    execsql { INSERT INTO t2 VALUES(randomblob(4000)) } db2
    list [file size test.db-wal] [file size test.db-wal2]
  } {7368 0}
  
  if {$tn==1} {
    do_test 1.8 {
      execsql { 
        INSERT INTO t2 VALUES(1);
        INSERT INTO t1 VALUES(5);
      } db2
      list [file size test.db-wal] [file size test.db-wal2]
    } {7368 2128}

    do_catchsql_test 1.9  { COMMIT   } {1 {database is locked}}
    do_catchsql_test 1.10 { ROLLBACK } {0 {}}
    db close
    sqlite3 db test.db
    do_execsql_test 1.11 { SELECT * FROM t1 } {1 3 5}
    do_execsql_test 1.12 { SELECT count(*) FROM t2 } {2}
  } else {
    do_test 1.8 {
      execsql { 
        INSERT INTO t2 VALUES(1);
      } db2
      list [file size test.db-wal] [file size test.db-wal2]
    } {7368 1080}

    do_catchsql_test 1.9  { COMMIT   } {0 {}}
    db close
    sqlite3 db test.db
    do_execsql_test 1.11 { SELECT * FROM t1 } {1 3 2}
    do_execsql_test 1.12 { SELECT count(*) FROM t2 } {2}

    do_test 1.13 {
      list [file size test.db-wal] [file size test.db-wal2]
    } {7368 2128}
  }
}

do_multiclient_test tn {
  do_test 2.$tn.1 {
    sql1 {
      PRAGMA auto_vacuum = OFF;
      CREATE TABLE t1(x UNIQUE);
      CREATE TABLE t2(x UNIQUE);
      PRAGMA journal_mode = wal2;
      PRAGMA journal_size_limit = 15000;
    }
  } {wal2 15000}

  do_test 2.$tn.2 {
    sql1 {
      WITH s(i) AS (
        SELECT 1 UNION ALL SELECT i+1 FROM s WHERE i<=10
      )
      INSERT INTO t1 SELECT randomblob(800) FROM s;
    }
  } {}

  do_test 2.$tn.3 {
    sql1 { DELETE FROM t1 WHERE (rowid%4)==0 }
    list [expr [file size test.db-wal]>15000] \
         [expr [file size test.db-wal2]>15000]
  } {1 0}

  do_test 2.$tn.4 {
    sql1 { PRAGMA wal_checkpoint; }
    sql1 { 
      BEGIN CONCURRENT;
        INSERT INTO t1 VALUES(randomblob(800));
    }
  } {}

  do_test 2.$tn.5 {
    sql2 { 
      PRAGMA journal_size_limit = 15000;
      INSERT INTO t2 VALUES(randomblob(800));
      INSERT INTO t2 VALUES(randomblob(800));
      INSERT INTO t2 VALUES(randomblob(800));
      INSERT INTO t2 VALUES(randomblob(800));
      INSERT INTO t2 VALUES(randomblob(800));
      DELETE FROM t2;
    }
    list [expr [file size test.db-wal]>15000] \
         [expr [file size test.db-wal2]>15000]
  } {1 1}

  do_test 2.$tn.6 {
    sql1 { 
        INSERT INTO t1 VALUES(randomblob(800));
      COMMIT;
      PRAGMA integrity_check;
    }
  } {ok}
}



finish_test

Added test/wal2fault.test.





















































1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
# 2010 May 03
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the operation of the library in
# "PRAGMA journal_mode=WAL" mode.
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl
source $testdir/malloc_common.tcl
source $testdir/lock_common.tcl

ifcapable !wal {finish_test ; return }
set testprefix wal2fault

do_execsql_test 1.0 {
  CREATE TABLE t1(x,y);
  PRAGMA journal_mode = wal2;
  WITH s(i) AS ( SELECT 100 UNION ALL SELECT i-1 FROM s WHERE (i-1)>0 )
  INSERT INTO t1 SELECT i, randomblob(i) FROM s;
  WITH s(i) AS ( SELECT 100 UNION ALL SELECT i-1 FROM s WHERE (i-1)>0 )
  INSERT INTO t1 SELECT i, randomblob(i) FROM s;
} {wal2}

do_test 1.1 {
  expr [file size test.db-wal]>10000
} {1}
faultsim_save_and_close

do_faultsim_test 1 -prep {
  faultsim_restore_and_reopen
  execsql {
    PRAGMA journal_size_limit = 10000;
    SELECT count(*) FROM sqlite_master;
  }
} -body {
  execsql {
    INSERT INTO t1 VALUES(1, 2);
  }
} -test {
  faultsim_test_result {0 {}}
}

finish_test

Added test/wal2lock.test.











































































































1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
# 2018 December 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the operation of the library in
# "PRAGMA journal_mode=WAL2" mode.
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl
source $testdir/lock_common.tcl
source $testdir/malloc_common.tcl
source $testdir/wal_common.tcl

set testprefix wal2lock
ifcapable !wal {finish_test ; return }

db close
testvfs tvfs 
sqlite3 db test.db -vfs tvfs

do_execsql_test 1.0 {
  PRAGMA journal_mode = wal2;
  CREATE TABLE y1(y, yy);
  CREATE INDEX y1y ON y1(y);
  CREATE INDEX y1yy ON y1(yy);
  INSERT INTO y1 VALUES(1, 2), (3, 4), (5, 6);
} {wal2}

tvfs script vfs_callback
tvfs filter xShmLock

set ::lock [list]
proc vfs_callback {func file name lock} {
  lappend ::lock $lock
  return SQLITE_OK
}

do_execsql_test 1.1.1 {
  SELECT * FROM y1
} {1 2 3 4 5 6}
do_test 1.1.2 {
  set ::lock
} {{4 1 lock shared} {4 1 unlock shared}}

set ::bFirst 1
proc vfs_callback {func file name lock} {
  if {$::bFirst} {
    set ::bFirst 0
    return SQLITE_BUSY
  }
  return SQLITE_OK
}
do_execsql_test 1.2 {
  SELECT * FROM y1
} {1 2 3 4 5 6}

set ::bFirst 1
proc vfs_callback {func file name lock} {
  if {$::bFirst} {
    set ::bFirst 0
    return SQLITE_IOERR
  }
  return SQLITE_OK
}
do_catchsql_test 1.3 {
  SELECT * FROM y1
} {1 {disk I/O error}}

puts "# Warning: This next test case causes SQLite to call xSleep(1) 100 times."
puts "# Normally this equates to a delay of roughly 10 seconds, but if SQLite"
puts "# is built on unix without HAVE_USLEEP defined, it may be much longer."
proc vfs_callback {func file name lock} { return SQLITE_BUSY }
do_catchsql_test 1.4 {
  SELECT * FROM y1
} {1 {locking protocol}}
proc vfs_callback {func file name lock} { return SQLITE_OK }

sqlite3 db2 test.db -vfs tvfs
set ::bFirst 1

proc vfs_callback {func file name lock} {
  if {$::bFirst} {
    set ::bFirst 0
    db2 eval { INSERT INTO y1 VALUES(7, 8) }
  }
}

do_execsql_test 1.5.1 {
  SELECT * FROM y1
} {1 2 3 4 5 6 7 8}
do_execsql_test 1.5.2 {
  SELECT * FROM y1
} {1 2 3 4 5 6 7 8}

db close
db2 close
tvfs delete
finish_test

Added test/wal2recover.test.










































































































































































































































































1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
# 2018 December 13
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the operation of the library in
# "PRAGMA journal_mode=WAL2" mode.
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl
source $testdir/lock_common.tcl
source $testdir/malloc_common.tcl
source $testdir/wal_common.tcl

set testprefix wal2recover
ifcapable !wal {finish_test ; return }

proc db_copy {from to} {
  forcecopy $from $to
  forcecopy ${from}-wal ${to}-wal
  forcecopy ${from}-wal2 ${to}-wal2
}

do_execsql_test 1.0 {
  CREATE TABLE t1(a, b, c);
  CREATE INDEX t1a ON t1(a);
  CREATE INDEX t1b ON t1(b);
  CREATE INDEX t1c ON t1(c);
  PRAGMA journal_mode = wal2;
  PRAGMA journal_size_limit = 15000;
  PRAGMA wal_autocheckpoint = 0;
} {wal2 15000 0}

do_test 1.1 {
  for {set i 1} {$i <= 1000} {incr i} {
    execsql { INSERT INTO t1 VALUES(random(), random(), random()) }
    db_copy test.db test.db2
    sqlite3 db2 test.db
    set res [execsql {
      SELECT count(*) FROM t1;
      PRAGMA integrity_check;
    } db2]
    db2 close
    if {$res != [list $i ok]} {
      error "failure on iteration $i"
    }
  }
  set {} {}
} {}

#--------------------------------------------------------------------------
reset_db
do_execsql_test 2.0 {
  CREATE TABLE t1(x UNIQUE);
  CREATE TABLE t2(x UNIQUE);
  PRAGMA journal_mode = wal2;
  PRAGMA journal_size_limit = 10000;
  PRAGMA wal_autocheckpoint = 0;
  BEGIN;
    INSERT INTO t1 VALUES(randomblob(4000));
    INSERT INTO t1 VALUES(randomblob(4000));
    INSERT INTO t1 VALUES(randomblob(4000));
  COMMIT;
  BEGIN;
    INSERT INTO t2 VALUES(randomblob(4000));
    INSERT INTO t2 VALUES(randomblob(4000));
    INSERT INTO t2 VALUES(randomblob(4000));
  COMMIT;
} {wal2 10000 0}
do_test 2.0.1 {
  list [file size test.db] [file size test.db-wal] [file size test.db-wal2]
} {5120 28328 28328}

# Test recovery with both wal files intact.
#
do_test 2.1 {
  db_copy test.db test.db2
  sqlite3 db2 test.db2
  execsql {
    SELECT count(*) FROM t1;
    SELECT count(*) FROM t2;
    PRAGMA integrity_check;
  } db2
} {3 3 ok}

do_test 2.2 {
  db2 close
  db_copy test.db test.db2
  hexio_write test.db2-wal 16 12345678
  sqlite3 db2 test.db2
  execsql {
    SELECT count(*) FROM t1;
    SELECT count(*) FROM t2;
  } db2
} {0 3}

do_test 2.3 {
  db2 close
  db_copy test.db test.db2
  hexio_write test.db2-wal2 16 12345678
  sqlite3 db2 test.db2
  execsql {
    SELECT count(*) FROM t1;
    SELECT count(*) FROM t2;
    PRAGMA integrity_check;
  } db2
} {3 0 ok}

do_test 2.4 {
  db2 close
  db_copy test.db test.db2
  forcecopy test.db-wal test.db2-wal2
  sqlite3 db2 test.db2
  execsql {
    SELECT count(*) FROM t1;
    SELECT count(*) FROM t2;
    PRAGMA integrity_check;
  } db2
} {3 0 ok}

do_test 2.5 {
  db2 close
  db_copy test.db test.db2
  forcecopy test.db-wal  test.db2-wal2
  forcecopy test.db-wal2  test.db2-wal
  sqlite3 db2 test.db2
  execsql {
    SELECT count(*) FROM t1;
    SELECT count(*) FROM t2;
    PRAGMA integrity_check;
  } db2
} {3 3 ok}

do_test 2.6 {
  db2 close
  db_copy test.db test.db2
  forcecopy test.db-wal test.db2-wal2
  close [open test.db-wal w]
  sqlite3 db2 test.db2
  execsql {
    SELECT count(*) FROM t1;
    SELECT count(*) FROM t2;
    PRAGMA integrity_check;
  } db2
} {3 0 ok}

do_test 2.7 {
  db2 close
  db_copy test.db test.db2
  forcedelete test.db2-wal
  sqlite3 db2 test.db2
  execsql {
    SELECT count(*) FROM t1;
    SELECT count(*) FROM t2;
    PRAGMA integrity_check;
  } db2
} {0 0 ok}

#-------------------------------------------------------------------------
#
reset_db
do_execsql_test 3.0 {
  CREATE TABLE t1(a TEXT, b TEXT, c TEXT);
  CREATE INDEX t1a ON t1(a);
  CREATE INDEX t1b ON t1(b);
  CREATE INDEX t1c ON t1(c);
  PRAGMA journal_mode = wal2;
  PRAGMA journal_size_limit = 10000;
  PRAGMA wal_autocheckpoint = 0;
  PRAGMA cache_size = 5;
} {wal2 10000 0}

do_execsql_test 3.1 {
  WITH s(i) AS ( SELECT 1 UNION ALL SELECT i+1 FROM s where i < 200)
  INSERT INTO t1 SELECT i, i, i FROM s;

  INSERT INTO t1 VALUES(201, 201, 201);
} {}

do_test 3.2 {
  list [file size test.db] [file size test.db-wal] [file size test.db-wal2]
} {5120 15752 4224}

do_test 3.3 {
  forcecopy test.db test.db2
  forcecopy test.db-wal test.db2-wal
  forcecopy test.db-wal2 test.db2-wal2
  sqlite3 db2 test.db2
  execsql {
    PRAGMA journal_size_limit = 10000;
    PRAGMA wal_autocheckpoint = 0;
    PRAGMA cache_size = 5;
    BEGIN;
      WITH s(i) AS ( SELECT 1 UNION ALL SELECT i+1 FROM s where i < 200)
      INSERT INTO t1 SELECT i, i, i FROM s;
  } db2
  list [file size test.db2] [file size test.db2-wal] [file size test.db2-wal2]
} {5120 15752 23088}

do_test 3.4 {
  set fd [open test.db2-shm]
  fconfigure $fd -encoding binary -translation binary
  set data [read $fd]
  close $fd

  set fd [open test.db-shm w]
  fconfigure $fd -encoding binary -translation binary
  puts -nonewline $fd $data
  close $fd

  execsql {
    WITH s(i) AS ( SELECT 1 UNION ALL SELECT i+1 FROM s where i < 10)
      INSERT INTO t1 SELECT i, i, i FROM s;
    SELECT count(*) FROM t1;
    PRAGMA integrity_check;
  }
} {211 ok}

do_test 3.5 {
  list [file size test.db] [file size test.db-wal] [file size test.db-wal2]
} {5120 15752 18896}

#-------------------------------------------------------------------------
#
reset_db
do_execsql_test 4.0 {
  PRAGMA journal_mode = wal2;
  CREATE TABLE xyz(x, y, z);
  INSERT INTO xyz VALUES('x', 'y', 'z');
} {wal2}
db close
do_test 4.1 {
  close [open test.db-wal w]
  file mkdir test.db-wal2
  sqlite3 db test.db
  catchsql { SELECT * FROM xyz }
} {1 {unable to open database file}}
db close
file delete test.db-wal2

do_test 4.2 {
  sqlite3 db test.db
  execsql { 
    INSERT INTO xyz VALUES('a', 'b', 'c');
  }
  forcecopy test.db test.db2
  forcecopy test.db-wal test.db2-wal
  forcedelete test.db2-wal2
  file mkdir test.db2-wal2
  sqlite3 db2 test.db2
  catchsql { SELECT * FROM xyz } db2
} {1 {unable to open database file}}
db2 close
file delete test.db2-wal2


finish_test

Added test/wal2recover2.test.


























































































































































































































































































































1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
# 2018 December 13
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the operation of the library in
# "PRAGMA journal_mode=WAL2" mode.
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl
source $testdir/lock_common.tcl
source $testdir/malloc_common.tcl
source $testdir/wal_common.tcl

set testprefix wal2recover2
ifcapable !wal {finish_test ; return }

do_execsql_test 1.0 {
  CREATE TABLE t1(x);
  CREATE TABLE t2(x);
  WITH s(i) AS ( VALUES(1) UNION ALL SELECT i+1 FROM s WHERE i<1500 )
    INSERT INTO t1 SELECT i FROM s;
  WITH s(i) AS ( VALUES(1) UNION ALL SELECT i+1 FROM s WHERE i<1500 )
    INSERT INTO t2 SELECT i FROM s;

  PRAGMA journal_mode = wal2;
  PRAGMA journal_size_limit = 10000;
} {wal2 10000}

set ::L 1125750
set ::M 1126500
set ::H 1127250

do_execsql_test 1.1 {
  UPDATE t1 SET x=x+1;
  UPDATE t2 SET x=x+1 WHERE rowid<=750;

  SELECT sum(x) FROM t1;
  SELECT sum(x) FROM t2;
} [list $H $M]

do_test 1.2 {
  list [file size test.db] [file size test.db-wal] [file size test.db-wal2]
} {31744 14704 7368}

proc cksum {zIn data} {
  if {[string length $zIn]==0} {
    set s0 0
    set s1 0
  } else {
    set s0 [hexio_get_int [string range $zIn 0 7]]
    set s1 [hexio_get_int [string range $zIn 8 15]]
  }
  set n [expr [string length $data] / 8]

  for {set i 0} {$i < $n} {incr i 2} {
    set x0 [hexio_get_int -l [string range $data [expr $i*8]   [expr $i*8+7]]]
    set x1 [hexio_get_int -l [string range $data [expr $i*8+8] [expr $i*8+8+7]]]

    set s0 [expr ($s0 + $x0 + $s1) & 0xFFFFFFFF]
    set s1 [expr ($s1 + $x1 + $s0) & 0xFFFFFFFF]
  }

  return "[hexio_render_int32 $s0][hexio_render_int32 $s1]"
}

proc fix_wal_cksums {file} {
  # Fix the checksum on the wal header.
  set data [hexio_read $file 0 32]
  set cksum [cksum {} [string range $data 0 47]]
  set salt [hexio_read $file 16 8]
  hexio_write $file 24 $cksum

  # Fix the checksums for all pages in the wal file.
  set pgsz [hexio_get_int [hexio_read $file 8 4]]
  set sz [file size $file]
  for {set off 32} {$off < $sz} {incr off [expr $pgsz+24]} {
    set e [hexio_read $file $off 8]
    set cksum [cksum $cksum $e]

    set p [hexio_read $file [expr $off+24] $pgsz]
    set cksum [cksum $cksum $p]

    hexio_write $file [expr $off+8] $salt
    hexio_write $file [expr $off+16] $cksum
  }
}

proc wal_incr_hdrfield {file field} {
  switch -- $field {
    nCkpt { set offset 12 }
    salt0 { set offset 16 }
    salt1 { set offset 20 }
    default {
      error "unknown field $field - should be \"nCkpt\", \"salt0\" or \"salt1\""
    }
  }

  # Increment the value in the wal header.
  set v [hexio_get_int [hexio_read $file $offset 4]]
  incr v
  hexio_write $file $offset [hexio_render_int32 $v]
  
  # Fix various checksums
  fix_wal_cksums $file
}

proc wal_set_nckpt {file val} {
  # Increment the value in the wal header.
  hexio_write $file 12 [hexio_render_int32 $val]
  
  # Fix various checksums
  fix_wal_cksums $file
}

proc wal_set_follow {file prevfile} {
  set pgsz [hexio_get_int [hexio_read $prevfile 8 4]]
  set sz [file size $prevfile]
  set cksum [hexio_read $prevfile [expr $sz-$pgsz-8] 8]

  hexio_write $file 16 $cksum
  fix_wal_cksums $file
}

foreach {tn file field} {
  1 test.db2-wal    salt0
  2 test.db2-wal    salt1
  3 test.db2-wal    nCkpt
  4 test.db2-wal2   salt0
  5 test.db2-wal2   salt1
  6 test.db2-wal2   nCkpt
} {
  do_test 1.3.$tn {
    forcecopy test.db test.db2
    forcecopy test.db-wal test.db2-wal
    forcecopy test.db-wal2 test.db2-wal2
    wal_incr_hdrfield $file $field
    sqlite3 db2 test.db2
    execsql {
      SELECT sum(x) FROM t1;
      SELECT sum(x) FROM t2;
    } db2
  } [list $H $L]
  db2 close
}

do_test 1.4 {
  forcecopy test.db test.db2
  forcecopy test.db-wal2 test.db2-wal
  forcedelete test.db2-wal2
  sqlite3 db2 test.db2
  execsql {
    SELECT sum(x) FROM t1;
    SELECT sum(x) FROM t2;
  } db2
} [list $L $M]

do_test 1.5 {
  forcecopy test.db test.db2
  forcecopy test.db-wal2 test.db2-wal
  forcecopy test.db-wal test.db2-wal2
  sqlite3 db2 test.db2
  execsql {
    SELECT sum(x) FROM t1;
    SELECT sum(x) FROM t2;
  } db2
} [list $H $M]

foreach {tn file field} {
  1 test.db2-wal    salt0
  2 test.db2-wal    salt1
  3 test.db2-wal2   salt0
  4 test.db2-wal2   salt1
} {
  do_test 1.6.$tn {
    forcecopy test.db test.db2
    forcecopy test.db-wal2 test.db2-wal
    forcecopy test.db-wal test.db2-wal2
    wal_incr_hdrfield $file $field
    sqlite3 db2 test.db2
    execsql {
      SELECT sum(x) FROM t1;
      SELECT sum(x) FROM t2;
    } db2
  } [list $H $L]
  db2 close
}

foreach {tn nCkpt1 nCkpt2 res} [list \
  1   2 1   "$H $M"                  \
  2   2 2   "$L $M"                  \
  3   3 1   "$H $L"                  \
  4   15 14 "$H $M"                  \
  5   0 15  "$H $M"                  \
  6   1 15  "$L $M"                  \
] {
  do_test 1.7.$tn {
    forcecopy test.db test.db2
    forcecopy test.db-wal2 test.db2-wal
    forcecopy test.db-wal test.db2-wal2

    wal_set_nckpt test.db2-wal2 $nCkpt2
    wal_set_nckpt test.db2-wal  $nCkpt1
    wal_set_follow test.db2-wal test.db2-wal2


    sqlite3 db2 test.db2
    execsql {
      SELECT sum(x) FROM t1;
      SELECT sum(x) FROM t2;
    } db2
  } $res
  db2 close
}


#-------------------------------------------------------------------------
reset_db
do_execsql_test 1.8.1 {
  PRAGMA autovacuum = 0;
  PRAGMA page_size = 4096;
  CREATE TABLE t1(x);
  CREATE TABLE t2(x);
  WITH s(i) AS ( VALUES(1) UNION ALL SELECT i+1 FROM s WHERE i<1500 )
    INSERT INTO t1 SELECT i FROM s;
  WITH s(i) AS ( VALUES(1) UNION ALL SELECT i+1 FROM s WHERE i<1500 )
    INSERT INTO t2 SELECT i FROM s;

  PRAGMA journal_mode = wal2;
  PRAGMA journal_size_limit = 10000;

  WITH s(i) AS ( VALUES(1) UNION ALL SELECT i+1 FROM s WHERE i<1500 )
    INSERT INTO t2 SELECT i FROM s;
} {wal2 10000}

do_test 1.8.2 {
  list [file size test.db-wal] [file size test.db-wal2]
} {24752 0}

do_execsql_test 1.8.3 { PRAGMA user_version = 123 }
do_test 1.8.4 {
  list [file size test.db-wal] [file size test.db-wal2]
} {24752 4152}

do_test 1.8.5 {
  hexio_write test.db-wal2 [expr 56+16] 0400
  fix_wal_cksums test.db-wal2
} {}

do_test 1.8.6 {
  forcecopy test.db test.db2
  forcecopy test.db-wal test.db2-wal
  forcecopy test.db-wal2 test.db2-wal2
  sqlite3 db2 test.db2
  catchsql { SELECT * FROM sqlite_master } db2
} {1 {database disk image is malformed}}
db2 close

#-------------------------------------------------------------------------
reset_db
do_execsql_test 1.0 {
  CREATE TABLE t1(a, b, c);
  CREATE INDEX t1a ON t1(a);
  CREATE INDEX t1b ON t1(b);
  CREATE INDEX t1c ON t1(c);
  PRAGMA journal_mode = wal2;

  INSERT INTO t1 VALUES(randomblob(50), randomblob(50), randomblob(50));
  INSERT INTO t1 VALUES(randomblob(50), randomblob(50), randomblob(50));
  INSERT INTO t1 VALUES(randomblob(50), randomblob(50), randomblob(50));
  PRAGMA journal_size_limit = 5000;
  INSERT INTO t1 VALUES(randomblob(50), randomblob(50), randomblob(50));
  INSERT INTO t1 VALUES(randomblob(50), randomblob(50), randomblob(50));
  INSERT INTO t1 VALUES(randomblob(50), randomblob(50), randomblob(50));
  INSERT INTO t1 VALUES(randomblob(50), randomblob(50), randomblob(50));
  INSERT INTO t1 VALUES(randomblob(50), randomblob(50), randomblob(50));
} {wal2 5000}

do_test 2.1 {
  forcecopy test.db test.db2
  forcecopy test.db-wal2 test.db2-wal
  forcecopy test.db-wal test.db2-wal2
  
  hexio_write test.db2-wal 5000 1234567890
} {5}

do_test 2.2 {
  sqlite3 db2 test.db2
  breakpoint
  execsql {
    SELECT count(*) FROM t1;
    PRAGMA integrity_check
  } db2
} {4 ok}

do_test 2.3 {
  execsql {
    INSERT INTO t1 VALUES(randomblob(50), randomblob(50), randomblob(50));
    SELECT count(*) FROM t1;
    PRAGMA integrity_check
  } db2
} {5 ok}


finish_test

Added test/wal2rewrite.test.





























































































1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
# 2017 September 19
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the operation of the library in
# "PRAGMA journal_mode=WAL2" mode.
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl
source $testdir/lock_common.tcl
source $testdir/malloc_common.tcl
source $testdir/wal_common.tcl

set testprefix wal2rewrite
ifcapable !wal {finish_test ; return }

proc filesize {filename} {
  if {[file exists $filename]} {
    return [file size $filename]
  }
  return 0
}

foreach {tn jrnlmode} {
  1 wal
  2 wal2
} {
  reset_db
  execsql "PRAGMA journal_mode = $jrnlmode"
  do_execsql_test $tn.1 {
    PRAGMA journal_size_limit = 10000;
    PRAGMA cache_size = 5;
    PRAGMA wal_autocheckpoint = 10;
  
    CREATE TABLE t1(a INTEGER PRIMARY KEY, b INTEGER, c BLOB);
    CREATE INDEX t1b ON t1(b);
    CREATE INDEX t1c ON t1(c);
  
    WITH s(i) AS (
      SELECT 1 UNION SELECT i+1 FROM s WHERE i<10
    )
    INSERT INTO t1 SELECT i, i, randomblob(800) FROM s;
  } {10000 10}
  
  for {set i 0} {$i < 4} {incr i} {
    do_execsql_test $tn.$i.1 {
      UPDATE t1 SET c=randomblob(800) WHERE (b%10)==5 AND ($i%2)
    }
    do_execsql_test $tn.$i.2 {
      BEGIN;
      UPDATE t1 SET b=b+10, c=randomblob(800);
      UPDATE t1 SET b=b+10, c=randomblob(800);
      UPDATE t1 SET b=b+10, c=randomblob(800);
      UPDATE t1 SET b=b+10, c=randomblob(800);
      UPDATE t1 SET b=b+10, c=randomblob(800);
      UPDATE t1 SET b=b+10, c=randomblob(800);
      UPDATE t1 SET b=b+10, c=randomblob(800);
      UPDATE t1 SET b=b+10, c=randomblob(800);
      UPDATE t1 SET b=b+10, c=randomblob(800);
      UPDATE t1 SET b=b+10, c=randomblob(800);
    }
    execsql COMMIT

    do_test $tn.$i.3 { expr [filesize test.db-wal]  < 100000 } 1
    do_test $tn.$i.4 { expr [filesize test.db-wal2] < 100000 } 1

    set sum [db eval {SELECT sum(b), md5sum(c) FROM t1}]

    do_test $tn.$i.5 {
      foreach f [glob -nocomplain test.db2*] {forcedelete $f}
      foreach f [glob -nocomplain test.db*] {
        forcecopy $f [string map {test.db test.db2} $f]
      }

      sqlite3 db2 test.db2
      db2 eval {SELECT sum(b), md5sum(c) FROM t1}
    } $sum
    db2 close
  }
}
    


finish_test

Added test/wal2rollback.test.































































1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
# 2017 September 19
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the operation of the library in
# "PRAGMA journal_mode=WAL2" mode.
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl
source $testdir/lock_common.tcl
source $testdir/malloc_common.tcl
source $testdir/wal_common.tcl

set testprefix wal2rollback
ifcapable !wal {finish_test ; return }

do_execsql_test 1.0 {
  CREATE TABLE t1(a, b, c);
  CREATE TABLE t2(a, b, c);
  CREATE INDEX i1 ON t1(a);
  CREATE INDEX i2 ON t1(b);
  PRAGMA journal_mode = wal2;
  PRAGMA cache_size = 5;
  PRAGMA journal_size_limit = 10000;
  WITH s(i) AS (
    SELECT 1 UNION ALL SELECT i+1 FROM s LIMIT 1000
  )
  INSERT INTO t1 SELECT i, i, randomblob(200) FROM s;
} {wal2 10000}

do_test 1.1 {
  expr [file size test.db-wal] > 10000
} 1

do_test 1.2 {
  execsql {
    BEGIN;
      UPDATE t1 SET b=b+1;
      INSERT INTO t2 VALUES(1,2,3);
  }
  expr [file size test.db-wal2] > 10000
} {1}

breakpoint
do_execsql_test 1.3 {
  ROLLBACK;
  SELECT * FROM t2;
  SELECT count(*) FROM t1 WHERE a=b;
  PRAGMA integrity_check;
} {1000 ok}



finish_test

Added test/wal2savepoint.test.










































































1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
# 2018 December 13
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the operation of the library in
# "PRAGMA journal_mode=WAL2" mode.
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl
source $testdir/lock_common.tcl
source $testdir/malloc_common.tcl
source $testdir/wal_common.tcl

set testprefix wal2savepoint
ifcapable !wal {finish_test ; return }

do_execsql_test 1.0 {
  CREATE TABLE t1(a, b, c);
  CREATE INDEX t1a ON t1(a);
  CREATE INDEX t1b ON t1(b);
  CREATE INDEX t1c ON t1(c);
  PRAGMA journal_mode = wal2;
  PRAGMA journal_size_limit = 15000;
  PRAGMA wal_autocheckpoint = 0;
  PRAGMA cache_size = 5;
} {wal2 15000 0}

do_execsql_test 1.1 {
  WITH s(i) AS ( SELECT 1 UNION ALL SELECT i+1 FROM s where i < 200)
  INSERT INTO t1 SELECT random(), random(), random() FROM s;
} {}

do_test 1.2 {
  list [file size test.db] [file size test.db-wal] [file size test.db-wal2]
} {5120 23088 0}

do_execsql_test 1.3 {
  BEGIN;
    SAVEPOINT abc;
      WITH s(i) AS ( SELECT 1 UNION ALL SELECT i+1 FROM s where i < 100)
      INSERT INTO t1 SELECT random(), random(), random() FROM s;
    ROLLBACK TO abc;
    WITH s(i) AS ( SELECT 1 UNION ALL SELECT i+1 FROM s where i < 10)
    INSERT INTO t1 SELECT random(), random(), random() FROM s;
  COMMIT;
  SELECT count(*) FROM t1;
  PRAGMA integrity_check;
} {210 ok}

do_execsql_test 1.4 {
  BEGIN;
    SAVEPOINT abc;
      WITH s(i) AS ( SELECT 1 UNION ALL SELECT i+1 FROM s where i < 100)
      INSERT INTO t1 SELECT random(), random(), random() FROM s;
    ROLLBACK TO abc;
    WITH s(i) AS ( SELECT 1 UNION ALL SELECT i+1 FROM s where i < 10)
    INSERT INTO t1 SELECT random(), random(), random() FROM s;
  COMMIT;
  SELECT count(*) FROM t1;
  PRAGMA integrity_check;
} {220 ok}


finish_test

Added test/wal2simple.test.



























































































































































































































































































































































































































































































1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
# 2017 September 19
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the operation of the library in
# "PRAGMA journal_mode=WAL2" mode.
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl
source $testdir/lock_common.tcl
source $testdir/malloc_common.tcl
source $testdir/wal_common.tcl

set testprefix wal2simple
ifcapable !wal {finish_test ; return }

#-------------------------------------------------------------------------
# The following tests verify that a client can switch in and out of wal
# and wal2 mode. But that it is not possible to change directly from wal
# to wal2, or from wal2 to wal mode.
#
do_execsql_test 1.1.0 {
  PRAGMA journal_mode = wal2
} {wal2}
execsql { SELECT * FROM sqlite_master} 
do_execsql_test 1.x {
  PRAGMA journal_mode;
  PRAGMA main.journal_mode;
} {wal2 wal2}
db close
do_test 1.1.1 { file size test.db } {1024}
do_test 1.1.2 { hexio_read test.db 18 2 } 0303

sqlite3 db test.db
do_execsql_test 1.2.0 {
  SELECT * FROM sqlite_master;
  PRAGMA journal_mode = delete;
} {delete}
db close
do_test 1.2.1 { file size test.db } {1024}
do_test 1.2.2 { hexio_read test.db 18 2 } 0101

sqlite3 db test.db
do_execsql_test 1.3.0 {
  SELECT * FROM sqlite_master;
  PRAGMA journal_mode = wal;
} {wal}
db close
do_test 1.3.1 { file size test.db } {1024}
do_test 1.3.2 { hexio_read test.db 18 2 } 0202

sqlite3 db test.db
do_catchsql_test 1.4.0 {
  PRAGMA journal_mode = wal2;
} {1 {cannot change from wal to wal2 mode}}
do_execsql_test 1.4.1 {
  PRAGMA journal_mode = wal;
  PRAGMA journal_mode = delete;
  PRAGMA journal_mode = wal2;
  PRAGMA journal_mode = wal2;
} {wal delete wal2 wal2}
do_catchsql_test 1.4.2 {
  PRAGMA journal_mode = wal;
} {1 {cannot change from wal2 to wal mode}}
db close
do_test 1.4.3 { hexio_read test.db 18 2 } 0303

#-------------------------------------------------------------------------
# Test that recovery in wal2 mode works.
#
forcedelete test.db test.db-wal test.db-wal2
reset_db
do_execsql_test 2.0 {
  CREATE TABLE t1(a INTEGER PRIMARY KEY, b);
  PRAGMA journal_mode = wal2;
  PRAGMA journal_size_limit = 5000;
} {wal2 5000}

proc wal_hook {DB nm nFrame} { $DB eval { PRAGMA wal_checkpoint } }
db wal_hook {wal_hook db}

for {set i 1} {$i <= 200} {incr i} {
  execsql { INSERT INTO t1 VALUES(NULL, randomblob(100)) }
  set res [db eval { SELECT sum(a), md5sum(b) FROM t1 }]

  do_test 2.1.$i {
    foreach f [glob -nocomplain test.db2*] { forcedelete $f }
    forcecopy test.db      test.db2
    forcecopy test.db-wal  test.db2-wal
    forcecopy test.db-wal2 test.db2-wal2

    sqlite3 db2 test.db2
    db2 eval { SELECT sum(a), md5sum(b) FROM t1 }
  } $res

  db2 close
}

#-------------------------------------------------------------------------

reset_db
do_execsql_test 3.0 {
  CREATE TABLE t1(x BLOB, y INTEGER PRIMARY KEY);
  CREATE INDEX i1 ON t1(x);
  PRAGMA cache_size = 5;
  PRAGMA journal_mode = wal2;
} {wal2}

do_test 3.1 {
  execsql BEGIN
  for {set i 1} {$i < 1000} {incr i} {
    execsql { INSERT INTO t1 VALUES(randomblob(800), $i) }
  }
  execsql COMMIT
} {}

do_execsql_test 3.2 {
  PRAGMA integrity_check;
} {ok}

#-------------------------------------------------------------------------
catch { db close }
foreach f [glob -nocomplain test.db*] { forcedelete $f }
reset_db
do_execsql_test 4.0 {
  CREATE TABLE t1(x, y);
  PRAGMA journal_mode = wal2;
} {wal2}

do_execsql_test 4.1 {
  SELECT * FROM t1;
} {}

do_execsql_test 4.2 {
  INSERT INTO t1 VALUES(1, 2);
} {}

do_execsql_test 4.3 {
  SELECT * FROM t1;
} {1 2}

do_test 4.4 {
  sqlite3 db2 test.db
  execsql { SELECT * FROM t1 } db2
} {1 2}

do_test 4.5 {
  lsort [glob test.db*]
} {test.db test.db-shm test.db-wal test.db-wal2}

do_test 4.6 {
  db close
  db2 close
  sqlite3 db test.db
  execsql { SELECT * FROM t1 }
} {1 2}

do_execsql_test 4.7 {
  PRAGMA journal_size_limit = 4000;
  INSERT INTO t1 VALUES(3, 4);
  INSERT INTO t1 VALUES(5, 6);
  INSERT INTO t1 VALUES(7, 8);
  INSERT INTO t1 VALUES(9, 10);
  INSERT INTO t1 VALUES(11, 12);
  INSERT INTO t1 VALUES(13, 14);
  INSERT INTO t1 VALUES(15, 16);
  INSERT INTO t1 VALUES(17, 18);
  SELECT * FROM t1;
} {4000 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18}

do_test 4.8 {
  sqlite3 db2 test.db
  execsql { SELECT * FROM t1 } db2
} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18}

do_test 4.9 {
  db close
  db2 close
  lsort [glob test.db*]
} {test.db}

#-------------------------------------------------------------------------
reset_db
do_execsql_test 5.0 {
  CREATE TABLE t1(a INTEGER PRIMARY KEY, b, c);
  CREATE INDEX i1 ON t1(b, c);
  PRAGMA journal_mode = wal2;
  PRAGMA journal_size_limit = 4000;
} {wal2 4000}

proc wal_hook {DB nm nFrame} {
  $DB eval { PRAGMA wal_checkpoint }
}
db wal_hook [list wal_hook db]


foreach js {4000 8000 12000} {
  foreach NROW [list 100 200 300 400 500 600 1000] {
    do_test 5.$js.$NROW.1 {
      db eval "DELETE FROM t1"
      db eval "PRAGMA journal_size_limit = $js"
      set nTotal 0
      for {set i 0} {$i < $NROW} {incr i} {
        db eval { INSERT INTO t1 VALUES($i, $i, randomblob(abs(random()%50))) }
        incr nTotal $i
      }
      set {} {}
    } {}

    do_test 5.$js.$NROW.2 {
      sqlite3 db2 test.db
      db2 eval { 
        PRAGMA integrity_check;
        SELECT count(*), sum(b) FROM t1;
      }
    } [list ok $NROW $nTotal]

    db2 close
  }
}


#-------------------------------------------------------------------------
reset_db
do_execsql_test 6.0 {
  CREATE TABLE tx(x);
  PRAGMA journal_mode = wal2;
  PRAGMA journal_size_limit = 3500;
} {wal2 3500}

do_test 6.1 {
  for {set i 0} {$i < 10} {incr i} {
    execsql "CREATE TABLE t$i (x);"
  }
} {}

do_test 6.2.1 {
  foreach f [glob -nocomplain test.db2*] { forcedelete $f }
  forcecopy test.db-wal2 test.db2-wal2
  sqlite3 db2 test.db2
  db2 eval { SELECT * FROM sqlite_master }
} {}
do_test 6.2.2 {
  db2 eval {
    PRAGMA journal_mode = wal2;
    SELECT * FROM sqlite_master;
  }
} {wal2}

do_test 6.3.1 {
  db2 close
  foreach f [glob -nocomplain test.db2*] { forcedelete $f }
  forcecopy test.db-wal2 test.db2-wal2
  forcecopy test.db test.db2
  sqlite3 db2 test.db2
  db2 eval { SELECT * FROM sqlite_master }
} {table tx tx 2 {CREATE TABLE tx(x)}}
do_test 6.3.2 {
  db2 eval {
    PRAGMA journal_mode = wal2;
    SELECT * FROM sqlite_master;
  }
} {wal2 table tx tx 2 {CREATE TABLE tx(x)}}

do_test 6.4.1 {
  db2 close
  foreach f [glob -nocomplain test.db2*] { forcedelete $f }
  forcecopy test.db-wal2 test.db2-wal2
  forcecopy test.db-wal test.db2-wal
  sqlite3 db2 test.db2
  db2 eval { SELECT * FROM sqlite_master }
} {}
do_test 6.4.2 {
  db2 eval {
    PRAGMA journal_mode = wal2;
    SELECT * FROM sqlite_master;
  }
} {wal2}
db2 close

#-------------------------------------------------------------------------
reset_db
sqlite3 db2 test.db
do_execsql_test 7.0 {
  PRAGMA journal_size_limit = 10000;
  PRAGMA journal_mode = wal2;
  PRAGMA wal_autocheckpoint = 0;
  BEGIN;
    CREATE TABLE t1(a);
    INSERT INTO t1 VALUES( randomblob(8000) );
  COMMIT;
} {10000 wal2 0}

do_test 7.1 {
  list [file size test.db-wal] [file size test.db-wal2]
} {9464 0}

# Connection db2 is holding a PART1 lock. 
#
#   7.2.2: Test that the PART1 does not prevent db from switching to the
#          other wal file.
#
#   7.2.3: Test that the PART1 does prevent a checkpoint of test.db-wal.
#
#   7.2.4: Test that after the PART1 is released the checkpoint is possible.
#
do_test 7.2.1 {
  execsql {
    BEGIN;
      SELECT count(*) FROM t1;
  } db2
} {1}
do_test 7.2.2 {
  execsql {
    INSERT INTO t1 VALUES( randomblob(800) );
    INSERT INTO t1 VALUES( randomblob(800) );
  }
  list [file size test.db-wal] [file size test.db-wal2] [file size test.db]
} {13656 3176 1024}
do_test 7.2.3 {
  execsql { PRAGMA wal_checkpoint }
  list [file size test.db-wal] [file size test.db-wal2] [file size test.db]
} {13656 3176 1024}
do_test 7.2.4 {
  execsql { END } db2
  execsql { PRAGMA wal_checkpoint }
  list [file size test.db-wal] [file size test.db-wal2] [file size test.db]
} {13656 3176 11264}

# Connection db2 is holding a PART2_FULL1 lock. 
#
#   7.3.2: Test that the lock does not prevent checkpointing.
#
#   7.3.3: Test that the lock does prevent the writer from overwriting 
#          test.db-wal.
#
#   7.3.4: Test that after the PART2_FULL1 is released the writer can
#          switch wal files and overwrite test.db-wal
#
db close
db2 close
sqlite3 db test.db
sqlite3 db2 test.db
do_test 7.3.1 {
  execsql {
    PRAGMA wal_autocheckpoint = 0;
    PRAGMA journal_size_limit = 10000;
    INSERT INTO t1 VALUES(randomblob(10000));
    INSERT INTO t1 VALUES(randomblob(500));
  }
  execsql {
    BEGIN;
      SELECT count(*) FROM t1;
  } db2
  list [file size test.db-wal] [file size test.db-wal2] [file size test.db]
} {12608 3176 11264}
do_test 7.3.2 {
  execsql { PRAGMA wal_checkpoint }
  list [file size test.db-wal] [file size test.db-wal2] [file size test.db]
} {12608 3176 21504}
do_test 7.3.3 {
  execsql { 
    INSERT INTO t1 VALUES(randomblob(10000));
    INSERT INTO t1 VALUES(randomblob(500));
  }
  list [file size test.db-wal] [file size test.db-wal2] [file size test.db]
} {12608 18896 21504}
do_test 7.3.4 {
  execsql END db2
  execsql { INSERT INTO t1 VALUES(randomblob(5000)); }
  list [file size test.db-wal] [file size test.db-wal2] [file size test.db]
} {12608 18896 21504}

# Connection db2 is holding a PART2 lock. 
#
#   7.4.2: Test that the lock does not prevent writer switching to test.db-wal.
#
#   7.3.3: Test that the lock does prevent checkpointing of test.db-wal2.
#
#   7.3.4: Test that after the PART2 is released test.db-wal2 can be
#          checkpointed.
#
db close
db2 close
sqlite3 db test.db
sqlite3 db2 test.db
do_test 7.4.1 {
  execsql {
    PRAGMA wal_autocheckpoint = 0;
    PRAGMA journal_size_limit = 10000;
    INSERT INTO t1 VALUES(randomblob(10000));
    INSERT INTO t1 VALUES(randomblob(10000));
    PRAGMA wal_checkpoint;
  }
  execsql {
    BEGIN;
      SELECT count(*) FROM t1;
  } db2
  list [file size test.db-wal] [file size test.db-wal2] [file size test.db]
} {12608 12608 44032}
do_test 7.4.2 {
  execsql { 
    INSERT INTO t1 VALUES(randomblob(5000));
  }
  list [file size test.db-wal] [file size test.db-wal2] [file size test.db]
} {12608 12608 44032}
do_test 7.4.3 {
  execsql { PRAGMA wal_checkpoint }
  list [file size test.db-wal] [file size test.db-wal2] [file size test.db]
} {12608 12608 44032}
do_test 7.4.4 {
  execsql END db2
  execsql { PRAGMA wal_checkpoint }
  list [file size test.db-wal] [file size test.db-wal2] [file size test.db]
} {12608 12608 54272}

# Connection db2 is holding a PART1_FULL2 lock. 
#
#   7.5.2: Test that the lock does not prevent a checkpoint of test.db-wal2.
#
#   7.5.3: Test that the lock does prevent the writer from overwriting
#          test.db-wal2.
#
#   7.5.4: Test that after the PART1_FULL2 lock is released, the writer
#          can switch to test.db-wal2.
#
db close
db2 close
sqlite3 db test.db
sqlite3 db2 test.db
do_test 7.5.1 {
  execsql {
    PRAGMA wal_autocheckpoint = 0;
    PRAGMA journal_size_limit = 10000;
    INSERT INTO t1 VALUES(randomblob(10000));
    INSERT INTO t1 VALUES(randomblob(10000));
    PRAGMA wal_checkpoint;
    INSERT INTO t1 VALUES(randomblob(5000));
  }
  execsql {
    BEGIN;
      SELECT count(*) FROM t1;
  } db2
  list [file size test.db-wal] [file size test.db-wal2] [file size test.db]
} {12608 12608 64512}
do_test 7.5.2 {
  execsql { PRAGMA wal_checkpoint }
  list [file size test.db-wal] [file size test.db-wal2] [file size test.db]
} {12608 12608 75776}
do_test 7.5.3.1 {
  execsql { INSERT INTO t1 VALUES(randomblob(5000)) }
  list [file size test.db-wal] [file size test.db-wal2] [file size test.db]
} {14704 12608 75776}
do_test 7.5.3.2 {
  execsql { INSERT INTO t1 VALUES(randomblob(5000)) }
  list [file size test.db-wal] [file size test.db-wal2] [file size test.db]
} {22040 12608 75776}
do_test 7.5.4 {
  execsql END db2
  execsql { INSERT INTO t1 VALUES(randomblob(5000)) }
  list [file size test.db-wal] [file size test.db-wal2] [file size test.db]
} {22040 12608 75776}


finish_test

Added test/wal2snapshot.test.































































































1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
# 2018 December 5
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the operation of the library in
# "PRAGMA journal_mode=WAL2" mode.
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

set testprefix wal2snapshot
ifcapable !wal {finish_test ; return }
ifcapable !snapshot {finish_test; return}

foreach {tn mode} {1 wal 2 wal2} {
  reset_db
  do_execsql_test $tn.1 "PRAGMA journal_mode = $mode" $mode

  do_execsql_test $tn.2 {
    CREATE TABLE t1(a, b);
    INSERT INTO t1 VALUES(1, 2);
    INSERT INTO t1 VALUES(3, 4);
    BEGIN;
  }

  # Check that sqlite3_snapshot_get() is an error for a wal2 db.
  #
  if {$tn==1} {
    do_test 1.3 {
      set S [sqlite3_snapshot_get db main]
      sqlite3_snapshot_free $S
    } {}
  } else {
    do_test 2.3 {
      list [catch { sqlite3_snapshot_get db main } msg] $msg
    } {1 SQLITE_ERROR}
  }
  
  # Check that sqlite3_snapshot_recover() is an error for a wal2 db.
  #
  do_execsql_test $tn.4 COMMIT
  if {$tn==1} {
    do_test 1.5 {
      sqlite3_snapshot_recover db main
    } {}
  } else {
    do_test 2.5 {
      list [catch { sqlite3_snapshot_recover db main } msg] $msg
    } {1 SQLITE_ERROR}
  }
 
  # Check that sqlite3_snapshot_open() is an error for a wal2 db.
  #
  if {$tn==1} {
    do_test 1.6 {
      execsql BEGIN
      set SNAPSHOT [sqlite3_snapshot_get_blob db main]
      sqlite3_snapshot_open_blob db main $SNAPSHOT
      execsql COMMIT
    } {}
  } else {

    do_test 2.6.1 {
      execsql BEGIN
      set res [
        list [catch { sqlite3_snapshot_open_blob db main $SNAPSHOT } msg] $msg
      ]
      execsql COMMIT
      set res
    } {1 SQLITE_ERROR}
    do_test 2.6.2 {
      execsql BEGIN
      execsql {SELECT * FROM sqlite_master}
      set res [
        list [catch { sqlite3_snapshot_open_blob db main $SNAPSHOT } msg] $msg
      ]
      execsql COMMIT
      set res
    } {1 SQLITE_ERROR}
  }
}


finish_test


Changes to test/walprotocol2.test.

81
82
83
84
85
86
87
88

89
90
91
92
93
94
95
81
82
83
84
85
86
87

88
89
90
91
92
93
94
95







-
+







#
proc lock_callback {method filename handle lock} {
  if {$lock=="0 1 lock exclusive"} {
    proc lock_callback {method filename handle lock} {}
    db2 eval { INSERT INTO x VALUES('x') }
  }
}
db timeout 10
db timeout 1100
do_catchsql_test 2.4 {
  BEGIN EXCLUSIVE;
} {0 {}}
do_execsql_test 2.5 {
  SELECT * FROM x;
  COMMIT;
} {z y x}

Added tool/tserver.c.





























































































































































































































































































































































































































































































































































































































































1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
** 2017 June 7
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** Simple multi-threaded server used for informal testing of concurrency
** between connections in different threads. Listens for tcp/ip connections
** on port 9999 of the 127.0.0.1 interface only. To build:
**
**   gcc -g $(TOP)/tool/tserver.c sqlite3.o -lpthread -o tserver
**
** To run using "x.db" as the db file:
**
**   ./tserver x.db
**
** To connect, open a client socket on port 9999 and start sending commands.
** Commands are either SQL - which must be terminated by a semi-colon, or
** dot-commands, which must be terminated by a newline. If an SQL statement
** is seen, it is prepared and added to an internal list.
**
** Dot-commands are:
**
**   .list                    Display all SQL statements in the list.
**   .quit                    Disconnect.
**   .run                     Run all SQL statements in the list.
**   .repeats N               Configure the number of repeats per ".run".
**   .seconds N               Configure the number of seconds to ".run" for.
**   .mutex_commit            Add a "COMMIT" protected by a g.commit_mutex
**                            to the current SQL.
**   .stop                    Stop the tserver process - exit(0).
**   .checkpoint N
**   .integrity_check
**
** Example input:
**
**   BEGIN;
**     INSERT INTO t1 VALUES(randomblob(10), randomblob(100));
**     INSERT INTO t1 VALUES(randomblob(10), randomblob(100));
**     INSERT INTO t1 VALUES(randomblob(10), randomblob(100));
**   COMMIT;
**   .repeats 100000
**   .run
**
*/
#define TSERVER_PORTNUMBER 9999

#include <arpa/inet.h>
#include <assert.h>
#include <pthread.h>
#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <unistd.h>

#include "sqlite3.h"

#define TSERVER_DEFAULT_CHECKPOINT_THRESHOLD 3900

/* Global variables */
struct TserverGlobal {
  char *zDatabaseName;             /* Database used by this server */
  char *zVfs;
  sqlite3_mutex *commit_mutex;
  sqlite3 *db;                     /* Global db handle */

  /* The following use native pthreads instead of a portable interface. This
  ** is because a condition variable, as well as a mutex, is required.  */
  pthread_mutex_t ckpt_mutex;
  pthread_cond_t ckpt_cond;
  int nThreshold;                  /* Checkpoint when wal is this large */
  int bCkptRequired;               /* True if wal checkpoint is required */
  int nRun;                        /* Number of clients in ".run" */
  int nWait;                       /* Number of clients waiting on ckpt_cond */
};

static struct TserverGlobal g = {0};

typedef struct ClientSql ClientSql;
struct ClientSql {
  sqlite3_stmt *pStmt;
  int flags;
};

#define TSERVER_CLIENTSQL_MUTEX     0x0001
#define TSERVER_CLIENTSQL_INTEGRITY 0x0002

typedef struct ClientCtx ClientCtx;
struct ClientCtx {
  sqlite3 *db;                    /* Database handle for this client */
  int fd;                         /* Client fd */
  int nRepeat;                    /* Number of times to repeat SQL */
  int nSecond;                    /* Number of seconds to run for */
  ClientSql *aPrepare;            /* Array of prepared statements */
  int nPrepare;                   /* Valid size of apPrepare[] */
  int nAlloc;                     /* Allocated size of apPrepare[] */

  int nClientThreshold;           /* Threshold for checkpointing */
  int bClientCkptRequired;        /* True to do a checkpoint */
};

static int is_eol(int i){
  return (i=='\n' || i=='\r');
}
static int is_whitespace(int i){
  return (i==' ' || i=='\t' || is_eol(i));
}

/*
** Implementation of SQL scalar function usleep().
*/
static void usleepFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  int nUs;
  sqlite3_vfs *pVfs = (sqlite3_vfs*)sqlite3_user_data(context);
  assert( argc==1 );
  nUs = sqlite3_value_int64(argv[0]);
  pVfs->xSleep(pVfs, nUs);
}

static void trim_string(const char **pzStr, int *pnStr){
  const char *zStr = *pzStr;
  int nStr = *pnStr;

  while( nStr>0 && is_whitespace(zStr[0]) ){
    zStr++;
    nStr--;
  }
  while( nStr>0 && is_whitespace(zStr[nStr-1]) ){
    nStr--;
  }

  *pzStr = zStr;
  *pnStr = nStr;
}

static int send_message(ClientCtx *p, const char *zFmt, ...){
  char *zMsg;
  va_list ap;                             /* Vararg list */
  va_start(ap, zFmt);
  int res = -1;

  zMsg = sqlite3_vmprintf(zFmt, ap);
  if( zMsg ){
    res = write(p->fd, zMsg, strlen(zMsg));
  }
  sqlite3_free(zMsg);
  va_end(ap);

  return (res<0);
}

static int handle_some_sql(ClientCtx *p, const char *zSql, int nSql){
  const char *zTail = zSql;
  int nTail = nSql;
  int rc = SQLITE_OK;

  while( rc==SQLITE_OK ){
    if( p->nPrepare>=p->nAlloc ){
      int nByte = (p->nPrepare+32) * sizeof(ClientSql);
      ClientSql *aNew = sqlite3_realloc(p->aPrepare, nByte);
      if( aNew ){
        memset(&aNew[p->nPrepare], 0, sizeof(ClientSql)*32);
        p->aPrepare = aNew;
        p->nAlloc = p->nPrepare+32;
      }else{
        rc = SQLITE_NOMEM;
        break;
      }
    }
    rc = sqlite3_prepare_v2(
        p->db, zTail, nTail, &p->aPrepare[p->nPrepare].pStmt, &zTail
    );
    if( rc!=SQLITE_OK ){
      send_message(p, "error - %s (eec=%d)\n", sqlite3_errmsg(p->db),
          sqlite3_extended_errcode(p->db)
      );
      rc = 1;
      break;
    }
    if( p->aPrepare[p->nPrepare].pStmt==0 ){
      break;
    }
    p->nPrepare++;
    nTail = nSql - (zTail-zSql);
    rc = send_message(p, "ok (%d SQL statements)\n", p->nPrepare);
  }

  return rc;
}

static sqlite3_int64 get_timer(void){
  struct timeval t;
  gettimeofday(&t, 0);
  return ((sqlite3_int64)t.tv_usec / 1000) + ((sqlite3_int64)t.tv_sec * 1000);
}

static void clear_sql(ClientCtx *p){
  int j;
  for(j=0; j<p->nPrepare; j++){
    sqlite3_finalize(p->aPrepare[j].pStmt);
  }
  p->nPrepare = 0;
}

/*
** The sqlite3_wal_hook() callback used by all client database connections.
*/
static int clientWalHook(void *pArg, sqlite3 *db, const char *zDb, int nFrame){
  if( g.nThreshold>0 ){
    if( nFrame>=g.nThreshold ){
      g.bCkptRequired = 1;
    }
  }else{
    ClientCtx *pCtx = (ClientCtx*)pArg;
    if( pCtx->nClientThreshold && nFrame>=pCtx->nClientThreshold ){
      pCtx->bClientCkptRequired = 1;
    }
  }
  return SQLITE_OK;
}

static int handle_run_command(ClientCtx *p){
  int i, j;
  int nBusy = 0;
  sqlite3_int64 t0 = get_timer();
  sqlite3_int64 t1 = t0;
  int nT1 = 0;
  int nTBusy1 = 0;
  int rc = SQLITE_OK;

  pthread_mutex_lock(&g.ckpt_mutex);
  g.nRun++;
  pthread_mutex_unlock(&g.ckpt_mutex);


  for(j=0; (p->nRepeat<=0 || j<p->nRepeat) && rc==SQLITE_OK; j++){
    sqlite3_int64 t2;

    for(i=0; i<p->nPrepare && rc==SQLITE_OK; i++){
      sqlite3_stmt *pStmt = p->aPrepare[i].pStmt;

      /* If the MUTEX flag is set, grab g.commit_mutex before executing
      ** the SQL statement (which is always "COMMIT" in this case). */
      if( p->aPrepare[i].flags & TSERVER_CLIENTSQL_MUTEX ){
        sqlite3_mutex_enter(g.commit_mutex);
      }

      /* Execute the statement */
      if( p->aPrepare[i].flags & TSERVER_CLIENTSQL_INTEGRITY ){
        sqlite3_step(pStmt);
        if( sqlite3_stricmp("ok", sqlite3_column_text(pStmt, 0)) ){
          send_message(p, "error - integrity_check failed: %s\n", 
              sqlite3_column_text(pStmt, 0)
          );
        }
        sqlite3_reset(pStmt);
      }
      while( sqlite3_step(pStmt)==SQLITE_ROW );
      rc = sqlite3_reset(pStmt);

      /* Relinquish the g.commit_mutex mutex if required. */
      if( p->aPrepare[i].flags & TSERVER_CLIENTSQL_MUTEX ){
        sqlite3_mutex_leave(g.commit_mutex);
      }

      if( (rc & 0xFF)==SQLITE_BUSY ){
        if( sqlite3_get_autocommit(p->db)==0 ){
          sqlite3_exec(p->db, "ROLLBACK", 0, 0, 0);
        }
        nBusy++;
        rc = SQLITE_OK;
        break;
      }
      else if( rc!=SQLITE_OK ){
        send_message(p, "error - %s (eec=%d)\n", sqlite3_errmsg(p->db),
            sqlite3_extended_errcode(p->db)
        );
      }
    }

    t2 = get_timer();
    if( t2>=(t1+1000) ){
      int nMs = (t2 - t1);
      int nDone = (j+1 - nBusy - nT1);

      rc = send_message(
          p, "(%d done @ %d per second, %d busy)\n", 
          nDone, (1000*nDone + nMs/2) / nMs, nBusy - nTBusy1
          );
      t1 = t2;
      nT1 = j+1 - nBusy;
      nTBusy1 = nBusy;
      if( p->nSecond>0 && (p->nSecond*1000)<=t1-t0 ) break;
    }

    /* Global checkpoint handling. */
    if( g.nThreshold>0 ){
      pthread_mutex_lock(&g.ckpt_mutex);
      if( rc==SQLITE_OK && g.bCkptRequired ){
        if( g.nWait==g.nRun-1 ){
          /* All other clients are already waiting on the condition variable.
          ** Run the checkpoint, signal the condition and move on.  */
          rc = sqlite3_wal_checkpoint(p->db, "main");
          g.bCkptRequired = 0;
          pthread_cond_broadcast(&g.ckpt_cond);
        }else{
          assert( g.nWait<g.nRun-1 );
          g.nWait++;
          pthread_cond_wait(&g.ckpt_cond, &g.ckpt_mutex);
          g.nWait--;
        }
      }
      pthread_mutex_unlock(&g.ckpt_mutex);
    }

    if( rc==SQLITE_OK && p->bClientCkptRequired ){
      rc = sqlite3_wal_checkpoint(p->db, "main");
      if( rc==SQLITE_BUSY ) rc = SQLITE_OK;
      assert( rc==SQLITE_OK );
      p->bClientCkptRequired = 0;
    }
  }

  if( rc==SQLITE_OK ){
    int nMs = (int)(get_timer() - t0);
    send_message(p, "ok (%d/%d SQLITE_BUSY)\n", nBusy, j);
    if( p->nRepeat<=0 ){
      send_message(p, "### ok %d busy %d ms %d\n", j-nBusy, nBusy, nMs);
    }
  }
  clear_sql(p);

  pthread_mutex_lock(&g.ckpt_mutex);
  g.nRun--;
  pthread_mutex_unlock(&g.ckpt_mutex);

  return rc;
}

static int handle_dot_command(ClientCtx *p, const char *zCmd, int nCmd){
  int n;
  int rc = 0;
  const char *z = &zCmd[1];
  const char *zArg;
  int nArg;

  assert( zCmd[0]=='.' );
  for(n=0; n<(nCmd-1); n++){
    if( is_whitespace(z[n]) ) break;
  }

  zArg = &z[n];
  nArg = nCmd-n;
  trim_string(&zArg, &nArg);

  if( n>=1 && n<=4 && 0==strncmp(z, "list", n) ){
    int i;
    for(i=0; rc==0 && i<p->nPrepare; i++){
      const char *zSql = sqlite3_sql(p->aPrepare[i].pStmt);
      int nSql = strlen(zSql);
      trim_string(&zSql, &nSql);
      rc = send_message(p, "%d: %.*s\n", i, nSql, zSql);
    }
  }

  else if( n>=1 && n<=4 && 0==strncmp(z, "quit", n) ){
    rc = -1;
  }

  else if( n>=2 && n<=7 && 0==strncmp(z, "repeats", n) ){
    if( nArg ){
      p->nRepeat = strtol(zArg, 0, 0);
      if( p->nRepeat>0 ) p->nSecond = 0;
    }
    rc = send_message(p, "ok (repeat=%d)\n", p->nRepeat);
  }

  else if( n>=2 && n<=3 && 0==strncmp(z, "run", n) ){
    rc = handle_run_command(p);
  }

  else if( n>=2 && n<=7 && 0==strncmp(z, "seconds", n) ){
    if( nArg ){
      p->nSecond = strtol(zArg, 0, 0);
      if( p->nSecond>0 ) p->nRepeat = 0;
    }
    rc = send_message(p, "ok (seconds=%d)\n", p->nSecond);
  }

  else if( n>=1 && n<=12 && 0==strncmp(z, "mutex_commit", n) ){
    rc = handle_some_sql(p, "COMMIT;", 7);
    if( rc==SQLITE_OK ){
      p->aPrepare[p->nPrepare-1].flags |= TSERVER_CLIENTSQL_MUTEX;
    }
  }

  else if( n>=1 && n<=10 && 0==strncmp(z, "checkpoint", n) ){
    if( nArg ){
      p->nClientThreshold = strtol(zArg, 0, 0);
    }
    rc = send_message(p, "ok (checkpoint=%d)\n", p->nClientThreshold);
  }

  else if( n>=2 && n<=4 && 0==strncmp(z, "stop", n) ){
    sqlite3_close(g.db);
    exit(0);
  }

  else if( n>=2 && n<=15 && 0==strncmp(z, "integrity_check", n) ){
    rc = handle_some_sql(p, "PRAGMA integrity_check;", 23);
    if( rc==SQLITE_OK ){
      p->aPrepare[p->nPrepare-1].flags |= TSERVER_CLIENTSQL_INTEGRITY;
    }
  }

  else{
    send_message(p, 
        "unrecognized dot command: %.*s\n"
        "should be \"list\", \"run\", \"repeats\", \"mutex_commit\", "
        "\"checkpoint\", \"integrity_check\" or \"seconds\"\n", n, z
    );
    rc = 1;
  }

  return rc;
}

static void *handle_client(void *pArg){
  char zCmd[32*1024];             /* Read buffer */
  int nCmd = 0;                   /* Valid bytes in zCmd[] */
  int res;                        /* Result of read() call */
  int rc = SQLITE_OK;

  ClientCtx ctx;
  memset(&ctx, 0, sizeof(ClientCtx));

  ctx.fd = (int)(intptr_t)pArg;
  ctx.nRepeat = 1;
  rc = sqlite3_open_v2(g.zDatabaseName, &ctx.db,
      SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, g.zVfs
  );
  if( rc!=SQLITE_OK ){
    fprintf(stderr, "sqlite3_open(): %s\n", sqlite3_errmsg(ctx.db));
    return 0;
  }
  sqlite3_create_function(
      ctx.db, "usleep", 1, SQLITE_UTF8, (void*)sqlite3_vfs_find(0), 
      usleepFunc, 0, 0
  );

  /* Register the wal-hook with the new client connection */
  sqlite3_wal_hook(ctx.db, clientWalHook, (void*)&ctx);

  while( rc==SQLITE_OK ){
    int i;
    int iStart;
    int nConsume;
    res = read(ctx.fd, &zCmd[nCmd], sizeof(zCmd)-nCmd-1);
    if( res<=0 ) break;
    nCmd += res;
    if( nCmd>=sizeof(zCmd)-1 ){
      fprintf(stderr, "oversized (>32KiB) message\n");
      res = 0;
      break;
    }
    zCmd[nCmd] = '\0';

    do {
      nConsume = 0;

      /* Gobble up any whitespace */
      iStart = 0;
      while( is_whitespace(zCmd[iStart]) ) iStart++;

      if( zCmd[iStart]=='.' ){
        /* This is a dot-command. Search for end-of-line. */
        for(i=iStart; i<nCmd; i++){
          if( is_eol(zCmd[i]) ){
            rc = handle_dot_command(&ctx, &zCmd[iStart], i-iStart);
            nConsume = i+1;
            break;
          }
        }
      }else{

        int iSemi;
        char c = 0;
        for(iSemi=iStart; iSemi<nCmd; iSemi++){
          if( zCmd[iSemi]==';' ){
            c = zCmd[iSemi+1];
            zCmd[iSemi+1] = '\0';
            break;
          }
        }

        if( iSemi<nCmd ){
          if( sqlite3_complete(zCmd) ){
            rc = handle_some_sql(&ctx, zCmd, iSemi+1);
            nConsume = iSemi+1;
          }

          if( c ){
            zCmd[iSemi+1] = c;
          }
        }
      }

      if( nConsume>0 ){
        nCmd = nCmd-nConsume;
        if( nCmd>0 ){
          memmove(zCmd, &zCmd[nConsume], nCmd);
        }
      }
    }while( rc==SQLITE_OK && nConsume>0 );
  }

  fprintf(stdout, "Client %d disconnects (rc=%d)\n", ctx.fd, rc);
  fflush(stdout);
  close(ctx.fd);
  clear_sql(&ctx);
  sqlite3_free(ctx.aPrepare);
  sqlite3_close(ctx.db);
  return 0;
} 

static void usage(const char *zExec){
  fprintf(stderr, "Usage: %s ?-vfs VFS? DATABASE\n", zExec);
  exit(1);
}

int main(int argc, char *argv[]) {
  int sfd;
  int rc;
  int yes = 1;
  struct sockaddr_in server;
  int i;

  /* Ignore SIGPIPE. Otherwise the server exits if a client disconnects
  ** abruptly.  */
  signal(SIGPIPE, SIG_IGN);

  g.nThreshold = TSERVER_DEFAULT_CHECKPOINT_THRESHOLD;
  if( (argc%2) ) usage(argv[0]);
  for(i=1; i<(argc-1); i+=2){
    int n = strlen(argv[i]);
    if( n>=2 && 0==sqlite3_strnicmp("-walautocheckpoint", argv[i], n) ){
      g.nThreshold = strtol(argv[i+1], 0, 0);
    }else 
    if( n>=2 && 0==sqlite3_strnicmp("-vfs", argv[i], n) ){
      g.zVfs = argv[i+1];
    }
  }
  g.zDatabaseName = argv[argc-1];

  g.commit_mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  pthread_mutex_init(&g.ckpt_mutex, 0);
  pthread_cond_init(&g.ckpt_cond, 0);

  rc = sqlite3_open_v2(g.zDatabaseName, &g.db,
      SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, g.zVfs
  );
  if( rc!=SQLITE_OK ){
    fprintf(stderr, "sqlite3_open(): %s\n", sqlite3_errmsg(g.db));
    return 1;
  }

  rc = sqlite3_exec(g.db, "SELECT * FROM sqlite_master", 0, 0, 0);
  if( rc!=SQLITE_OK ){
    fprintf(stderr, "sqlite3_exec(): %s\n", sqlite3_errmsg(g.db));
    return 1;
  }

  sfd = socket(AF_INET, SOCK_STREAM, 0);
  if( sfd<0 ){
    fprintf(stderr, "socket() failed\n");
    return 1;
  }

  rc = setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  if( rc<0 ){
    perror("setsockopt");
    return 1;
  }

  memset(&server, 0, sizeof(server));
  server.sin_family = AF_INET;
  server.sin_addr.s_addr = inet_addr("127.0.0.1");
  server.sin_port = htons(TSERVER_PORTNUMBER);

  rc = bind(sfd, (struct sockaddr *)&server, sizeof(struct sockaddr));
  if( rc<0 ){
    fprintf(stderr, "bind() failed\n");
    return 1;
  }

  rc = listen(sfd, 8);
  if( rc<0 ){
    fprintf(stderr, "listen() failed\n");
    return 1;
  }

  while( 1 ){
    pthread_t tid;
    int cfd = accept(sfd, NULL, NULL);
    if( cfd<0 ){
      perror("accept()");
      return 1;
    }

    fprintf(stdout, "Client %d connects\n", cfd);
    fflush(stdout);
    rc = pthread_create(&tid, NULL, handle_client, (void*)(intptr_t)cfd);
    if( rc!=0 ){
      perror("pthread_create()");
      return 1;
    }

    pthread_detach(tid);
  }

  return 0;
}

Added tool/tserver_test.tcl.










































































































































































































































































































1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
#!/usr/bin/tclsh
#
# This script is used to run the performance test cases described in
# README-server-edition.html.
#


package require sqlite3

# Default values for command line switches:
set O(-database)  ""
set O(-rows)      [expr 5000000]
set O(-mode)      wal2
set O(-tserver)   "./tserver"
set O(-seconds)   20
set O(-writers)   1
set O(-readers)   0
set O(-integrity) 0
set O(-verbose)   0


proc error_out {err} {
  puts stderr $err
  exit -1
}

proc usage {} {
  puts stderr "Usage: $::argv0 ?OPTIONS?"
  puts stderr ""
  puts stderr "Where OPTIONS are:"
  puts stderr "  -database <database file>             (default: test.db)"
  puts stderr "  -mode <mode>                          (default: wal2)"
  puts stderr "  -rows <number of rows>                (default: 5000000)"
  puts stderr "  -tserver <path to tserver executable> (default: ./tserver)"
  puts stderr "  -seconds <time to run for in seconds> (default: 20)"
  puts stderr "  -writers <number of writer clients>   (default: 1)"
  puts stderr "  -readers <number of reader clients>   (default: 0)"
  puts stderr "  -integrity <number of IC clients>     (default: 0)"
  puts stderr "  -verbose 0|1                          (default: 0)"
  exit -1
}

for {set i 0} {$i < [llength $argv]} {incr i} {
  set opt ""
  set arg [lindex $argv $i]
  set n [expr [string length $arg]-1]
  foreach k [array names ::O] {
    if {[string range $k 0 $n]==$arg} {
      if {$opt==""} {
        set opt $k
      } else {
        error_out "ambiguous option: $arg ($k or $opt)"
      }
    }
  }
  if {$opt==""} { usage }
  if {$i==[llength $argv]-1} {
    error_out "option requires an argument: $opt"
  }
  incr i
  set val [lindex $argv $i]
  switch -- $opt {
    -mode {
      if {$val != "wal" && $val != "wal2"} {
        set xyz "\"wal\" or \"wal2\""
        error_out "Found \"$val\" - expected $xyz"
      }
    }
  }
  set O($opt) [lindex $argv $i]
}
if {$O(-database)==""} {
  set O(-database) "test.db"
}

set O(-rows) [expr $O(-rows)]

#--------------------------------------------------------------------------
# Create and populate the required test database, if it is not already 
# present in the file-system.
#
proc create_test_database {} {
  global O

  if {[file exists $O(-database)]} {
    sqlite3 db $O(-database)

    # Check the schema looks Ok.
    set s [db one {
      SELECT group_concat(name||pk, '.') FROM pragma_table_info('t1');
    }]
    if {$s != "a1.b0.c0.d0"} {
      error_out "Database $O(-database) exists but is not usable (schema)"
    }

    # Check that the row count matches.
    set n [db one { SELECT count(*) FROM t1 }]
    if {$n != $O(-rows)} {
      error_out "Database $O(-database) exists but is not usable (row-count)"
    }
    db close
  } else {
    catch { file delete -force $O(-database)-journal }
    catch { file delete -force $O(-database)-wal }

    if {$O(-verbose)} {
      puts "Building database $O(-database)..."
    }

    sqlite3 db $O(-database)
    db eval {
      CREATE TABLE t1(
        a INTEGER PRIMARY KEY, 
        b BLOB(16), 
        c BLOB(16), 
        d BLOB(400)
      );
      CREATE INDEX i1 ON t1(b);
      CREATE INDEX i2 ON t1(c);

      WITH s(i) AS (SELECT 1 UNION ALL SELECT i+1 FROM s WHERE i<$O(-rows))
      INSERT INTO t1 
      SELECT i-1, randomblob(16), randomblob(16), randomblob(400) FROM s;
    }
    db close
  }

  switch -- $O(-mode) {
    wal {
      sqlite3 db $O(-database)
      db eval {PRAGMA journal_mode = delete}
      db eval {PRAGMA journal_mode = wal}
      db close
    }

    wal2 {
      sqlite3 db $O(-database)
      db eval {PRAGMA journal_mode = delete}
      db eval {PRAGMA journal_mode = wal2}
      db close
    }
  }
}

#-------------------------------------------------------------------------
# Functions to start and stop the tserver process:
#
#   tserver_start
#   tserver_stop
#
set ::tserver {}
proc tserver_start {} {
  global O
  set cmd "|$O(-tserver) -vfs unix "
  if {$O(-mode)=="wal2"} {
    append cmd " -walautocheckpoint 0 "
  }
  append cmd "$O(-database)"
  set ::tserver [open $cmd]
  fconfigure $::tserver -blocking 0
  fileevent $::tserver readable tserver_data
}

proc tserver_data {} {
  global O
  if {[eof $::tserver]} {
    error_out "tserver has exited"
  }
  set line [gets $::tserver]
  if {$line != "" && $O(-verbose)} {
    puts "tserver: $line"
  }
}

proc tserver_stop {} {
  close $::tserver
  set fd [socket localhost 9999]
  puts $fd ".stop"
  close $fd
}
#-------------------------------------------------------------------------

set ::nClient 0
set ::client_output [list]

proc client_data {name fd} {
  global O
  if {[eof $fd]} {
    incr ::nClient -1
    close $fd
    return
  }
  set str [gets $fd]
  if {[string trim $str]!=""} {
    if {[string range $str 0 3]=="### "} {
      lappend ::client_output [concat [list name $name] [lrange $str 1 end]]
    } 
    if {$O(-verbose)} {
      puts "$name: $str"
    }
  }
}

proc client_launch {name script} {
  global O
  set fd [socket localhost 9999]
  fconfigure $fd -blocking 0
  puts $fd "PRAGMA synchronous = OFF;"
  puts $fd ".repeat 1"
  puts $fd ".run"
  puts $fd $script
  puts $fd ".seconds $O(-seconds)"
  puts $fd ".run"
  puts $fd ".quit"
  flush $fd
  incr ::nClient
  fileevent $fd readable [list client_data $name $fd]
}

proc client_wait {} {
  while {$::nClient>0} {vwait ::nClient}
}

proc script_writer {bCkpt} {
  global O

  set commit ".mutex_commit"
  set begin "BEGIN CONCURRENT;"
  set ckpt ""
  if {$bCkpt} {
    set ckpt ".checkpoint 2000"
  }

  set tail "randomblob(16), randomblob(16), randomblob(400));"
  return [subst -nocommands {
    $ckpt
    $begin
      REPLACE INTO t1 VALUES(abs(random() % $O(-rows)), $tail
    $commit
  }]
}

proc script_reader {} {
  global O

  return [subst -nocommands {
    BEGIN;
      SELECT * FROM t1 WHERE a>abs((random()%$O(-rows))) LIMIT 10;
    END;
  }]
}

proc script_integrity {} {
  global O

  return {
    .integrity_check
  }
}


create_test_database
tserver_start

for {set i 0} {$i < $O(-writers)} {incr i} {
  client_launch w.$i [script_writer [expr {$i==0 && $O(-mode)=="wal2"}]]
}
for {set i 0} {$i < $O(-readers)} {incr i} {
  client_launch r.$i [script_reader]
}
for {set i 0} {$i < $O(-integrity)} {incr i} {
  client_launch i.$i [script_integrity]
}
client_wait

set name(w) "Writers"
set name(r) "Readers"
set name(i) "Integrity"
foreach r $::client_output {
  array set a $r
  set type [string range $a(name) 0 0]
  incr x($type.ok) $a(ok);
  incr x($type.busy) $a(busy);
  incr x($type.n) 1
  set t($type) 1
}

foreach type [array names t] {
  set nTPS [expr $x($type.ok) / $O(-seconds)]
  set nC [expr $nTPS / $x($type.n)]
  set nTotal [expr $x($type.ok) + $x($type.busy)]
  set bp [format %.2f [expr $x($type.busy) * 100.0 / $nTotal]]
  puts "$name($type): $nTPS transactions/second ($nC per client) ($bp% busy)"
}

tserver_stop