PageRenderTime 1376ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/Community.CsharpSqlite/src/pager_c.cs

https://bitbucket.org/eumario/csharp-sqlite
C# | 7835 lines | 3841 code | 509 blank | 3485 comment | 1411 complexity | 20abeebb7e84790945836b6fa75721ad MD5 | raw file
  1. using System;
  2. using System.Diagnostics;
  3. using System.IO;
  4. using i16 = System.Int16;
  5. using i64 = System.Int64;
  6. using u8 = System.Byte;
  7. using u16 = System.UInt16;
  8. using u32 = System.UInt32;
  9. using Pgno = System.UInt32;
  10. using sqlite3_int64 = System.Int64;
  11. namespace Community.CsharpSqlite
  12. {
  13. using System.Text;
  14. using DbPage = Sqlite3.PgHdr;
  15. public partial class Sqlite3
  16. {
  17. /*
  18. ** 2001 September 15
  19. **
  20. ** The author disclaims copyright to this source code. In place of
  21. ** a legal notice, here is a blessing:
  22. **
  23. ** May you do good and not evil.
  24. ** May you find forgiveness for yourself and forgive others.
  25. ** May you share freely, never taking more than you give.
  26. **
  27. *************************************************************************
  28. ** This is the implementation of the page cache subsystem or "pager".
  29. **
  30. ** The pager is used to access a database disk file. It implements
  31. ** atomic commit and rollback through the use of a journal file that
  32. ** is separate from the database file. The pager also implements file
  33. ** locking to prevent two processes from writing the same database
  34. ** file simultaneously, or one process from reading the database while
  35. ** another is writing.
  36. *************************************************************************
  37. ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
  38. ** C#-SQLite is an independent reimplementation of the SQLite software library
  39. **
  40. ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2
  41. **
  42. *************************************************************************
  43. */
  44. #if !SQLITE_OMIT_DISKIO
  45. //#include "sqliteInt.h"
  46. //#include "wal.h"
  47. /******************* NOTES ON THE DESIGN OF THE PAGER ************************
  48. **
  49. ** This comment block describes invariants that hold when using a rollback
  50. ** journal. These invariants do not apply for journal_mode=WAL,
  51. ** journal_mode=MEMORY, or journal_mode=OFF.
  52. **
  53. ** Within this comment block, a page is deemed to have been synced
  54. ** automatically as soon as it is written when PRAGMA synchronous=OFF.
  55. ** Otherwise, the page is not synced until the xSync method of the VFS
  56. ** is called successfully on the file containing the page.
  57. **
  58. ** Definition: A page of the database file is said to be "overwriteable" if
  59. ** one or more of the following are true about the page:
  60. **
  61. ** (a) The original content of the page as it was at the beginning of
  62. ** the transaction has been written into the rollback journal and
  63. ** synced.
  64. **
  65. ** (b) The page was a freelist leaf page at the start of the transaction.
  66. **
  67. ** (c) The page number is greater than the largest page that existed in
  68. ** the database file at the start of the transaction.
  69. **
  70. ** (1) A page of the database file is never overwritten unless one of the
  71. ** following are true:
  72. **
  73. ** (a) The page and all other pages on the same sector are overwriteable.
  74. **
  75. ** (b) The atomic page write optimization is enabled, and the entire
  76. ** transaction other than the update of the transaction sequence
  77. ** number consists of a single page change.
  78. **
  79. ** (2) The content of a page written into the rollback journal exactly matches
  80. ** both the content in the database when the rollback journal was written
  81. ** and the content in the database at the beginning of the current
  82. ** transaction.
  83. **
  84. ** (3) Writes to the database file are an integer multiple of the page size
  85. ** in length and are aligned on a page boundary.
  86. **
  87. ** (4) Reads from the database file are either aligned on a page boundary and
  88. ** an integer multiple of the page size in length or are taken from the
  89. ** first 100 bytes of the database file.
  90. **
  91. ** (5) All writes to the database file are synced prior to the rollback journal
  92. ** being deleted, truncated, or zeroed.
  93. **
  94. ** (6) If a master journal file is used, then all writes to the database file
  95. ** are synced prior to the master journal being deleted.
  96. **
  97. ** Definition: Two databases (or the same database at two points it time)
  98. ** are said to be "logically equivalent" if they give the same answer to
  99. ** all queries. Note in particular the the content of freelist leaf
  100. ** pages can be changed arbitarily without effecting the logical equivalence
  101. ** of the database.
  102. **
  103. ** (7) At any time, if any subset, including the empty set and the total set,
  104. ** of the unsynced changes to a rollback journal are removed and the
  105. ** journal is rolled back, the resulting database file will be logical
  106. ** equivalent to the database file at the beginning of the transaction.
  107. **
  108. ** (8) When a transaction is rolled back, the xTruncate method of the VFS
  109. ** is called to restore the database file to the same size it was at
  110. ** the beginning of the transaction. (In some VFSes, the xTruncate
  111. ** method is a no-op, but that does not change the fact the SQLite will
  112. ** invoke it.)
  113. **
  114. ** (9) Whenever the database file is modified, at least one bit in the range
  115. ** of bytes from 24 through 39 inclusive will be changed prior to releasing
  116. ** the EXCLUSIVE lock, thus signaling other connections on the same
  117. ** database to flush their caches.
  118. **
  119. ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
  120. ** than one billion transactions.
  121. **
  122. ** (11) A database file is well-formed at the beginning and at the conclusion
  123. ** of every transaction.
  124. **
  125. ** (12) An EXCLUSIVE lock is held on the database file when writing to
  126. ** the database file.
  127. **
  128. ** (13) A SHARED lock is held on the database file while reading any
  129. ** content out of the database file.
  130. **
  131. ******************************************************************************/
  132. /*
  133. ** Macros for troubleshooting. Normally turned off
  134. */
  135. #if TRACE
  136. static bool sqlite3PagerTrace = false; /* True to enable tracing */
  137. //#define sqlite3DebugPrintf printf
  138. //#define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
  139. static void PAGERTRACE( string T, params object[] ap ) { if ( sqlite3PagerTrace )sqlite3DebugPrintf( T, ap ); }
  140. #else
  141. //#define PAGERTRACE(X)
  142. static void PAGERTRACE( string T, params object[] ap )
  143. {
  144. }
  145. #endif
  146. /*
  147. ** The following two macros are used within the PAGERTRACE() macros above
  148. ** to print out file-descriptors.
  149. **
  150. ** PAGERID() takes a pointer to a Pager struct as its argument. The
  151. ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
  152. ** struct as its argument.
  153. */
  154. //#define PAGERID(p) ((int)(p.fd))
  155. static int PAGERID( Pager p )
  156. {
  157. return p.GetHashCode();
  158. }
  159. //#define FILEHANDLEID(fd) ((int)fd)
  160. static int FILEHANDLEID( sqlite3_file fd )
  161. {
  162. return fd.GetHashCode();
  163. }
  164. /*
  165. ** The Pager.eState variable stores the current 'state' of a pager. A
  166. ** pager may be in any one of the seven states shown in the following
  167. ** state diagram.
  168. **
  169. ** OPEN <------+------+
  170. ** | | |
  171. ** V | |
  172. ** +---------> READER-------+ |
  173. ** | | |
  174. ** | V |
  175. ** |<-------WRITER_LOCKED------> ERROR
  176. ** | | ^
  177. ** | V |
  178. ** |<------WRITER_CACHEMOD-------->|
  179. ** | | |
  180. ** | V |
  181. ** |<-------WRITER_DBMOD---------->|
  182. ** | | |
  183. ** | V |
  184. ** +<------WRITER_FINISHED-------->+
  185. **
  186. **
  187. ** List of state transitions and the C [function] that performs each:
  188. **
  189. ** OPEN -> READER [sqlite3PagerSharedLock]
  190. ** READER -> OPEN [pager_unlock]
  191. **
  192. ** READER -> WRITER_LOCKED [sqlite3PagerBegin]
  193. ** WRITER_LOCKED -> WRITER_CACHEMOD [pager_open_journal]
  194. ** WRITER_CACHEMOD -> WRITER_DBMOD [syncJournal]
  195. ** WRITER_DBMOD -> WRITER_FINISHED [sqlite3PagerCommitPhaseOne]
  196. ** WRITER_*** -> READER [pager_end_transaction]
  197. **
  198. ** WRITER_*** -> ERROR [pager_error]
  199. ** ERROR -> OPEN [pager_unlock]
  200. **
  201. **
  202. ** OPEN:
  203. **
  204. ** The pager starts up in this state. Nothing is guaranteed in this
  205. ** state - the file may or may not be locked and the database size is
  206. ** unknown. The database may not be read or written.
  207. **
  208. ** * No read or write transaction is active.
  209. ** * Any lock, or no lock at all, may be held on the database file.
  210. ** * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
  211. **
  212. ** READER:
  213. **
  214. ** In this state all the requirements for reading the database in
  215. ** rollback (non-WAL) mode are met. Unless the pager is (or recently
  216. ** was) in exclusive-locking mode, a user-level read transaction is
  217. ** open. The database size is known in this state.
  218. **
  219. ** A connection running with locking_mode=normal enters this state when
  220. ** it opens a read-transaction on the database and returns to state
  221. ** OPEN after the read-transaction is completed. However a connection
  222. ** running in locking_mode=exclusive (including temp databases) remains in
  223. ** this state even after the read-transaction is closed. The only way
  224. ** a locking_mode=exclusive connection can transition from READER to OPEN
  225. ** is via the ERROR state (see below).
  226. **
  227. ** * A read transaction may be active (but a write-transaction cannot).
  228. ** * A SHARED or greater lock is held on the database file.
  229. ** * The dbSize variable may be trusted (even if a user-level read
  230. ** transaction is not active). The dbOrigSize and dbFileSize variables
  231. ** may not be trusted at this point.
  232. ** * If the database is a WAL database, then the WAL connection is open.
  233. ** * Even if a read-transaction is not open, it is guaranteed that
  234. ** there is no hot-journal in the file-system.
  235. **
  236. ** WRITER_LOCKED:
  237. **
  238. ** The pager moves to this state from READER when a write-transaction
  239. ** is first opened on the database. In WRITER_LOCKED state, all locks
  240. ** required to start a write-transaction are held, but no actual
  241. ** modifications to the cache or database have taken place.
  242. **
  243. ** In rollback mode, a RESERVED or (if the transaction was opened with
  244. ** BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
  245. ** moving to this state, but the journal file is not written to or opened
  246. ** to in this state. If the transaction is committed or rolled back while
  247. ** in WRITER_LOCKED state, all that is required is to unlock the database
  248. ** file.
  249. **
  250. ** IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
  251. ** If the connection is running with locking_mode=exclusive, an attempt
  252. ** is made to obtain an EXCLUSIVE lock on the database file.
  253. **
  254. ** * A write transaction is active.
  255. ** * If the connection is open in rollback-mode, a RESERVED or greater
  256. ** lock is held on the database file.
  257. ** * If the connection is open in WAL-mode, a WAL write transaction
  258. ** is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
  259. ** called).
  260. ** * The dbSize, dbOrigSize and dbFileSize variables are all valid.
  261. ** * The contents of the pager cache have not been modified.
  262. ** * The journal file may or may not be open.
  263. ** * Nothing (not even the first header) has been written to the journal.
  264. **
  265. ** WRITER_CACHEMOD:
  266. **
  267. ** A pager moves from WRITER_LOCKED state to this state when a page is
  268. ** first modified by the upper layer. In rollback mode the journal file
  269. ** is opened (if it is not already open) and a header written to the
  270. ** start of it. The database file on disk has not been modified.
  271. **
  272. ** * A write transaction is active.
  273. ** * A RESERVED or greater lock is held on the database file.
  274. ** * The journal file is open and the first header has been written
  275. ** to it, but the header has not been synced to disk.
  276. ** * The contents of the page cache have been modified.
  277. **
  278. ** WRITER_DBMOD:
  279. **
  280. ** The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
  281. ** when it modifies the contents of the database file. WAL connections
  282. ** never enter this state (since they do not modify the database file,
  283. ** just the log file).
  284. **
  285. ** * A write transaction is active.
  286. ** * An EXCLUSIVE or greater lock is held on the database file.
  287. ** * The journal file is open and the first header has been written
  288. ** and synced to disk.
  289. ** * The contents of the page cache have been modified (and possibly
  290. ** written to disk).
  291. **
  292. ** WRITER_FINISHED:
  293. **
  294. ** It is not possible for a WAL connection to enter this state.
  295. **
  296. ** A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
  297. ** state after the entire transaction has been successfully written into the
  298. ** database file. In this state the transaction may be committed simply
  299. ** by finalizing the journal file. Once in WRITER_FINISHED state, it is
  300. ** not possible to modify the database further. At this point, the upper
  301. ** layer must either commit or rollback the transaction.
  302. **
  303. ** * A write transaction is active.
  304. ** * An EXCLUSIVE or greater lock is held on the database file.
  305. ** * All writing and syncing of journal and database data has finished.
  306. ** If no error occured, all that remains is to finalize the journal to
  307. ** commit the transaction. If an error did occur, the caller will need
  308. ** to rollback the transaction.
  309. **
  310. ** ERROR:
  311. **
  312. ** The ERROR state is entered when an IO or disk-full error (including
  313. ** SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
  314. ** difficult to be sure that the in-memory pager state (cache contents,
  315. ** db size etc.) are consistent with the contents of the file-system.
  316. **
  317. ** Temporary pager files may enter the ERROR state, but in-memory pagers
  318. ** cannot.
  319. **
  320. ** For example, if an IO error occurs while performing a rollback,
  321. ** the contents of the page-cache may be left in an inconsistent state.
  322. ** At this point it would be dangerous to change back to READER state
  323. ** (as usually happens after a rollback). Any subsequent readers might
  324. ** report database corruption (due to the inconsistent cache), and if
  325. ** they upgrade to writers, they may inadvertently corrupt the database
  326. ** file. To avoid this hazard, the pager switches into the ERROR state
  327. ** instead of READER following such an error.
  328. **
  329. ** Once it has entered the ERROR state, any attempt to use the pager
  330. ** to read or write data returns an error. Eventually, once all
  331. ** outstanding transactions have been abandoned, the pager is able to
  332. ** transition back to OPEN state, discarding the contents of the
  333. ** page-cache and any other in-memory state at the same time. Everything
  334. ** is reloaded from disk (and, if necessary, hot-journal rollback peformed)
  335. ** when a read-transaction is next opened on the pager (transitioning
  336. ** the pager into READER state). At that point the system has recovered
  337. ** from the error.
  338. **
  339. ** Specifically, the pager jumps into the ERROR state if:
  340. **
  341. ** 1. An error occurs while attempting a rollback. This happens in
  342. ** function sqlite3PagerRollback().
  343. **
  344. ** 2. An error occurs while attempting to finalize a journal file
  345. ** following a commit in function sqlite3PagerCommitPhaseTwo().
  346. **
  347. ** 3. An error occurs while attempting to write to the journal or
  348. ** database file in function pagerStress() in order to free up
  349. ** memory.
  350. **
  351. ** In other cases, the error is returned to the b-tree layer. The b-tree
  352. ** layer then attempts a rollback operation. If the error condition
  353. ** persists, the pager enters the ERROR state via condition (1) above.
  354. **
  355. ** Condition (3) is necessary because it can be triggered by a read-only
  356. ** statement executed within a transaction. In this case, if the error
  357. ** code were simply returned to the user, the b-tree layer would not
  358. ** automatically attempt a rollback, as it assumes that an error in a
  359. ** read-only statement cannot leave the pager in an internally inconsistent
  360. ** state.
  361. **
  362. ** * The Pager.errCode variable is set to something other than SQLITE_OK.
  363. ** * There are one or more outstanding references to pages (after the
  364. ** last reference is dropped the pager should move back to OPEN state).
  365. ** * The pager is not an in-memory pager.
  366. **
  367. **
  368. ** Notes:
  369. **
  370. ** * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
  371. ** connection is open in WAL mode. A WAL connection is always in one
  372. ** of the first four states.
  373. **
  374. ** * Normally, a connection open in exclusive mode is never in PAGER_OPEN
  375. ** state. There are two exceptions: immediately after exclusive-mode has
  376. ** been turned on (and before any read or write transactions are
  377. ** executed), and when the pager is leaving the "error state".
  378. **
  379. ** * See also: assert_pager_state().
  380. */
  381. //#define PAGER_OPEN 0
  382. //#define PAGER_READER 1
  383. //#define PAGER_WRITER_LOCKED 2
  384. //#define PAGER_WRITER_CACHEMOD 3
  385. //#define PAGER_WRITER_DBMOD 4
  386. //#define PAGER_WRITER_FINISHED 5
  387. //#define PAGER_ERROR 6
  388. const int PAGER_OPEN = 0;
  389. const int PAGER_READER = 1;
  390. const int PAGER_WRITER_LOCKED = 2;
  391. const int PAGER_WRITER_CACHEMOD = 3;
  392. const int PAGER_WRITER_DBMOD = 4;
  393. const int PAGER_WRITER_FINISHED = 5;
  394. const int PAGER_ERROR = 6;
  395. /*
  396. ** The Pager.eLock variable is almost always set to one of the
  397. ** following locking-states, according to the lock currently held on
  398. ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  399. ** This variable is kept up to date as locks are taken and released by
  400. ** the pagerLockDb() and pagerUnlockDb() wrappers.
  401. **
  402. ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
  403. ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
  404. ** the operation was successful. In these circumstances pagerLockDb() and
  405. ** pagerUnlockDb() take a conservative approach - eLock is always updated
  406. ** when unlocking the file, and only updated when locking the file if the
  407. ** VFS call is successful. This way, the Pager.eLock variable may be set
  408. ** to a less exclusive (lower) value than the lock that is actually held
  409. ** at the system level, but it is never set to a more exclusive value.
  410. **
  411. ** This is usually safe. If an xUnlock fails or appears to fail, there may
  412. ** be a few redundant xLock() calls or a lock may be held for longer than
  413. ** required, but nothing really goes wrong.
  414. **
  415. ** The exception is when the database file is unlocked as the pager moves
  416. ** from ERROR to OPEN state. At this point there may be a hot-journal file
  417. ** in the file-system that needs to be rolled back (as part of a OPEN->SHARED
  418. ** transition, by the same pager or any other). If the call to xUnlock()
  419. ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
  420. ** can confuse the call to xCheckReservedLock() call made later as part
  421. ** of hot-journal detection.
  422. **
  423. ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
  424. ** lock held by this process or any others". So xCheckReservedLock may
  425. ** return true because the caller itself is holding an EXCLUSIVE lock (but
  426. ** doesn't know it because of a previous error in xUnlock). If this happens
  427. ** a hot-journal may be mistaken for a journal being created by an active
  428. ** transaction in another process, causing SQLite to read from the database
  429. ** without rolling it back.
  430. **
  431. ** To work around this, if a call to xUnlock() fails when unlocking the
  432. ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
  433. ** is only changed back to a real locking state after a successful call
  434. ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
  435. ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
  436. ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
  437. ** lock on the database file before attempting to roll it back. See function
  438. ** PagerSharedLock() for more detail.
  439. **
  440. ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
  441. ** PAGER_OPEN state.
  442. */
  443. //#define UNKNOWN_LOCK (EXCLUSIVE_LOCK+1)
  444. const int UNKNOWN_LOCK = ( EXCLUSIVE_LOCK + 1 );
  445. /*
  446. ** A macro used for invoking the codec if there is one
  447. */
  448. // The E parameter is what executes when there is an error,
  449. // cannot implement here, since this is not really a macro
  450. // calling code must be modified to call E when truen
  451. #if SQLITE_HAS_CODEC
  452. //# define CODEC1(P,D,N,X,E) \
  453. //if( P.xCodec && P.xCodec(P.pCodec,D,N,X)==0 ){ E; }
  454. static bool CODEC1( Pager P, byte[] D, uint N /* page number */, int X /* E (moved to caller */)
  455. {
  456. return ( ( P.xCodec != null ) && ( P.xCodec( P.pCodec, D, N, X ) == null ) );
  457. }
  458. // The E parameter is what executes when there is an error,
  459. // cannot implement here, since this is not really a macro
  460. // calling code must be modified to call E when truen
  461. //# define CODEC2(P,D,N,X,E,O) \
  462. //if( P.xCodec==0 ){ O=(char*)D; }else \
  463. //if( (O=(char*)(P.xCodec(P.pCodec,D,N,X)))==0 ){ E; }
  464. static bool CODEC2( Pager P, byte[] D, uint N, int X, ref byte[] O )
  465. {
  466. if ( P.xCodec == null )
  467. {
  468. O = D; // do nothing
  469. return false;
  470. }
  471. else
  472. {
  473. return ( ( O = P.xCodec( P.pCodec, D, N, X ) ) == null );
  474. }
  475. }
  476. #else
  477. //# define CODEC1(P,D,N,X,E) /* NO-OP */
  478. static bool CODEC1 (Pager P, byte[] D, uint N /* page number */, int X /* E (moved to caller */) { return false; }
  479. //# define CODEC2(P,D,N,X,E,O) O=(char*)D
  480. static bool CODEC2( Pager P, byte[] D, uint N, int X, ref byte[] O ) { O = D; return false; }
  481. #endif
  482. /*
  483. ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
  484. ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
  485. ** This could conceivably cause corruption following a power failure on
  486. ** such a system. This is currently an undocumented limit.
  487. */
  488. //#define MAX_SECTOR_SIZE 0x10000
  489. const int MAX_SECTOR_SIZE = 0x10000;
  490. /*
  491. ** An instance of the following structure is allocated for each active
  492. ** savepoint and statement transaction in the system. All such structures
  493. ** are stored in the Pager.aSavepoint[] array, which is allocated and
  494. ** resized using sqlite3Realloc().
  495. **
  496. ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
  497. ** set to 0. If a journal-header is written into the main journal while
  498. ** the savepoint is active, then iHdrOffset is set to the byte offset
  499. ** immediately following the last journal record written into the main
  500. ** journal before the journal-header. This is required during savepoint
  501. ** rollback (see pagerPlaybackSavepoint()).
  502. */
  503. //typedef struct PagerSavepoint PagerSavepoint;
  504. public class PagerSavepoint
  505. {
  506. public i64 iOffset; /* Starting offset in main journal */
  507. public i64 iHdrOffset; /* See above */
  508. public Bitvec pInSavepoint; /* Set of pages in this savepoint */
  509. public Pgno nOrig; /* Original number of pages in file */
  510. public Pgno iSubRec; /* Index of first record in sub-journal */
  511. #if !SQLITE_OMIT_WAL
  512. public u32 aWalData[WAL_SAVEPOINT_NDATA]; /* WAL savepoint context */
  513. #else
  514. public object aWalData = null; /* Used for C# convenience */
  515. #endif
  516. public static implicit operator bool( PagerSavepoint b )
  517. {
  518. return ( b != null );
  519. }
  520. };
  521. /*
  522. ** A open page cache is an instance of struct Pager. A description of
  523. ** some of the more important member variables follows:
  524. **
  525. ** eState
  526. **
  527. ** The current 'state' of the pager object. See the comment and state
  528. ** diagram above for a description of the pager state.
  529. **
  530. ** eLock
  531. **
  532. ** For a real on-disk database, the current lock held on the database file -
  533. ** NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  534. **
  535. ** For a temporary or in-memory database (neither of which require any
  536. ** locks), this variable is always set to EXCLUSIVE_LOCK. Since such
  537. ** databases always have Pager.exclusiveMode==1, this tricks the pager
  538. ** logic into thinking that it already has all the locks it will ever
  539. ** need (and no reason to release them).
  540. **
  541. ** In some (obscure) circumstances, this variable may also be set to
  542. ** UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
  543. ** details.
  544. **
  545. ** changeCountDone
  546. **
  547. ** This boolean variable is used to make sure that the change-counter
  548. ** (the 4-byte header field at byte offset 24 of the database file) is
  549. ** not updated more often than necessary.
  550. **
  551. ** It is set to true when the change-counter field is updated, which
  552. ** can only happen if an exclusive lock is held on the database file.
  553. ** It is cleared (set to false) whenever an exclusive lock is
  554. ** relinquished on the database file. Each time a transaction is committed,
  555. ** The changeCountDone flag is inspected. If it is true, the work of
  556. ** updating the change-counter is omitted for the current transaction.
  557. **
  558. ** This mechanism means that when running in exclusive mode, a connection
  559. ** need only update the change-counter once, for the first transaction
  560. ** committed.
  561. **
  562. ** setMaster
  563. **
  564. ** When PagerCommitPhaseOne() is called to commit a transaction, it may
  565. ** (or may not) specify a master-journal name to be written into the
  566. ** journal file before it is synced to disk.
  567. **
  568. ** Whether or not a journal file contains a master-journal pointer affects
  569. ** the way in which the journal file is finalized after the transaction is
  570. ** committed or rolled back when running in "journal_mode=PERSIST" mode.
  571. ** If a journal file does not contain a master-journal pointer, it is
  572. ** finalized by overwriting the first journal header with zeroes. If
  573. ** it does contain a master-journal pointer the journal file is finalized
  574. ** by truncating it to zero bytes, just as if the connection were
  575. ** running in "journal_mode=truncate" mode.
  576. **
  577. ** Journal files that contain master journal pointers cannot be finalized
  578. ** simply by overwriting the first journal-header with zeroes, as the
  579. ** master journal pointer could interfere with hot-journal rollback of any
  580. ** subsequently interrupted transaction that reuses the journal file.
  581. **
  582. ** The flag is cleared as soon as the journal file is finalized (either
  583. ** by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
  584. ** journal file from being successfully finalized, the setMaster flag
  585. ** is cleared anyway (and the pager will move to ERROR state).
  586. **
  587. ** doNotSpill, doNotSyncSpill
  588. **
  589. ** These two boolean variables control the behaviour of cache-spills
  590. ** (calls made by the pcache module to the pagerStress() routine to
  591. ** write cached data to the file-system in order to free up memory).
  592. **
  593. ** When doNotSpill is non-zero, writing to the database from pagerStress()
  594. ** is disabled altogether. This is done in a very obscure case that
  595. ** comes up during savepoint rollback that requires the pcache module
  596. ** to allocate a new page to prevent the journal file from being written
  597. ** while it is being traversed by code in pager_playback().
  598. **
  599. ** If doNotSyncSpill is non-zero, writing to the database from pagerStress()
  600. ** is permitted, but syncing the journal file is not. This flag is set
  601. ** by sqlite3PagerWrite() when the file-system sector-size is larger than
  602. ** the database page-size in order to prevent a journal sync from happening
  603. ** in between the journalling of two pages on the same sector.
  604. **
  605. ** subjInMemory
  606. **
  607. ** This is a boolean variable. If true, then any required sub-journal
  608. ** is opened as an in-memory journal file. If false, then in-memory
  609. ** sub-journals are only used for in-memory pager files.
  610. **
  611. ** This variable is updated by the upper layer each time a new
  612. ** write-transaction is opened.
  613. **
  614. ** dbSize, dbOrigSize, dbFileSize
  615. **
  616. ** Variable dbSize is set to the number of pages in the database file.
  617. ** It is valid in PAGER_READER and higher states (all states except for
  618. ** OPEN and ERROR).
  619. **
  620. ** dbSize is set based on the size of the database file, which may be
  621. ** larger than the size of the database (the value stored at offset
  622. ** 28 of the database header by the btree). If the size of the file
  623. ** is not an integer multiple of the page-size, the value stored in
  624. ** dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
  625. ** Except, any file that is greater than 0 bytes in size is considered
  626. ** to have at least one page. (i.e. a 1KB file with 2K page-size leads
  627. ** to dbSize==1).
  628. **
  629. ** During a write-transaction, if pages with page-numbers greater than
  630. ** dbSize are modified in the cache, dbSize is updated accordingly.
  631. ** Similarly, if the database is truncated using PagerTruncateImage(),
  632. ** dbSize is updated.
  633. **
  634. ** Variables dbOrigSize and dbFileSize are valid in states
  635. ** PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
  636. ** variable at the start of the transaction. It is used during rollback,
  637. ** and to determine whether or not pages need to be journalled before
  638. ** being modified.
  639. **
  640. ** Throughout a write-transaction, dbFileSize contains the size of
  641. ** the file on disk in pages. It is set to a copy of dbSize when the
  642. ** write-transaction is first opened, and updated when VFS calls are made
  643. ** to write or truncate the database file on disk.
  644. **
  645. ** The only reason the dbFileSize variable is required is to suppress
  646. ** unnecessary calls to xTruncate() after committing a transaction. If,
  647. ** when a transaction is committed, the dbFileSize variable indicates
  648. ** that the database file is larger than the database image (Pager.dbSize),
  649. ** pager_truncate() is called. The pager_truncate() call uses xFilesize()
  650. ** to measure the database file on disk, and then truncates it if required.
  651. ** dbFileSize is not used when rolling back a transaction. In this case
  652. ** pager_truncate() is called unconditionally (which means there may be
  653. ** a call to xFilesize() that is not strictly required). In either case,
  654. ** pager_truncate() may cause the file to become smaller or larger.
  655. **
  656. ** dbHintSize
  657. **
  658. ** The dbHintSize variable is used to limit the number of calls made to
  659. ** the VFS xFileControl(FCNTL_SIZE_HINT) method.
  660. **
  661. ** dbHintSize is set to a copy of the dbSize variable when a
  662. ** write-transaction is opened (at the same time as dbFileSize and
  663. ** dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
  664. ** dbHintSize is increased to the number of pages that correspond to the
  665. ** size-hint passed to the method call. See pager_write_pagelist() for
  666. ** details.
  667. **
  668. ** errCode
  669. **
  670. ** The Pager.errCode variable is only ever used in PAGER_ERROR state. It
  671. ** is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
  672. ** is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
  673. ** sub-codes.
  674. */
  675. public class Pager
  676. {
  677. public sqlite3_vfs pVfs; /* OS functions to use for IO */
  678. public bool exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */
  679. public u8 journalMode; /* One of the PAGER_JOURNALMODE_* values */
  680. public u8 useJournal; /* Use a rollback journal on this file */
  681. public u8 noReadlock; /* Do not bother to obtain readlocks */
  682. public bool noSync; /* Do not sync the journal if true */
  683. public bool fullSync; /* Do extra syncs of the journal for robustness */
  684. public u8 ckptSyncFlags; /* SYNC_NORMAL or SYNC_FULL for checkpoint */
  685. public u8 syncFlags; /* SYNC_NORMAL or SYNC_FULL otherwise */
  686. public bool tempFile; /* zFilename is a temporary file */
  687. public bool readOnly; /* True for a read-only database */
  688. public bool alwaysRollback; /* Disable DontRollback() for all pages */
  689. public u8 memDb; /* True to inhibit all file I/O */
  690. /**************************************************************************
  691. ** The following block contains those class members that change during
  692. ** routine opertion. Class members not in this block are either fixed
  693. ** when the pager is first created or else only change when there is a
  694. ** significant mode change (such as changing the page_size, locking_mode,
  695. ** or the journal_mode). From another view, these class members describe
  696. ** the "state" of the pager, while other class members describe the
  697. ** "configuration" of the pager.
  698. */
  699. public u8 eState; /* Pager state (OPEN, READER, WRITER_LOCKED..) */
  700. public u8 eLock; /* Current lock held on database file */
  701. public bool changeCountDone; /* Set after incrementing the change-counter */
  702. public int setMaster; /* True if a m-j name has been written to jrnl */
  703. public u8 doNotSpill; /* Do not spill the cache when non-zero */
  704. public u8 doNotSyncSpill; /* Do not do a spill that requires jrnl sync */
  705. public u8 subjInMemory; /* True to use in-memory sub-journals */
  706. public Pgno dbSize; /* Number of pages in the database */
  707. public Pgno dbOrigSize; /* dbSize before the current transaction */
  708. public Pgno dbFileSize; /* Number of pages in the database file */
  709. public Pgno dbHintSize; /* Value passed to FCNTL_SIZE_HINT call */
  710. public int errCode; /* One of several kinds of errors */
  711. public int nRec; /* Pages journalled since last j-header written */
  712. public u32 cksumInit; /* Quasi-random value added to every checksum */
  713. public u32 nSubRec; /* Number of records written to sub-journal */
  714. public Bitvec pInJournal; /* One bit for each page in the database file */
  715. public sqlite3_file fd; /* File descriptor for database */
  716. public sqlite3_file jfd; /* File descriptor for main journal */
  717. public sqlite3_file sjfd; /* File descriptor for sub-journal */
  718. public i64 journalOff; /* Current write offset in the journal file */
  719. public i64 journalHdr; /* Byte offset to previous journal header */
  720. public sqlite3_backup pBackup; /* Pointer to list of ongoing backup processes */
  721. public PagerSavepoint[] aSavepoint;/* Array of active savepoints */
  722. public int nSavepoint; /* Number of elements in aSavepoint[] */
  723. public u8[] dbFileVers = new u8[16];/* Changes whenever database file changes */
  724. /*
  725. ** End of the routinely-changing class members
  726. ***************************************************************************/
  727. public u16 nExtra; /* Add this many bytes to each in-memory page */
  728. public i16 nReserve; /* Number of unused bytes at end of each page */
  729. public u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */
  730. public u32 sectorSize; /* Assumed sector size during rollback */
  731. public int pageSize; /* Number of bytes in a page */
  732. public Pgno mxPgno; /* Maximum allowed size of the database */
  733. public i64 journalSizeLimit; /* Size limit for persistent journal files */
  734. public string zFilename; /* Name of the database file */
  735. public string zJournal; /* Name of the journal file */
  736. public dxBusyHandler xBusyHandler; /* Function to call when busy */
  737. public object pBusyHandlerArg; /* Context argument for xBusyHandler */
  738. #if SQLITE_TEST || DEBUG
  739. public int nHit, nMiss; /* Cache hits and missing */
  740. public int nRead, nWrite; /* Database pages read/written */
  741. #else
  742. public int nHit;
  743. #endif
  744. public dxReiniter xReiniter; //(DbPage*,int);/* Call this routine when reloading pages */
  745. #if SQLITE_HAS_CODEC
  746. //void *(*xCodec)(void*,void*,Pgno,int);
  747. public dxCodec xCodec; /* Routine for en/decoding data */
  748. //void (*xCodecSizeChng)(void*,int,int);
  749. public dxCodecSizeChng xCodecSizeChng; /* Notify of page size changes */
  750. //void (*xCodecFree)(void*);
  751. public dxCodecFree xCodecFree; /* Destructor for the codec */
  752. public codec_ctx pCodec; /* First argument to xCodec... methods */
  753. #endif
  754. public byte[] pTmpSpace; /* Pager.pageSize bytes of space for tmp use */
  755. public PCache pPCache; /* Pointer to page cache object */
  756. #if !SQLITE_OMIT_WAL
  757. public Wal pWal; /* Write-ahead log used by "journal_mode=wal" */
  758. public string zWal; /* File name for write-ahead log */
  759. #else
  760. public sqlite3_vfs pWal = null; /* Having this dummy here makes C# easier */
  761. #endif
  762. };
  763. /*
  764. ** The following global variables hold counters used for
  765. ** testing purposes only. These variables do not exist in
  766. ** a non-testing build. These variables are not thread-safe.
  767. */
  768. #if SQLITE_TEST
  769. #if !TCLSH
  770. static int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */
  771. static int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */
  772. static int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */
  773. #else
  774. static tcl.lang.Var.SQLITE3_GETSET sqlite3_pager_readdb_count = new tcl.lang.Var.SQLITE3_GETSET( "sqlite3_pager_readdb_count" );
  775. static tcl.lang.Var.SQLITE3_GETSET sqlite3_pager_writedb_count = new tcl.lang.Var.SQLITE3_GETSET( "sqlite3_pager_writedb_count" );
  776. static tcl.lang.Var.SQLITE3_GETSET sqlite3_pager_writej_count = new tcl.lang.Var.SQLITE3_GETSET( "sqlite3_pager_writej_count" );
  777. #endif
  778. static void PAGER_INCR( ref int v )
  779. {
  780. v++;
  781. }
  782. #else
  783. //# define PAGER_INCR(v)
  784. static void PAGER_INCR(ref int v) {}
  785. #endif
  786. /*
  787. ** Journal files begin with the following magic string. The data
  788. ** was obtained from /dev/random. It is used only as a sanity check.
  789. **
  790. ** Since version 2.8.0, the journal format contains additional sanity
  791. ** checking information. If the power fails while the journal is being
  792. ** written, semi-random garbage data might appear in the journal
  793. ** file after power is restored. If an attempt is then made
  794. ** to roll the journal back, the database could be corrupted. The additional
  795. ** sanity checking data is an attempt to discover the garbage in the
  796. ** journal and ignore it.
  797. **
  798. ** The sanity checking information for the new journal format consists
  799. ** of a 32-bit checksum on each page of data. The checksum covers both
  800. ** the page number and the pPager.pageSize bytes of data for the page.
  801. ** This cksum is initialized to a 32-bit random value that appears in the
  802. ** journal file right after the header. The random initializer is important,
  803. ** because garbage data that appears at the end of a journal is likely
  804. ** data that was once in other files that have now been deleted. If the
  805. ** garbage data came from an obsolete journal file, the checksums might
  806. ** be correct. But by initializing the checksum to random value which
  807. ** is different for every journal, we minimize that risk.
  808. */
  809. static byte[] aJournalMagic = new byte[] {
  810. 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
  811. };
  812. /*
  813. ** The size of the of each page record in the journal is given by
  814. ** the following macro.
  815. */
  816. //#define JOURNAL_PG_SZ(pPager) ((pPager.pageSize) + 8)
  817. static int JOURNAL_PG_SZ( Pager pPager )
  818. {
  819. return ( pPager.pageSize + 8 );
  820. }
  821. /*
  822. ** The journal header size for this pager. This is usually the same
  823. ** size as a single disk sector. See also setSectorSize().
  824. */
  825. //#define JOURNAL_HDR_SZ(pPager) (pPager.sectorSize)
  826. static u32 JOURNAL_HDR_SZ( Pager pPager )
  827. {
  828. return ( pPager.sectorSize );
  829. }
  830. /*
  831. ** The macro MEMDB is true if we are dealing with an in-memory database.
  832. ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
  833. ** the value of MEMDB will be a constant and the compiler will optimize
  834. ** out code that would never execute.
  835. */
  836. #if SQLITE_OMIT_MEMORYDB
  837. //# define MEMDB 0
  838. const int MEMDB = 0;
  839. #else
  840. //# define MEMDB pPager.memDb
  841. #endif
  842. /*
  843. ** The maximum legal page number is (2^31 - 1).
  844. */
  845. //#define PAGER_MAX_PGNO 2147483647
  846. const int PAGER_MAX_PGNO = 2147483647;
  847. /*
  848. ** The argument to this macro is a file descriptor (type sqlite3_file*).
  849. ** Return 0 if it is not open, or non-zero (but not 1) if it is.
  850. **
  851. ** This is so that expressions can be written as:
  852. **
  853. ** if( isOpen(pPager.jfd) ){ ...
  854. **
  855. ** instead of
  856. **
  857. ** if( pPager.jfd->pMethods ){ ...
  858. */
  859. //#define isOpen(pFd) ((pFd)->pMethods)
  860. static bool isOpen( sqlite3_file pFd )
  861. {
  862. return pFd.pMethods != null;
  863. }
  864. /*
  865. ** Return true if this pager uses a write-ahead log instead of the usual
  866. ** rollback journal. Otherwise false.
  867. */
  868. #if !SQLITE_OMIT_WAL
  869. static int pagerUseWal(Pager *pPager){
  870. return (pPager->pWal!=0);
  871. }
  872. #else
  873. //# define pagerUseWal(x) 0
  874. static bool pagerUseWal( Pager x )
  875. {
  876. return false;
  877. }
  878. //# define pagerRollbackWal(x) 0
  879. static int pagerRollbackWal( Pager x )
  880. {
  881. return 0;
  882. }
  883. //# define pagerWalFrames(v,w,x,y,z) 0
  884. static int pagerWalFrames( Pager v, PgHdr w, Pgno x, int y, int z )
  885. {
  886. return 0;
  887. }
  888. //# define pagerOpenWalIfPresent(z) SQLITE_OK
  889. static int pagerOpenWalIfPresent( Pager z )
  890. {
  891. return SQLITE_OK;
  892. }
  893. //# define pagerBeginReadTransaction(z) SQLITE_OK
  894. static int pagerBeginReadTransaction( Pager z )
  895. {
  896. return SQLITE_OK;
  897. }
  898. #endif
  899. #if NDEBUG
  900. /*
  901. ** Usage:
  902. **
  903. ** Debug.Assert( assert_pager_state(pPager) );
  904. **
  905. ** This function runs many Debug.Asserts to try to find inconsistencies in
  906. ** the internal state of the Pager object.
  907. */
  908. static bool assert_pager_state( Pager p )
  909. {
  910. Pager pPager = p;
  911. /* State must be valid. */
  912. Debug.Assert( p.eState == PAGER_OPEN
  913. || p.eState == PAGER_READER
  914. || p.eState == PAGER_WRITER_LOCKED
  915. || p.eState == PAGER_WRITER_CACHEMOD
  916. || p.eState == PAGER_WRITER_DBMOD
  917. || p.eState == PAGER_WRITER_FINISHED
  918. || p.eState == PAGER_ERROR
  919. );
  920. /* Regardless of the current state, a temp-file connection always behaves
  921. ** as if it has an exclusive lock on the database file. It never updates
  922. ** the change-counter field, so the changeCountDone flag is always set.
  923. */
  924. Debug.Assert( p.tempFile == false || p.eLock == EXCLUSIVE_LOCK );
  925. Debug.Assert( p.tempFile == false || pPager.changeCountDone );
  926. /* If the useJournal flag is clear, the journal-mode must be "OFF".
  927. ** And if the journal-mode is "OFF", the journal file must not be open.
  928. */
  929. Debug.Assert( p.journalMode == PAGER_JOURNALMODE_OFF || p.useJournal != 0 );
  930. Debug.Assert( p.journalMode != PAGER_JOURNALMODE_OFF || !isOpen( p.jfd ) );
  931. /* Check that MEMDB implies noSync. And an in-memory journal. Since
  932. ** this means an in-memory pager performs no IO at all, it cannot encounter
  933. ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
  934. ** a journal file. (although the in-memory journal implementation may
  935. ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
  936. ** is therefore not possible for an in-memory pager to enter the ERROR
  937. ** state.
  938. */
  939. if (
  940. #if SQLITE_OMIT_MEMORYDB
  941. 0!=MEMDB
  942. #else
  943. 0 != pPager.memDb
  944. #endif
  945. )
  946. {
  947. Debug.Assert( p.noSync );
  948. Debug.Assert( p.journalMode == PAGER_JOURNALMODE_OFF
  949. || p.journalMode == PAGER_JOURNALMODE_MEMORY
  950. );
  951. Debug.Assert( p.eState != PAGER_ERROR && p.eState != PAGER_OPEN );
  952. Debug.Assert( pagerUseWal( p ) == false );
  953. }
  954. /* If changeCountDone is set, a RESERVED lock or greater must be held
  955. ** on the file.
  956. */
  957. Debug.Assert( pPager.changeCountDone == false || pPager.eLock >= RESERVED_LOCK );
  958. Debug.Assert( p.eLock != PENDING_LOCK );
  959. switch ( p.eState )
  960. {
  961. case PAGER_OPEN:
  962. Debug.Assert(
  963. #if SQLITE_OMIT_MEMORYDB
  964. 0==MEMDB
  965. #else
  966. 0 == pPager.memDb
  967. #endif
  968. );
  969. Debug.Assert( pPager.errCode == SQLITE_OK );
  970. Debug.Assert( sqlite3PcacheRefCount( pPager.pPCache ) == 0 || pPager.tempFile );
  971. break;
  972. case PAGER_READER:
  973. Debug.Assert( pPager.errCode == SQLITE_OK );
  974. Debug.Assert( p.eLock != UNKNOWN_LOCK );
  975. Debug.Assert( p.eLock >= SHARED_LOCK || p.noReadlock != 0 );
  976. break;
  977. case PAGER_WRITER_LOCKED:
  978. Debug.Assert( p.eLock != UNKNOWN_LOCK );
  979. Debug.Assert( pPager.errCode == SQLITE_OK );
  980. if ( !pagerUseWal( pPager ) )
  981. {
  982. Debug.Assert( p.eLock >= RESERVED_LOCK );
  983. }
  984. Debug.Assert( pPager.dbSize == pPager.dbOrigSize );
  985. Debug.Assert( pPager.dbOrigSize == pPager.dbFileSize );
  986. Debug.Assert( pPager.dbOrigSize == pPager.dbHintSize );
  987. Debug.Assert( pPager.setMaster == 0 );
  988. break;
  989. case PAGER_WRITER_CACHEMOD:
  990. Debug.Assert( p.eLock != UNKNOWN_LOCK );
  991. Debug.Assert( pPager.errCode == SQLITE_OK );
  992. if ( !pagerUseWal( pPager ) )
  993. {
  994. /* It is possible that if journal_mode=wal here that neither the
  995. ** journal file nor the WAL file are open. This happens during
  996. ** a rollback transaction that switches from journal_mode=off
  997. ** to journal_mode=wal.
  998. */
  999. Debug.Assert( p.eLock >= RESERVED_LOCK );
  1000. Debug.Assert( isOpen( p.jfd )
  1001. || p.journalMode == PAGER_JOURNALMODE_OFF
  1002. || p.journalMode == PAGER_JOURNALMODE_WAL
  1003. );
  1004. }
  1005. Debug.Assert( pPager.dbOrigSize == pPager.dbFileSize );
  1006. Debug.Assert( pPager.dbOrigSize == pPager.dbHintSize );
  1007. break;
  1008. case PAGER_WRITER_DBMOD:
  1009. Debug.Assert( p.eLock == EXCLUSIVE_LOCK );
  1010. Debug.Assert( pPager.errCode == SQLITE_OK );
  1011. Debug.Assert( !pagerUseWal( pPager ) );
  1012. Debug.Assert( p.eLock >= EXCLUSIVE_LOCK );
  1013. Debug.Assert( isOpen( p.jfd )
  1014. || p.journalMode == PAGER_JOURNALMODE_OFF
  1015. || p.journalMode == PAGER_JOURNALMODE_WAL
  1016. );
  1017. Debug.Assert( pPager.dbOrigSize <= pPager.dbHintSize );
  1018. break;
  1019. case PAGER_WRITER_FINISHED:
  1020. Debug.Assert( p.eLock == EXCLUSIVE_LOCK );
  1021. Debug.Assert( pPager.errCode == SQLITE_OK );
  1022. Debug.Assert( !pagerUseWal( pPager ) );
  1023. Debug.Assert( isOpen( p.jfd )
  1024. || p.journalMode == PAGER_JOURNALMODE_OFF
  1025. || p.journalMode == PAGER_JOURNALMODE_WAL
  1026. );
  1027. break;
  1028. case PAGER_ERROR:
  1029. /* There must be at least one outstanding reference to the pager if
  1030. ** in ERROR state. Otherwise the pager should have already dropped
  1031. ** back to OPEN state.
  1032. */
  1033. Debug.Assert( pPager.errCode != SQLITE_OK );
  1034. Debug.Assert( sqlite3PcacheRefCount( pPager.pPCache ) > 0 );
  1035. break;
  1036. }
  1037. return true;
  1038. }
  1039. #else
  1040. static bool assert_pager_state( Pager pPager )
  1041. {
  1042. return true;
  1043. }
  1044. #endif //* ifndef NDEBUG */
  1045. #if SQLITE_DEBUG
  1046. /*
  1047. ** Return a pointer to a human readable string in a static buffer
  1048. ** containing the state of the Pager object passed as an argument. This
  1049. ** is intended to be used within debuggers. For example, as an alternative
  1050. ** to "print *pPager" in gdb:
  1051. **
  1052. ** (gdb) printf "%s", print_pager_state(pPager)
  1053. */
  1054. static string print_pager_state( Pager p )
  1055. {
  1056. StringBuilder zRet = new StringBuilder( 1024 );
  1057. sqlite3_snprintf( 1024, zRet,
  1058. "Filename: %s\n" +
  1059. "State: %s errCode=%d\n" +
  1060. "Lock: %s\n" +
  1061. "Locking mode: locking_mode=%s\n" +
  1062. "Journal mode: journal_mode=%s\n" +
  1063. "Backing store: tempFile=%d memDb=%d useJournal=%d\n" +
  1064. "Journal: journalOff=%lld journalHdr=%lld\n" +
  1065. "Size: dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
  1066. , p.zFilename
  1067. , p.eState == PAGER_OPEN ? "OPEN" :
  1068. p.eState == PAGER_READER ? "READER" :
  1069. p.eState == PAGER_WRITER_LOCKED ? "WRITER_LOCKED" :
  1070. p.eState == PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
  1071. p.eState == PAGER_WRITER_DBMOD ? "WRITER_DBMOD" :
  1072. p.eState == PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
  1073. p.eState == PAGER_ERROR ? "ERROR" : "?error?"
  1074. , (int)p.errCode
  1075. , p.eLock == NO_LOCK ? "NO_LOCK" :
  1076. p.eLock == RESERVED_LOCK ? "RESERVED" :
  1077. p.eLock == EXCLUSIVE_LOCK ? "EXCLUSIVE" :
  1078. p.eLock == SHARED_LOCK ? "SHARED" :
  1079. p.eLock == UNKNOWN_LOCK ? "UNKNOWN" : "?error?"
  1080. , p.exclusiveMode ? "exclusive" : "normal"
  1081. , p.journalMode == PAGER_JOURNALMODE_MEMORY ? "memory" :
  1082. p.journalMode == PAGER_JOURNALMODE_OFF ? "off" :
  1083. p.journalMode == PAGER_JOURNALMODE_DELETE ? "delete" :
  1084. p.journalMode == PAGER_JOURNALMODE_PERSIST ? "persist" :
  1085. p.journalMode == PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
  1086. p.journalMode == PAGER_JOURNALMODE_WAL ? "wal" : "?error?"
  1087. , p.tempFile ? 1 : 0, (int)p.memDb, (int)p.useJournal
  1088. , p.journalOff, p.journalHdr
  1089. , (int)p.dbSize, (int)p.dbOrigSize, (int)p.dbFileSize
  1090. );
  1091. return zRet.ToString();
  1092. }
  1093. #endif
  1094. /*
  1095. ** Return true if it is necessary to write page *pPg into the sub-journal.
  1096. ** A page needs to be written into the sub-journal if there exists one
  1097. ** or more open savepoints for which:
  1098. **
  1099. ** * The page-number is less than or equal to PagerSavepoint.nOrig, and
  1100. ** * The bit corresponding to the page-number is not set in
  1101. ** PagerSavepoint.pInSavepoint.
  1102. */
  1103. static bool subjRequiresPage( PgHdr pPg )
  1104. {
  1105. u32 pgno = pPg.pgno;
  1106. Pager pPager = pPg.pPager;
  1107. int i;
  1108. for ( i = 0; i < pPager.nSavepoint; i++ )
  1109. {
  1110. PagerSavepoint p = pPager.aSavepoint[i];
  1111. if ( p.nOrig >= pgno && 0 == sqlite3BitvecTest( p.pInSavepoint, pgno ) )
  1112. {
  1113. return true;
  1114. }
  1115. }
  1116. return false;
  1117. }
  1118. /*
  1119. ** Return true if the page is already in the journal file.
  1120. */
  1121. static bool pageInJournal( PgHdr pPg )
  1122. {
  1123. return sqlite3BitvecTest( pPg.pPager.pInJournal, pPg.pgno ) != 0;
  1124. }
  1125. /*
  1126. ** Read a 32-bit integer from the given file descriptor. Store the integer
  1127. ** that is read in pRes. Return SQLITE_OK if everything worked, or an
  1128. ** error code is something goes wrong.
  1129. **
  1130. ** All values are stored on disk as big-endian.
  1131. */
  1132. static int read32bits( sqlite3_file fd, int offset, ref int pRes )
  1133. {
  1134. u32 u32_pRes = 0;
  1135. int rc = read32bits( fd, offset, ref u32_pRes );
  1136. pRes = (int)u32_pRes;
  1137. return rc;
  1138. }
  1139. static int read32bits( sqlite3_file fd, i64 offset, ref u32 pRes )
  1140. {
  1141. int rc = read32bits( fd, (int)offset, ref pRes );
  1142. return rc;
  1143. }
  1144. static int read32bits( sqlite3_file fd, int offset, ref u32 pRes )
  1145. {
  1146. byte[] ac = new byte[4];
  1147. int rc = sqlite3OsRead( fd, ac, ac.Length, offset );
  1148. if ( rc == SQLITE_OK )
  1149. {
  1150. pRes = sqlite3Get4byte( ac );
  1151. }
  1152. else
  1153. pRes = 0;
  1154. return rc;
  1155. }
  1156. /*
  1157. ** Write a 32-bit integer into a string buffer in big-endian byte order.
  1158. */
  1159. //#define put32bits(A,B) sqlite3sqlite3Put4byte((u8*)A,B)
  1160. static void put32bits( string ac, int offset, int val )
  1161. {
  1162. byte[] A = new byte[4];
  1163. A[0] = (byte)ac[offset + 0];
  1164. A[1] = (byte)ac[offset + 1];
  1165. A[2] = (byte)ac[offset + 2];
  1166. A[3] = (byte)ac[offset + 3];
  1167. sqlite3Put4byte( A, 0, val );
  1168. }
  1169. static void put32bits( byte[] ac, int offset, int val )
  1170. {
  1171. sqlite3Put4byte( ac, offset, (u32)val );
  1172. }
  1173. static void put32bits( byte[] ac, u32 val )
  1174. {
  1175. sqlite3Put4byte( ac, 0U, val );
  1176. }
  1177. static void put32bits( byte[] ac, int offset, u32 val )
  1178. {
  1179. sqlite3Put4byte( ac, offset, val );
  1180. }
  1181. /*
  1182. ** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK
  1183. ** on success or an error code is something goes wrong.
  1184. */
  1185. static int write32bits( sqlite3_file fd, i64 offset, u32 val )
  1186. {
  1187. byte[] ac = new byte[4];
  1188. put32bits( ac, val );
  1189. return sqlite3OsWrite( fd, ac, 4, offset );
  1190. }
  1191. /*
  1192. ** Unlock the database file to level eLock, which must be either NO_LOCK
  1193. ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
  1194. ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
  1195. **
  1196. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  1197. ** called, do not modify it. See the comment above the #define of
  1198. ** UNKNOWN_LOCK for an explanation of this.
  1199. */
  1200. static int pagerUnlockDb( Pager pPager, int eLock )
  1201. {
  1202. int rc = SQLITE_OK;
  1203. Debug.Assert( !pPager.exclusiveMode || pPager.eLock == eLock );
  1204. Debug.Assert( eLock == NO_LOCK || eLock == SHARED_LOCK );
  1205. Debug.Assert( eLock != NO_LOCK || pagerUseWal( pPager ) == false );
  1206. if ( isOpen( pPager.fd ) )
  1207. {
  1208. Debug.Assert( pPager.eLock >= eLock );
  1209. rc = sqlite3OsUnlock( pPager.fd, eLock );
  1210. if ( pPager.eLock != UNKNOWN_LOCK )
  1211. {
  1212. pPager.eLock = (u8)eLock;
  1213. }
  1214. IOTRACE( "UNLOCK %p %d\n", pPager, eLock );
  1215. }
  1216. return rc;
  1217. }
  1218. /*
  1219. ** Lock the database file to level eLock, which must be either SHARED_LOCK,
  1220. ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
  1221. ** Pager.eLock variable to the new locking state.
  1222. **
  1223. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  1224. ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
  1225. ** See the comment above the #define of UNKNOWN_LOCK for an explanation
  1226. ** of this.
  1227. */
  1228. static int pagerLockDb( Pager pPager, int eLock )
  1229. {
  1230. int rc = SQLITE_OK;
  1231. Debug.Assert( eLock == SHARED_LOCK || eLock == RESERVED_LOCK || eLock == EXCLUSIVE_LOCK );
  1232. if ( pPager.eLock < eLock || pPager.eLock == UNKNOWN_LOCK )
  1233. {
  1234. rc = sqlite3OsLock( pPager.fd, eLock );
  1235. if ( rc == SQLITE_OK && ( pPager.eLock != UNKNOWN_LOCK || eLock == EXCLUSIVE_LOCK ) )
  1236. {
  1237. pPager.eLock = (u8)eLock;
  1238. IOTRACE( "LOCK %p %d\n", pPager, eLock );
  1239. }
  1240. }
  1241. return rc;
  1242. }
  1243. /*
  1244. ** This function determines whether or not the atomic-write optimization
  1245. ** can be used with this pager. The optimization can be used if:
  1246. **
  1247. ** (a) the value returned by OsDeviceCharacteristics() indicates that
  1248. ** a database page may be written atomically, and
  1249. ** (b) the value returned by OsSectorSize() is less than or equal
  1250. ** to the page size.
  1251. **
  1252. ** The optimization is also always enabled for temporary files. It is
  1253. ** an error to call this function if pPager is opened on an in-memory
  1254. ** database.
  1255. **
  1256. ** If the optimization cannot be used, 0 is returned. If it can be used,
  1257. ** then the value returned is the size of the journal file when it
  1258. ** contains rollback data for exactly one page.
  1259. */
  1260. #if SQLITE_ENABLE_ATOMIC_WRITE
  1261. static int jrnlBufferSize(Pager *pPager){
  1262. Debug.Assert( 0==MEMDB );
  1263. if( !pPager.tempFile ){
  1264. int dc; /* Device characteristics */
  1265. int nSector; /* Sector size */
  1266. int szPage; /* Page size */
  1267. Debug.Assert( isOpen(pPager.fd) );
  1268. dc = sqlite3OsDeviceCharacteristics(pPager.fd);
  1269. nSector = pPager.sectorSize;
  1270. szPage = pPager.pageSize;
  1271. Debug.Assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  1272. Debug.Assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  1273. if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
  1274. return 0;
  1275. }
  1276. }
  1277. return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
  1278. }
  1279. #endif
  1280. /*
  1281. ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
  1282. ** on the cache using a hash function. This is used for testing
  1283. ** and debugging only.
  1284. */
  1285. #if SQLITE_CHECK_PAGES
  1286. /*
  1287. ** Return a 32-bit hash of the page data for pPage.
  1288. */
  1289. static u32 pager_datahash(int nByte, unsigned char pData){
  1290. u32 hash = 0;
  1291. int i;
  1292. for(i=0; i<nByte; i++){
  1293. hash = (hash*1039) + pData[i];
  1294. }
  1295. return hash;
  1296. }
  1297. static void pager_pagehash(PgHdr pPage){
  1298. return pager_datahash(pPage.pPager.pageSize, (unsigned char *)pPage.pData);
  1299. }
  1300. static u32 pager_set_pagehash(PgHdr pPage){
  1301. pPage.pageHash = pager_pagehash(pPage);
  1302. }
  1303. /*
  1304. ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
  1305. ** is defined, and NDEBUG is not defined, an Debug.Assert() statement checks
  1306. ** that the page is either dirty or still matches the calculated page-hash.
  1307. */
  1308. //#define CHECK_PAGE(x) checkPage(x)
  1309. static void checkPage(PgHdr pPg){
  1310. Pager pPager = pPg.pPager;
  1311. assert( pPager->eState!=PAGER_ERROR );
  1312. assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
  1313. }
  1314. #else
  1315. //#define pager_datahash(X,Y) 0
  1316. static int pager_datahash( int X, byte[] Y )
  1317. {
  1318. return 0;
  1319. }
  1320. //#define pager_pagehash(X) 0
  1321. static int pager_pagehash( PgHdr X )
  1322. {
  1323. return 0;
  1324. }
  1325. //#define pager_set_pagehash(X)
  1326. static void pager_set_pagehash( PgHdr X )
  1327. {
  1328. }
  1329. //#define CHECK_PAGE(x)
  1330. #endif //* SQLITE_CHECK_PAGES */
  1331. /*
  1332. ** When this is called the journal file for pager pPager must be open.
  1333. ** This function attempts to read a master journal file name from the
  1334. ** end of the file and, if successful, copies it into memory supplied
  1335. ** by the caller. See comments above writeMasterJournal() for the format
  1336. ** used to store a master journal file name at the end of a journal file.
  1337. **
  1338. ** zMaster must point to a buffer of at least nMaster bytes allocated by
  1339. ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
  1340. ** enough space to write the master journal name). If the master journal
  1341. ** name in the journal is longer than nMaster bytes (including a
  1342. ** nul-terminator), then this is handled as if no master journal name
  1343. ** were present in the journal.
  1344. **
  1345. ** If a master journal file name is present at the end of the journal
  1346. ** file, then it is copied into the buffer pointed to by zMaster. A
  1347. ** nul-terminator byte is appended to the buffer following the master
  1348. ** journal file name.
  1349. **
  1350. ** If it is determined that no master journal file name is present
  1351. ** zMaster[0] is set to 0 and SQLITE_OK returned.
  1352. **
  1353. ** If an error occurs while reading from the journal file, an SQLite
  1354. ** error code is returned.
  1355. */
  1356. static int readMasterJournal( sqlite3_file pJrnl, byte[] zMaster, u32 nMaster )
  1357. {
  1358. int rc; /* Return code */
  1359. int len = 0; /* Length in bytes of master journal name */
  1360. i64 szJ = 0; /* Total size in bytes of journal file pJrnl */
  1361. u32 cksum = 0; /* MJ checksum value read from journal */
  1362. int u; /* Unsigned loop counter */
  1363. byte[] aMagic = new byte[8]; /* A buffer to hold the magic header */
  1364. zMaster[0] = 0;
  1365. if ( SQLITE_OK != ( rc = sqlite3OsFileSize( pJrnl, ref szJ ) )
  1366. || szJ < 16
  1367. || SQLITE_OK != ( rc = read32bits( pJrnl, (int)( szJ - 16 ), ref len ) )
  1368. || len >= nMaster
  1369. || SQLITE_OK != ( rc = read32bits( pJrnl, szJ - 12, ref cksum ) )
  1370. || SQLITE_OK != ( rc = sqlite3OsRead( pJrnl, aMagic, 8, szJ - 8 ) )
  1371. || memcmp( aMagic, aJournalMagic, 8 ) != 0
  1372. || SQLITE_OK != ( rc = sqlite3OsRead( pJrnl, zMaster, len, (long)( szJ - 16 - len ) ) )
  1373. )
  1374. {
  1375. return rc;
  1376. }
  1377. /* See if the checksum matches the master journal name */
  1378. for ( u = 0; u < len; u++ )
  1379. {
  1380. cksum -= zMaster[u];
  1381. }
  1382. if ( cksum != 0 )
  1383. {
  1384. /* If the checksum doesn't add up, then one or more of the disk sectors
  1385. ** containing the master journal filename is corrupted. This means
  1386. ** definitely roll back, so just return SQLITE_OK and report a (nul)
  1387. ** master-journal filename.
  1388. */
  1389. len = 0;
  1390. }
  1391. if ( len == 0 )
  1392. zMaster[0] = 0;
  1393. return SQLITE_OK;
  1394. }
  1395. /*
  1396. ** Return the offset of the sector boundary at or immediately
  1397. ** following the value in pPager.journalOff, assuming a sector
  1398. ** size of pPager.sectorSize bytes.
  1399. **
  1400. ** i.e for a sector size of 512:
  1401. **
  1402. ** Pager.journalOff Return value
  1403. ** ---------------------------------------
  1404. ** 0 0
  1405. ** 512 512
  1406. ** 100 512
  1407. ** 2000 2048
  1408. **
  1409. */
  1410. static i64 journalHdrOffset( Pager pPager )
  1411. {
  1412. i64 offset = 0;
  1413. i64 c = pPager.journalOff;
  1414. if ( c != 0 )
  1415. {
  1416. offset = (int)( ( ( c - 1 ) / pPager.sectorSize + 1 ) * pPager.sectorSize );//offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
  1417. }
  1418. Debug.Assert( offset % pPager.sectorSize == 0 ); //Debug.Assert(offset % JOURNAL_HDR_SZ(pPager) == 0);
  1419. Debug.Assert( offset >= c );
  1420. Debug.Assert( ( offset - c ) < pPager.sectorSize );//Debug.Assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
  1421. return offset;
  1422. }
  1423. static void seekJournalHdr( Pager pPager )
  1424. {
  1425. pPager.journalOff = journalHdrOffset( pPager );
  1426. }
  1427. /*
  1428. ** The journal file must be open when this function is called.
  1429. **
  1430. ** This function is a no-op if the journal file has not been written to
  1431. ** within the current transaction (i.e. if Pager.journalOff==0).
  1432. **
  1433. ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
  1434. ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
  1435. ** zero the 28-byte header at the start of the journal file. In either case,
  1436. ** if the pager is not in no-sync mode, sync the journal file immediately
  1437. ** after writing or truncating it.
  1438. **
  1439. ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
  1440. ** following the truncation or zeroing described above the size of the
  1441. ** journal file in bytes is larger than this value, then truncate the
  1442. ** journal file to Pager.journalSizeLimit bytes. The journal file does
  1443. ** not need to be synced following this operation.
  1444. **
  1445. ** If an IO error occurs, abandon processing and return the IO error code.
  1446. ** Otherwise, return SQLITE_OK.
  1447. */
  1448. static int zeroJournalHdr( Pager pPager, int doTruncate )
  1449. {
  1450. int rc = SQLITE_OK; /* Return code */
  1451. Debug.Assert( isOpen( pPager.jfd ) );
  1452. if ( pPager.journalOff != 0 )
  1453. {
  1454. i64 iLimit = pPager.journalSizeLimit; /* Local cache of jsl */
  1455. IOTRACE( "JZEROHDR %p\n", pPager );
  1456. if ( doTruncate != 0 || iLimit == 0 )
  1457. {
  1458. rc = sqlite3OsTruncate( pPager.jfd, 0 );
  1459. }
  1460. else
  1461. {
  1462. byte[] zeroHdr = new byte[28];// = {0};
  1463. rc = sqlite3OsWrite( pPager.jfd, zeroHdr, zeroHdr.Length, 0 );
  1464. }
  1465. if ( rc == SQLITE_OK && !pPager.noSync )
  1466. {
  1467. rc = sqlite3OsSync( pPager.jfd, SQLITE_SYNC_DATAONLY | pPager.syncFlags );
  1468. }
  1469. /* At this point the transaction is committed but the write lock
  1470. ** is still held on the file. If there is a size limit configured for
  1471. ** the persistent journal and the journal file currently consumes more
  1472. ** space than that limit allows for, truncate it now. There is no need
  1473. ** to sync the file following this operation.
  1474. */
  1475. if ( rc == SQLITE_OK && iLimit > 0 )
  1476. {
  1477. i64 sz = 0;
  1478. rc = sqlite3OsFileSize( pPager.jfd, ref sz );
  1479. if ( rc == SQLITE_OK && sz > iLimit )
  1480. {
  1481. rc = sqlite3OsTruncate( pPager.jfd, iLimit );
  1482. }
  1483. }
  1484. }
  1485. return rc;
  1486. }
  1487. /*
  1488. ** The journal file must be open when this routine is called. A journal
  1489. ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
  1490. ** current location.
  1491. **
  1492. ** The format for the journal header is as follows:
  1493. ** - 8 bytes: Magic identifying journal format.
  1494. ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
  1495. ** - 4 bytes: Random number used for page hash.
  1496. ** - 4 bytes: Initial database page count.
  1497. ** - 4 bytes: Sector size used by the process that wrote this journal.
  1498. ** - 4 bytes: Database page size.
  1499. **
  1500. ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
  1501. */
  1502. static int writeJournalHdr( Pager pPager )
  1503. {
  1504. int rc = SQLITE_OK; /* Return code */
  1505. byte[] zHeader = pPager.pTmpSpace; /* Temporary space used to build header */
  1506. u32 nHeader = (u32)pPager.pageSize; /* Size of buffer pointed to by zHeader */
  1507. u32 nWrite; /* Bytes of header sector written */
  1508. int ii; /* Loop counter */
  1509. Debug.Assert( isOpen( pPager.jfd ) ); /* Journal file must be open. */
  1510. if ( nHeader > JOURNAL_HDR_SZ( pPager ) )
  1511. {
  1512. nHeader = JOURNAL_HDR_SZ( pPager );
  1513. }
  1514. /* If there are active savepoints and any of them were created
  1515. ** since the most recent journal header was written, update the
  1516. ** PagerSavepoint.iHdrOffset fields now.
  1517. */
  1518. for ( ii = 0; ii < pPager.nSavepoint; ii++ )
  1519. {
  1520. if ( pPager.aSavepoint[ii].iHdrOffset == 0 )
  1521. {
  1522. pPager.aSavepoint[ii].iHdrOffset = pPager.journalOff;
  1523. }
  1524. }
  1525. pPager.journalHdr = pPager.journalOff = journalHdrOffset( pPager );
  1526. /*
  1527. ** Write the nRec Field - the number of page records that follow this
  1528. ** journal header. Normally, zero is written to this value at this time.
  1529. ** After the records are added to the journal (and the journal synced,
  1530. ** if in full-sync mode), the zero is overwritten with the true number
  1531. ** of records (see syncJournal()).
  1532. **
  1533. ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
  1534. ** reading the journal this value tells SQLite to assume that the
  1535. ** rest of the journal file contains valid page records. This assumption
  1536. ** is dangerous, as if a failure occurred whilst writing to the journal
  1537. ** file it may contain some garbage data. There are two scenarios
  1538. ** where this risk can be ignored:
  1539. **
  1540. ** * When the pager is in no-sync mode. Corruption can follow a
  1541. ** power failure in this case anyway.
  1542. **
  1543. ** * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
  1544. ** that garbage data is never appended to the journal file.
  1545. */
  1546. Debug.Assert( isOpen( pPager.fd ) || pPager.noSync );
  1547. if ( pPager.noSync || ( pPager.journalMode == PAGER_JOURNALMODE_MEMORY )
  1548. || ( sqlite3OsDeviceCharacteristics( pPager.fd ) & SQLITE_IOCAP_SAFE_APPEND ) != 0
  1549. )
  1550. {
  1551. aJournalMagic.CopyTo( zHeader, 0 );// memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  1552. put32bits( zHeader, aJournalMagic.Length, 0xffffffff );
  1553. }
  1554. else
  1555. {
  1556. Array.Clear( zHeader, 0, aJournalMagic.Length + 4 );//memset(zHeader, 0, sizeof(aJournalMagic)+4);
  1557. }
  1558. /* The random check-hash initialiser */
  1559. i64 i64Temp = 0;
  1560. sqlite3_randomness( sizeof( i64 ), ref i64Temp );
  1561. pPager.cksumInit = (u32)i64Temp;
  1562. put32bits( zHeader, aJournalMagic.Length + 4, pPager.cksumInit );
  1563. /* The initial database size */
  1564. put32bits( zHeader, aJournalMagic.Length + 8, pPager.dbOrigSize );
  1565. /* The assumed sector size for this process */
  1566. put32bits( zHeader, aJournalMagic.Length + 12, pPager.sectorSize );
  1567. /* The page size */
  1568. put32bits( zHeader, aJournalMagic.Length + 16, (u32)pPager.pageSize );
  1569. /* Initializing the tail of the buffer is not necessary. Everything
  1570. ** works find if the following memset() is omitted. But initializing
  1571. ** the memory prevents valgrind from complaining, so we are willing to
  1572. ** take the performance hit.
  1573. */
  1574. // memset(&zHeader[sizeof(aJournalMagic)+20], 0,
  1575. // nHeader-(sizeof(aJournalMagic)+20));
  1576. Array.Clear( zHeader, aJournalMagic.Length + 20, (int)nHeader - ( aJournalMagic.Length + 20 ) );
  1577. /* In theory, it is only necessary to write the 28 bytes that the
  1578. ** journal header consumes to the journal file here. Then increment the
  1579. ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
  1580. ** record is written to the following sector (leaving a gap in the file
  1581. ** that will be implicitly filled in by the OS).
  1582. **
  1583. ** However it has been discovered that on some systems this pattern can
  1584. ** be significantly slower than contiguously writing data to the file,
  1585. ** even if that means explicitly writing data to the block of
  1586. ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
  1587. ** is done.
  1588. **
  1589. ** The loop is required here in case the sector-size is larger than the
  1590. ** database page size. Since the zHeader buffer is only Pager.pageSize
  1591. ** bytes in size, more than one call to sqlite3OsWrite() may be required
  1592. ** to populate the entire journal header sector.
  1593. */
  1594. for ( nWrite = 0; rc == SQLITE_OK && nWrite < JOURNAL_HDR_SZ( pPager ); nWrite += nHeader )
  1595. {
  1596. IOTRACE( "JHDR %p %lld %d\n", pPager, pPager.journalHdr, nHeader );
  1597. rc = sqlite3OsWrite( pPager.jfd, zHeader, (int)nHeader, pPager.journalOff );
  1598. Debug.Assert( pPager.journalHdr <= pPager.journalOff );
  1599. pPager.journalOff += (int)nHeader;
  1600. }
  1601. return rc;
  1602. }
  1603. /*
  1604. ** The journal file must be open when this is called. A journal header file
  1605. ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
  1606. ** file. The current location in the journal file is given by
  1607. ** pPager.journalOff. See comments above function writeJournalHdr() for
  1608. ** a description of the journal header format.
  1609. **
  1610. ** If the header is read successfully, *pNRec is set to the number of
  1611. ** page records following this header and *pDbSize is set to the size of the
  1612. ** database before the transaction began, in pages. Also, pPager.cksumInit
  1613. ** is set to the value read from the journal header. SQLITE_OK is returned
  1614. ** in this case.
  1615. **
  1616. ** If the journal header file appears to be corrupted, SQLITE_DONE is
  1617. ** returned and *pNRec and *PDbSize are undefined. If JOURNAL_HDR_SZ bytes
  1618. ** cannot be read from the journal file an error code is returned.
  1619. */
  1620. static int readJournalHdr(
  1621. Pager pPager, /* Pager object */
  1622. int isHot,
  1623. i64 journalSize, /* Size of the open journal file in bytes */
  1624. out u32 pNRec, /* OUT: Value read from the nRec field */
  1625. out u32 pDbSize /* OUT: Value of original database size field */
  1626. )
  1627. {
  1628. int rc; /* Return code */
  1629. byte[] aMagic = new byte[8]; /* A buffer to hold the magic header */
  1630. i64 iHdrOff; /* Offset of journal header being read */
  1631. Debug.Assert( isOpen( pPager.jfd ) ); /* Journal file must be open. */
  1632. pNRec = 0;
  1633. pDbSize = 0;
  1634. /* Advance Pager.journalOff to the start of the next sector. If the
  1635. ** journal file is too small for there to be a header stored at this
  1636. ** point, return SQLITE_DONE.
  1637. */
  1638. pPager.journalOff = journalHdrOffset( pPager );
  1639. if ( pPager.journalOff + JOURNAL_HDR_SZ( pPager ) > journalSize )
  1640. {
  1641. return SQLITE_DONE;
  1642. }
  1643. iHdrOff = pPager.journalOff;
  1644. /* Read in the first 8 bytes of the journal header. If they do not match
  1645. ** the magic string found at the start of each journal header, return
  1646. ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
  1647. ** proceed.
  1648. */
  1649. if ( isHot != 0 || iHdrOff != pPager.journalHdr )
  1650. {
  1651. rc = sqlite3OsRead( pPager.jfd, aMagic, aMagic.Length, iHdrOff );
  1652. if ( rc != 0 )
  1653. {
  1654. return rc;
  1655. }
  1656. if ( memcmp( aMagic, aJournalMagic, aMagic.Length ) != 0 )
  1657. {
  1658. return SQLITE_DONE;
  1659. }
  1660. }
  1661. /* Read the first three 32-bit fields of the journal header: The nRec
  1662. ** field, the checksum-initializer and the database size at the start
  1663. ** of the transaction. Return an error code if anything goes wrong.
  1664. */
  1665. if ( SQLITE_OK != ( rc = read32bits( pPager.jfd, iHdrOff + 8, ref pNRec ) )
  1666. || SQLITE_OK != ( rc = read32bits( pPager.jfd, iHdrOff + 12, ref pPager.cksumInit ) )
  1667. || SQLITE_OK != ( rc = read32bits( pPager.jfd, iHdrOff + 16, ref pDbSize ) )
  1668. )
  1669. {
  1670. return rc;
  1671. }
  1672. if ( pPager.journalOff == 0 )
  1673. {
  1674. u32 iPageSize = 0; /* Page-size field of journal header */
  1675. u32 iSectorSize = 0; /* Sector-size field of journal header */
  1676. /* Read the page-size and sector-size journal header fields. */
  1677. if ( SQLITE_OK != ( rc = read32bits( pPager.jfd, iHdrOff + 20, ref iSectorSize ) )
  1678. || SQLITE_OK != ( rc = read32bits( pPager.jfd, iHdrOff + 24, ref iPageSize ) )
  1679. )
  1680. {
  1681. return rc;
  1682. }
  1683. /* Versions of SQLite prior to 3.5.8 set the page-size field of the
  1684. ** journal header to zero. In this case, assume that the Pager.pageSize
  1685. ** variable is already set to the correct page size.
  1686. */
  1687. if ( iPageSize == 0 )
  1688. {
  1689. iPageSize = (u32)pPager.pageSize;
  1690. }
  1691. /* Check that the values read from the page-size and sector-size fields
  1692. ** are within range. To be 'in range', both values need to be a power
  1693. ** of two greater than or equal to 512 or 32, and not greater than their
  1694. ** respective compile time maximum limits.
  1695. */
  1696. if ( iPageSize < 512 || iSectorSize < 32
  1697. || iPageSize > SQLITE_MAX_PAGE_SIZE || iSectorSize > MAX_SECTOR_SIZE
  1698. || ( ( iPageSize - 1 ) & iPageSize ) != 0 || ( ( iSectorSize - 1 ) & iSectorSize ) != 0
  1699. )
  1700. {
  1701. /* If the either the page-size or sector-size in the journal-header is
  1702. ** invalid, then the process that wrote the journal-header must have
  1703. ** crashed before the header was synced. In this case stop reading
  1704. ** the journal file here.
  1705. */
  1706. return SQLITE_DONE;
  1707. }
  1708. /* Update the page-size to match the value read from the journal.
  1709. ** Use a testcase() macro to make sure that malloc failure within
  1710. ** PagerSetPagesize() is tested.
  1711. */
  1712. rc = sqlite3PagerSetPagesize( pPager, ref iPageSize, -1 );
  1713. testcase( rc != SQLITE_OK );
  1714. /* Update the assumed sector-size to match the value used by
  1715. ** the process that created this journal. If this journal was
  1716. ** created by a process other than this one, then this routine
  1717. ** is being called from within pager_playback(). The local value
  1718. ** of Pager.sectorSize is restored at the end of that routine.
  1719. */
  1720. pPager.sectorSize = iSectorSize;
  1721. }
  1722. pPager.journalOff += (int)JOURNAL_HDR_SZ( pPager );
  1723. return rc;
  1724. }
  1725. /*
  1726. ** Write the supplied master journal name into the journal file for pager
  1727. ** pPager at the current location. The master journal name must be the last
  1728. ** thing written to a journal file. If the pager is in full-sync mode, the
  1729. ** journal file descriptor is advanced to the next sector boundary before
  1730. ** anything is written. The format is:
  1731. **
  1732. ** + 4 bytes: PAGER_MJ_PGNO.
  1733. ** + N bytes: Master journal filename in utf-8.
  1734. ** + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
  1735. ** + 4 bytes: Master journal name checksum.
  1736. ** + 8 bytes: aJournalMagic[].
  1737. **
  1738. ** The master journal page checksum is the sum of the bytes in the master
  1739. ** journal name, where each byte is interpreted as a signed 8-bit integer.
  1740. **
  1741. ** If zMaster is a NULL pointer (occurs for a single database transaction),
  1742. ** this call is a no-op.
  1743. */
  1744. static int writeMasterJournal( Pager pPager, string zMaster )
  1745. {
  1746. int rc; /* Return code */
  1747. int nMaster; /* Length of string zMaster */
  1748. i64 iHdrOff; /* Offset of header in journal file */
  1749. i64 jrnlSize = 0; /* Size of journal file on disk */
  1750. u32 cksum = 0; /* Checksum of string zMaster */
  1751. Debug.Assert( pPager.setMaster == 0 );
  1752. Debug.Assert( !pagerUseWal( pPager ) );
  1753. if ( null == zMaster
  1754. || pPager.journalMode == PAGER_JOURNALMODE_MEMORY
  1755. || pPager.journalMode == PAGER_JOURNALMODE_OFF
  1756. )
  1757. {
  1758. return SQLITE_OK;
  1759. }
  1760. pPager.setMaster = 1;
  1761. Debug.Assert( isOpen( pPager.jfd ) );
  1762. Debug.Assert( pPager.journalHdr <= pPager.journalOff );
  1763. /* Calculate the length in bytes and the checksum of zMaster */
  1764. for ( nMaster = 0; nMaster < zMaster.Length && zMaster[nMaster] != 0; nMaster++ )
  1765. {
  1766. cksum += zMaster[nMaster];
  1767. }
  1768. /* If in full-sync mode, advance to the next disk sector before writing
  1769. ** the master journal name. This is in case the previous page written to
  1770. ** the journal has already been synced.
  1771. */
  1772. if ( pPager.fullSync )
  1773. {
  1774. pPager.journalOff = journalHdrOffset( pPager );
  1775. }
  1776. iHdrOff = pPager.journalOff;
  1777. /* Write the master journal data to the end of the journal file. If
  1778. ** an error occurs, return the error code to the caller.
  1779. */
  1780. if ( ( 0 != ( rc = write32bits( pPager.jfd, iHdrOff, (u32)PAGER_MJ_PGNO( pPager ) ) ) )
  1781. || ( 0 != ( rc = sqlite3OsWrite( pPager.jfd, Encoding.UTF8.GetBytes( zMaster ), nMaster, iHdrOff + 4 ) ) )
  1782. || ( 0 != ( rc = write32bits( pPager.jfd, iHdrOff + 4 + nMaster, (u32)nMaster ) ) )
  1783. || ( 0 != ( rc = write32bits( pPager.jfd, iHdrOff + 4 + nMaster + 4, cksum ) ) )
  1784. || ( 0 != ( rc = sqlite3OsWrite( pPager.jfd, aJournalMagic, 8, iHdrOff + 4 + nMaster + 8 ) ) )
  1785. )
  1786. {
  1787. return rc;
  1788. }
  1789. pPager.journalOff += ( nMaster + 20 );
  1790. /* If the pager is in peristent-journal mode, then the physical
  1791. ** journal-file may extend past the end of the master-journal name
  1792. ** and 8 bytes of magic data just written to the file. This is
  1793. ** dangerous because the code to rollback a hot-journal file
  1794. ** will not be able to find the master-journal name to determine
  1795. ** whether or not the journal is hot.
  1796. **
  1797. ** Easiest thing to do in this scenario is to truncate the journal
  1798. ** file to the required size.
  1799. */
  1800. if ( SQLITE_OK == ( rc = sqlite3OsFileSize( pPager.jfd, ref jrnlSize ) )
  1801. && jrnlSize > pPager.journalOff
  1802. )
  1803. {
  1804. rc = sqlite3OsTruncate( pPager.jfd, pPager.journalOff );
  1805. }
  1806. return rc;
  1807. }
  1808. /*
  1809. ** Find a page in the hash table given its page number. Return
  1810. ** a pointer to the page or NULL if the requested page is not
  1811. ** already in memory.
  1812. */
  1813. static PgHdr pager_lookup( Pager pPager, u32 pgno )
  1814. {
  1815. PgHdr p = null; /* Return value */
  1816. /* It is not possible for a call to PcacheFetch() with createFlag==0 to
  1817. ** fail, since no attempt to allocate dynamic memory will be made.
  1818. */
  1819. sqlite3PcacheFetch( pPager.pPCache, pgno, 0, ref p );
  1820. return p;
  1821. }
  1822. /*
  1823. ** Discard the entire contents of the in-memory page-cache.
  1824. */
  1825. static void pager_reset( Pager pPager )
  1826. {
  1827. sqlite3BackupRestart( pPager.pBackup );
  1828. sqlite3PcacheClear( pPager.pPCache );
  1829. }
  1830. /*
  1831. ** Free all structures in the Pager.aSavepoint[] array and set both
  1832. ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
  1833. ** if it is open and the pager is not in exclusive mode.
  1834. */
  1835. static void releaseAllSavepoints( Pager pPager )
  1836. {
  1837. int ii; /* Iterator for looping through Pager.aSavepoint */
  1838. for ( ii = 0; ii < pPager.nSavepoint; ii++ )
  1839. {
  1840. sqlite3BitvecDestroy( ref pPager.aSavepoint[ii].pInSavepoint );
  1841. }
  1842. if ( !pPager.exclusiveMode || sqlite3IsMemJournal( pPager.sjfd ) )
  1843. {
  1844. sqlite3OsClose( pPager.sjfd );
  1845. }
  1846. //sqlite3_free( ref pPager.aSavepoint );
  1847. pPager.aSavepoint = null;
  1848. pPager.nSavepoint = 0;
  1849. pPager.nSubRec = 0;
  1850. }
  1851. /*
  1852. ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
  1853. ** bitvecs of all open savepoints. Return SQLITE_OK if successful
  1854. ** or SQLITE_NOMEM if a malloc failure occurs.
  1855. */
  1856. static int addToSavepointBitvecs( Pager pPager, u32 pgno )
  1857. {
  1858. int ii; /* Loop counter */
  1859. int rc = SQLITE_OK; /* Result code */
  1860. for ( ii = 0; ii < pPager.nSavepoint; ii++ )
  1861. {
  1862. PagerSavepoint p = pPager.aSavepoint[ii];
  1863. if ( pgno <= p.nOrig )
  1864. {
  1865. rc |= sqlite3BitvecSet( p.pInSavepoint, pgno );
  1866. testcase( rc == SQLITE_NOMEM );
  1867. Debug.Assert( rc == SQLITE_OK || rc == SQLITE_NOMEM );
  1868. }
  1869. }
  1870. return rc;
  1871. }
  1872. /*
  1873. ** This function is a no-op if the pager is in exclusive mode and not
  1874. ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
  1875. ** state.
  1876. **
  1877. ** If the pager is not in exclusive-access mode, the database file is
  1878. ** completely unlocked. If the file is unlocked and the file-system does
  1879. ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
  1880. ** closed (if it is open).
  1881. **
  1882. ** If the pager is in ERROR state when this function is called, the
  1883. ** contents of the pager cache are discarded before switching back to
  1884. ** the OPEN state. Regardless of whether the pager is in exclusive-mode
  1885. ** or not, any journal file left in the file-system will be treated
  1886. ** as a hot-journal and rolled back the next time a read-transaction
  1887. ** is opened (by this or by any other connection).
  1888. */
  1889. static void pager_unlock( Pager pPager )
  1890. {
  1891. Debug.Assert( pPager.eState == PAGER_READER
  1892. || pPager.eState == PAGER_OPEN
  1893. || pPager.eState == PAGER_ERROR
  1894. );
  1895. sqlite3BitvecDestroy( ref pPager.pInJournal );
  1896. pPager.pInJournal = null;
  1897. releaseAllSavepoints( pPager );
  1898. if ( pagerUseWal( pPager ) )
  1899. {
  1900. Debug.Assert( !isOpen( pPager.jfd ) );
  1901. sqlite3WalEndReadTransaction( pPager.pWal );
  1902. pPager.eState = PAGER_OPEN;
  1903. }
  1904. else if ( !pPager.exclusiveMode )
  1905. {
  1906. int rc; /* Error code returned by pagerUnlockDb() */
  1907. int iDc = isOpen( pPager.fd ) ? sqlite3OsDeviceCharacteristics( pPager.fd ) : 0;
  1908. /* If the operating system support deletion of open files, then
  1909. ** close the journal file when dropping the database lock. Otherwise
  1910. ** another connection with journal_mode=delete might delete the file
  1911. ** out from under us.
  1912. */
  1913. Debug.Assert( ( PAGER_JOURNALMODE_MEMORY & 5 ) != 1 );
  1914. Debug.Assert( ( PAGER_JOURNALMODE_OFF & 5 ) != 1 );
  1915. Debug.Assert( ( PAGER_JOURNALMODE_WAL & 5 ) != 1 );
  1916. Debug.Assert( ( PAGER_JOURNALMODE_DELETE & 5 ) != 1 );
  1917. Debug.Assert( ( PAGER_JOURNALMODE_TRUNCATE & 5 ) == 1 );
  1918. Debug.Assert( ( PAGER_JOURNALMODE_PERSIST & 5 ) == 1 );
  1919. if ( 0 == ( iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN )
  1920. || 1 != ( pPager.journalMode & 5 )
  1921. )
  1922. {
  1923. sqlite3OsClose( pPager.jfd );
  1924. }
  1925. /* If the pager is in the ERROR state and the call to unlock the database
  1926. ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
  1927. ** above the #define for UNKNOWN_LOCK for an explanation of why this
  1928. ** is necessary.
  1929. */
  1930. rc = pagerUnlockDb( pPager, NO_LOCK );
  1931. if ( rc != SQLITE_OK && pPager.eState == PAGER_ERROR )
  1932. {
  1933. pPager.eLock = UNKNOWN_LOCK;
  1934. }
  1935. /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
  1936. ** without clearing the error code. This is intentional - the error
  1937. ** code is cleared and the cache reset in the block below.
  1938. */
  1939. Debug.Assert( pPager.errCode != 0 || pPager.eState != PAGER_ERROR );
  1940. pPager.changeCountDone = false;
  1941. pPager.eState = PAGER_OPEN;
  1942. }
  1943. /* If Pager.errCode is set, the contents of the pager cache cannot be
  1944. ** trusted. Now that there are no outstanding references to the pager,
  1945. ** it can safely move back to PAGER_OPEN state. This happens in both
  1946. ** normal and exclusive-locking mode.
  1947. */
  1948. if ( pPager.errCode != 0 )
  1949. {
  1950. Debug.Assert(
  1951. #if SQLITE_OMIT_MEMORYDB
  1952. 0==MEMDB
  1953. #else
  1954. 0 == pPager.memDb
  1955. #endif
  1956. );
  1957. pager_reset( pPager );
  1958. pPager.changeCountDone = pPager.tempFile;
  1959. pPager.eState = PAGER_OPEN;
  1960. pPager.errCode = SQLITE_OK;
  1961. }
  1962. pPager.journalOff = 0;
  1963. pPager.journalHdr = 0;
  1964. pPager.setMaster = 0;
  1965. }
  1966. /*
  1967. ** This function is called whenever an IOERR or FULL error that requires
  1968. ** the pager to transition into the ERROR state may ahve occurred.
  1969. ** The first argument is a pointer to the pager structure, the second
  1970. ** the error-code about to be returned by a pager API function. The
  1971. ** value returned is a copy of the second argument to this function.
  1972. **
  1973. ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
  1974. ** IOERR sub-codes, the pager enters the ERROR state and the error code
  1975. ** is stored in Pager.errCode. While the pager remains in the ERROR state,
  1976. ** all major API calls on the Pager will immediately return Pager.errCode.
  1977. **
  1978. ** The ERROR state indicates that the contents of the pager-cache
  1979. ** cannot be trusted. This state can be cleared by completely discarding
  1980. ** the contents of the pager-cache. If a transaction was active when
  1981. ** the persistent error occurred, then the rollback journal may need
  1982. ** to be replayed to restore the contents of the database file (as if
  1983. ** it were a hot-journal).
  1984. */
  1985. static int pager_error( Pager pPager, int rc )
  1986. {
  1987. int rc2 = rc & 0xff;
  1988. Debug.Assert( rc == SQLITE_OK ||
  1989. #if SQLITE_OMIT_MEMORYDB
  1990. 0==MEMDB
  1991. #else
  1992. 0 == pPager.memDb
  1993. #endif
  1994. );
  1995. Debug.Assert(
  1996. pPager.errCode == SQLITE_FULL ||
  1997. pPager.errCode == SQLITE_OK ||
  1998. ( pPager.errCode & 0xff ) == SQLITE_IOERR
  1999. );
  2000. if (
  2001. rc2 == SQLITE_FULL || rc2 == SQLITE_IOERR )
  2002. {
  2003. pPager.errCode = rc;
  2004. pPager.eState = PAGER_ERROR;
  2005. }
  2006. return rc;
  2007. }
  2008. /*
  2009. ** This routine ends a transaction. A transaction is usually ended by
  2010. ** either a COMMIT or a ROLLBACK operation. This routine may be called
  2011. ** after rollback of a hot-journal, or if an error occurs while opening
  2012. ** the journal file or writing the very first journal-header of a
  2013. ** database transaction.
  2014. **
  2015. ** This routine is never called in PAGER_ERROR state. If it is called
  2016. ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
  2017. ** exclusive than a RESERVED lock, it is a no-op.
  2018. **
  2019. ** Otherwise, any active savepoints are released.
  2020. **
  2021. ** If the journal file is open, then it is "finalized". Once a journal
  2022. ** file has been finalized it is not possible to use it to roll back a
  2023. ** transaction. Nor will it be considered to be a hot-journal by this
  2024. ** or any other database connection. Exactly how a journal is finalized
  2025. ** depends on whether or not the pager is running in exclusive mode and
  2026. ** the current journal-mode (Pager.journalMode value), as follows:
  2027. **
  2028. ** journalMode==MEMORY
  2029. ** Journal file descriptor is simply closed. This destroys an
  2030. ** in-memory journal.
  2031. **
  2032. ** journalMode==TRUNCATE
  2033. ** Journal file is truncated to zero bytes in size.
  2034. **
  2035. ** journalMode==PERSIST
  2036. ** The first 28 bytes of the journal file are zeroed. This invalidates
  2037. ** the first journal header in the file, and hence the entire journal
  2038. ** file. An invalid journal file cannot be rolled back.
  2039. **
  2040. ** journalMode==DELETE
  2041. ** The journal file is closed and deleted using sqlite3OsDelete().
  2042. **
  2043. ** If the pager is running in exclusive mode, this method of finalizing
  2044. ** the journal file is never used. Instead, if the journalMode is
  2045. ** DELETE and the pager is in exclusive mode, the method described under
  2046. ** journalMode==PERSIST is used instead.
  2047. **
  2048. ** After the journal is finalized, the pager moves to PAGER_READER state.
  2049. ** If running in non-exclusive rollback mode, the lock on the file is
  2050. ** downgraded to a SHARED_LOCK.
  2051. **
  2052. ** SQLITE_OK is returned if no error occurs. If an error occurs during
  2053. ** any of the IO operations to finalize the journal file or unlock the
  2054. ** database then the IO error code is returned to the user. If the
  2055. ** operation to finalize the journal file fails, then the code still
  2056. ** tries to unlock the database file if not in exclusive mode. If the
  2057. ** unlock operation fails as well, then the first error code related
  2058. ** to the first error encountered (the journal finalization one) is
  2059. ** returned.
  2060. */
  2061. static int pager_end_transaction( Pager pPager, int hasMaster )
  2062. {
  2063. int rc = SQLITE_OK; /* Error code from journal finalization operation */
  2064. int rc2 = SQLITE_OK; /* Error code from db file unlock operation */
  2065. /* Do nothing if the pager does not have an open write transaction
  2066. ** or at least a RESERVED lock. This function may be called when there
  2067. ** is no write-transaction active but a RESERVED or greater lock is
  2068. ** held under two circumstances:
  2069. **
  2070. ** 1. After a successful hot-journal rollback, it is called with
  2071. ** eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
  2072. **
  2073. ** 2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
  2074. ** lock switches back to locking_mode=normal and then executes a
  2075. ** read-transaction, this function is called with eState==PAGER_READER
  2076. ** and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
  2077. */
  2078. Debug.Assert( assert_pager_state( pPager ) );
  2079. Debug.Assert( pPager.eState != PAGER_ERROR );
  2080. if ( pPager.eState < PAGER_WRITER_LOCKED && pPager.eLock < RESERVED_LOCK )
  2081. {
  2082. return SQLITE_OK;
  2083. }
  2084. releaseAllSavepoints( pPager );
  2085. Debug.Assert( isOpen( pPager.jfd ) || pPager.pInJournal == null );
  2086. if ( isOpen( pPager.jfd ) )
  2087. {
  2088. Debug.Assert( !pagerUseWal( pPager ) );
  2089. /* Finalize the journal file. */
  2090. if ( sqlite3IsMemJournal( pPager.jfd ) )
  2091. {
  2092. Debug.Assert( pPager.journalMode == PAGER_JOURNALMODE_MEMORY );
  2093. sqlite3OsClose( pPager.jfd );
  2094. }
  2095. else if ( pPager.journalMode == PAGER_JOURNALMODE_TRUNCATE )
  2096. {
  2097. if ( pPager.journalOff == 0 )
  2098. {
  2099. rc = SQLITE_OK;
  2100. }
  2101. else
  2102. {
  2103. rc = sqlite3OsTruncate( pPager.jfd, 0 );
  2104. }
  2105. pPager.journalOff = 0;
  2106. }
  2107. else if ( pPager.journalMode == PAGER_JOURNALMODE_PERSIST
  2108. || ( pPager.exclusiveMode && pPager.journalMode != PAGER_JOURNALMODE_WAL )
  2109. )
  2110. {
  2111. rc = zeroJournalHdr( pPager, hasMaster );
  2112. pPager.journalOff = 0;
  2113. }
  2114. else
  2115. {
  2116. /* This branch may be executed with Pager.journalMode==MEMORY if
  2117. ** a hot-journal was just rolled back. In this case the journal
  2118. ** file should be closed and deleted. If this connection writes to
  2119. ** the database file, it will do so using an in-memory journal.
  2120. */
  2121. Debug.Assert( pPager.journalMode == PAGER_JOURNALMODE_DELETE
  2122. || pPager.journalMode == PAGER_JOURNALMODE_MEMORY
  2123. || pPager.journalMode == PAGER_JOURNALMODE_WAL
  2124. );
  2125. sqlite3OsClose( pPager.jfd );
  2126. if ( !pPager.tempFile )
  2127. {
  2128. rc = sqlite3OsDelete( pPager.pVfs, pPager.zJournal, 0 );
  2129. }
  2130. }
  2131. }
  2132. #if SQLITE_CHECK_PAGES
  2133. sqlite3PcacheIterateDirty(pPager.pPCache, pager_set_pagehash);
  2134. if( pPager.dbSize==0 && sqlite3PcacheRefCount(pPager.pPCache)>0 ){
  2135. PgHdr p = pager_lookup(pPager, 1);
  2136. if( p != null ){
  2137. p.pageHash = null;
  2138. sqlite3PagerUnref(p);
  2139. }
  2140. }
  2141. #endif
  2142. sqlite3BitvecDestroy( ref pPager.pInJournal );
  2143. pPager.pInJournal = null;
  2144. pPager.nRec = 0;
  2145. sqlite3PcacheCleanAll( pPager.pPCache );
  2146. sqlite3PcacheTruncate( pPager.pPCache, pPager.dbSize );
  2147. if ( pagerUseWal( pPager ) )
  2148. {
  2149. /* Drop the WAL write-lock, if any. Also, if the connection was in
  2150. ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
  2151. ** lock held on the database file.
  2152. */
  2153. rc2 = sqlite3WalEndWriteTransaction( pPager.pWal );
  2154. Debug.Assert( rc2 == SQLITE_OK );
  2155. }
  2156. if ( !pPager.exclusiveMode
  2157. && ( !pagerUseWal( pPager ) || sqlite3WalExclusiveMode( pPager.pWal, 0 ) )
  2158. )
  2159. {
  2160. rc2 = pagerUnlockDb( pPager, SHARED_LOCK );
  2161. pPager.changeCountDone = false;
  2162. }
  2163. pPager.eState = PAGER_READER;
  2164. pPager.setMaster = 0;
  2165. return ( rc == SQLITE_OK ? rc2 : rc );
  2166. }
  2167. /*
  2168. ** Execute a rollback if a transaction is active and unlock the
  2169. ** database file.
  2170. **
  2171. ** If the pager has already entered the ERROR state, do not attempt
  2172. ** the rollback at this time. Instead, pager_unlock() is called. The
  2173. ** call to pager_unlock() will discard all in-memory pages, unlock
  2174. ** the database file and move the pager back to OPEN state. If this
  2175. ** means that there is a hot-journal left in the file-system, the next
  2176. ** connection to obtain a shared lock on the pager (which may be this one)
  2177. ** will roll it back.
  2178. **
  2179. ** If the pager has not already entered the ERROR state, but an IO or
  2180. ** malloc error occurs during a rollback, then this will itself cause
  2181. ** the pager to enter the ERROR state. Which will be cleared by the
  2182. ** call to pager_unlock(), as described above.
  2183. */
  2184. static void pagerUnlockAndRollback( Pager pPager )
  2185. {
  2186. if ( pPager.eState != PAGER_ERROR && pPager.eState != PAGER_OPEN )
  2187. {
  2188. Debug.Assert( assert_pager_state( pPager ) );
  2189. if ( pPager.eState >= PAGER_WRITER_LOCKED )
  2190. {
  2191. sqlite3BeginBenignMalloc();
  2192. sqlite3PagerRollback( pPager );
  2193. sqlite3EndBenignMalloc();
  2194. }
  2195. else if ( !pPager.exclusiveMode )
  2196. {
  2197. Debug.Assert( pPager.eState == PAGER_READER );
  2198. pager_end_transaction( pPager, 0 );
  2199. }
  2200. }
  2201. pager_unlock( pPager );
  2202. }
  2203. /*
  2204. ** Parameter aData must point to a buffer of pPager.pageSize bytes
  2205. ** of data. Compute and return a checksum based ont the contents of the
  2206. ** page of data and the current value of pPager.cksumInit.
  2207. **
  2208. ** This is not a real checksum. It is really just the sum of the
  2209. ** random initial value (pPager.cksumInit) and every 200th byte
  2210. ** of the page data, starting with byte offset (pPager.pageSize%200).
  2211. ** Each byte is interpreted as an 8-bit unsigned integer.
  2212. **
  2213. ** Changing the formula used to compute this checksum results in an
  2214. ** incompatible journal file format.
  2215. **
  2216. ** If journal corruption occurs due to a power failure, the most likely
  2217. ** scenario is that one end or the other of the record will be changed.
  2218. ** It is much less likely that the two ends of the journal record will be
  2219. ** correct and the middle be corrupt. Thus, this "checksum" scheme,
  2220. ** though fast and simple, catches the mostly likely kind of corruption.
  2221. */
  2222. static u32 pager_cksum( Pager pPager, byte[] aData )
  2223. {
  2224. u32 cksum = pPager.cksumInit; /* Checksum value to return */
  2225. int i = pPager.pageSize - 200; /* Loop counter */
  2226. while ( i > 0 )
  2227. {
  2228. cksum += aData[i];
  2229. i -= 200;
  2230. }
  2231. return cksum;
  2232. }
  2233. /*
  2234. ** Report the current page size and number of reserved bytes back
  2235. ** to the codec.
  2236. */
  2237. #if SQLITE_HAS_CODEC
  2238. static void pagerReportSize( Pager pPager )
  2239. {
  2240. if ( pPager.xCodecSizeChng != null )
  2241. {
  2242. pPager.xCodecSizeChng( pPager.pCodec, pPager.pageSize,
  2243. pPager.nReserve );
  2244. }
  2245. }
  2246. #else
  2247. //# define pagerReportSize(X) /* No-op if we do not support a codec */
  2248. static void pagerReportSize(Pager X){}
  2249. #endif
  2250. /*
  2251. ** Read a single page from either the journal file (if isMainJrnl==1) or
  2252. ** from the sub-journal (if isMainJrnl==0) and playback that page.
  2253. ** The page begins at offset *pOffset into the file. The *pOffset
  2254. ** value is increased to the start of the next page in the journal.
  2255. **
  2256. ** The main rollback journal uses checksums - the statement journal does
  2257. ** not.
  2258. **
  2259. ** If the page number of the page record read from the (sub-)journal file
  2260. ** is greater than the current value of Pager.dbSize, then playback is
  2261. ** skipped and SQLITE_OK is returned.
  2262. **
  2263. ** If pDone is not NULL, then it is a record of pages that have already
  2264. ** been played back. If the page at *pOffset has already been played back
  2265. ** (if the corresponding pDone bit is set) then skip the playback.
  2266. ** Make sure the pDone bit corresponding to the *pOffset page is set
  2267. ** prior to returning.
  2268. **
  2269. ** If the page record is successfully read from the (sub-)journal file
  2270. ** and played back, then SQLITE_OK is returned. If an IO error occurs
  2271. ** while reading the record from the (sub-)journal file or while writing
  2272. ** to the database file, then the IO error code is returned. If data
  2273. ** is successfully read from the (sub-)journal file but appears to be
  2274. ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
  2275. ** two circumstances:
  2276. **
  2277. ** * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
  2278. ** * If the record is being rolled back from the main journal file
  2279. ** and the checksum field does not match the record content.
  2280. **
  2281. ** Neither of these two scenarios are possible during a savepoint rollback.
  2282. **
  2283. ** If this is a savepoint rollback, then memory may have to be dynamically
  2284. ** allocated by this function. If this is the case and an allocation fails,
  2285. ** SQLITE_NOMEM is returned.
  2286. */
  2287. static int pager_playback_one_page(
  2288. Pager pPager, /* The pager being played back */
  2289. ref i64 pOffset, /* Offset of record to playback */
  2290. Bitvec pDone, /* Bitvec of pages already played back */
  2291. int isMainJrnl, /* True for main rollback journal. False for Stmt jrnl */
  2292. int isSavepnt /* True for a savepoint rollback */
  2293. )
  2294. {
  2295. int rc;
  2296. PgHdr pPg; /* An existing page in the cache */
  2297. Pgno pgno = 0; /* The page number of a page in journal */
  2298. u32 cksum = 0; /* Checksum used for sanity checking */
  2299. byte[] aData; /* Temporary storage for the page */
  2300. sqlite3_file jfd; /* The file descriptor for the journal file */
  2301. bool isSynced; /* True if journal page is synced */
  2302. Debug.Assert( ( isMainJrnl & ~1 ) == 0 ); /* isMainJrnl is 0 or 1 */
  2303. Debug.Assert( ( isSavepnt & ~1 ) == 0 ); /* isSavepnt is 0 or 1 */
  2304. Debug.Assert( isMainJrnl != 0 || pDone != null ); /* pDone always used on sub-journals */
  2305. Debug.Assert( isSavepnt != 0 || pDone == null ); /* pDone never used on non-savepoint */
  2306. aData = pPager.pTmpSpace;
  2307. Debug.Assert( aData != null ); /* Temp storage must have already been allocated */
  2308. Debug.Assert( pagerUseWal( pPager ) == false || ( 0 == isMainJrnl && isSavepnt != 0 ) );
  2309. /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
  2310. ** or savepoint rollback done at the request of the caller) or this is
  2311. ** a hot-journal rollback. If it is a hot-journal rollback, the pager
  2312. ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
  2313. ** only reads from the main journal, not the sub-journal.
  2314. */
  2315. Debug.Assert( pPager.eState >= PAGER_WRITER_CACHEMOD
  2316. || ( pPager.eState == PAGER_OPEN && pPager.eLock == EXCLUSIVE_LOCK )
  2317. );
  2318. Debug.Assert( pPager.eState >= PAGER_WRITER_CACHEMOD || isMainJrnl != 0 );
  2319. /* Read the page number and page data from the journal or sub-journal
  2320. ** file. Return an error code to the caller if an IO error occurs.
  2321. */
  2322. jfd = isMainJrnl != 0 ? pPager.jfd : pPager.sjfd;
  2323. rc = read32bits( jfd, pOffset, ref pgno );
  2324. if ( rc != SQLITE_OK )
  2325. return rc;
  2326. rc = sqlite3OsRead( jfd, aData, pPager.pageSize, ( pOffset ) + 4 );
  2327. if ( rc != SQLITE_OK )
  2328. return rc;
  2329. pOffset += pPager.pageSize + 4 + isMainJrnl * 4;
  2330. /* Sanity checking on the page. This is more important that I originally
  2331. ** thought. If a power failure occurs while the journal is being written,
  2332. ** it could cause invalid data to be written into the journal. We need to
  2333. ** detect this invalid data (with high probability) and ignore it.
  2334. */
  2335. if ( pgno == 0 || pgno == PAGER_MJ_PGNO( pPager ) )
  2336. {
  2337. Debug.Assert( 0 == isSavepnt );
  2338. return SQLITE_DONE;
  2339. }
  2340. if ( pgno > pPager.dbSize || sqlite3BitvecTest( pDone, pgno ) != 0 )
  2341. {
  2342. return SQLITE_OK;
  2343. }
  2344. if ( isMainJrnl != 0 )
  2345. {
  2346. rc = read32bits( jfd, ( pOffset ) - 4, ref cksum );
  2347. if ( rc != 0 )
  2348. return rc;
  2349. if ( 0 == isSavepnt && pager_cksum( pPager, aData ) != cksum )
  2350. {
  2351. return SQLITE_DONE;
  2352. }
  2353. }
  2354. /* If this page has already been played by before during the current
  2355. ** rollback, then don't bother to play it back again.
  2356. */
  2357. if ( pDone != null && ( rc = sqlite3BitvecSet( pDone, pgno ) ) != SQLITE_OK )
  2358. {
  2359. return rc;
  2360. }
  2361. /* When playing back page 1, restore the nReserve setting
  2362. */
  2363. if ( pgno == 1 && pPager.nReserve != ( aData )[20] )
  2364. {
  2365. pPager.nReserve = ( aData )[20];
  2366. pagerReportSize( pPager );
  2367. }
  2368. /* If the pager is in CACHEMOD state, then there must be a copy of this
  2369. ** page in the pager cache. In this case just update the pager cache,
  2370. ** not the database file. The page is left marked dirty in this case.
  2371. **
  2372. ** An exception to the above rule: If the database is in no-sync mode
  2373. ** and a page is moved during an incremental vacuum then the page may
  2374. ** not be in the pager cache. Later: if a malloc() or IO error occurs
  2375. ** during a Movepage() call, then the page may not be in the cache
  2376. ** either. So the condition described in the above paragraph is not
  2377. ** assert()able.
  2378. **
  2379. ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
  2380. ** pager cache if it exists and the main file. The page is then marked
  2381. ** not dirty. Since this code is only executed in PAGER_OPEN state for
  2382. ** a hot-journal rollback, it is guaranteed that the page-cache is empty
  2383. ** if the pager is in OPEN state.
  2384. **
  2385. ** Ticket #1171: The statement journal might contain page content that is
  2386. ** different from the page content at the start of the transaction.
  2387. ** This occurs when a page is changed prior to the start of a statement
  2388. ** then changed again within the statement. When rolling back such a
  2389. ** statement we must not write to the original database unless we know
  2390. ** for certain that original page contents are synced into the main rollback
  2391. ** journal. Otherwise, a power loss might leave modified data in the
  2392. ** database file without an entry in the rollback journal that can
  2393. ** restore the database to its original form. Two conditions must be
  2394. ** met before writing to the database files. (1) the database must be
  2395. ** locked. (2) we know that the original page content is fully synced
  2396. ** in the main journal either because the page is not in cache or else
  2397. ** the page is marked as needSync==0.
  2398. **
  2399. ** 2008-04-14: When attempting to vacuum a corrupt database file, it
  2400. ** is possible to fail a statement on a database that does not yet exist.
  2401. ** Do not attempt to write if database file has never been opened.
  2402. */
  2403. if ( pagerUseWal( pPager ) )
  2404. {
  2405. pPg = null;
  2406. }
  2407. else
  2408. {
  2409. pPg = pager_lookup( pPager, pgno );
  2410. }
  2411. Debug.Assert( pPg != null ||
  2412. #if SQLITE_OMIT_MEMORYDB
  2413. 0==MEMDB
  2414. #else
  2415. pPager.memDb == 0
  2416. #endif
  2417. );
  2418. Debug.Assert( pPager.eState != PAGER_OPEN || pPg == null );
  2419. PAGERTRACE( "PLAYBACK %d page %d hash(%08x) %s\n",
  2420. PAGERID( pPager ), pgno, pager_datahash( pPager.pageSize, aData ),
  2421. ( isMainJrnl != 0 ? "main-journal" : "sub-journal" )
  2422. );
  2423. if ( isMainJrnl != 0 )
  2424. {
  2425. isSynced = pPager.noSync || ( pOffset <= pPager.journalHdr );
  2426. }
  2427. else
  2428. {
  2429. isSynced = ( pPg == null || 0 == ( pPg.flags & PGHDR_NEED_SYNC ) );
  2430. }
  2431. if ( isOpen( pPager.fd )
  2432. && ( pPager.eState >= PAGER_WRITER_DBMOD || pPager.eState == PAGER_OPEN )
  2433. && isSynced
  2434. )
  2435. {
  2436. i64 ofst = ( pgno - 1 ) * pPager.pageSize;
  2437. testcase( 0 == isSavepnt && pPg != null && ( pPg.flags & PGHDR_NEED_SYNC ) != 0 );
  2438. Debug.Assert( !pagerUseWal( pPager ) );
  2439. rc = sqlite3OsWrite( pPager.fd, aData, pPager.pageSize, ofst );
  2440. if ( pgno > pPager.dbFileSize )
  2441. {
  2442. pPager.dbFileSize = pgno;
  2443. }
  2444. if ( pPager.pBackup != null )
  2445. {
  2446. if ( CODEC1( pPager, aData, pgno, SQLITE_DECRYPT ) )
  2447. rc = SQLITE_NOMEM; // CODEC1( pPager, aData, pgno, 3, rc = SQLITE_NOMEM );
  2448. sqlite3BackupUpdate( pPager.pBackup, pgno, (u8[])aData );
  2449. if ( CODEC2( pPager, aData, pgno, SQLITE_ENCRYPT_READ_CTX, ref aData ) )
  2450. rc = SQLITE_NOMEM;//CODEC2( pPager, aData, pgno, 7, rc = SQLITE_NOMEM, aData);
  2451. }
  2452. }
  2453. else if ( 0 == isMainJrnl && pPg == null )
  2454. {
  2455. /* If this is a rollback of a savepoint and data was not written to
  2456. ** the database and the page is not in-memory, there is a potential
  2457. ** problem. When the page is next fetched by the b-tree layer, it
  2458. ** will be read from the database file, which may or may not be
  2459. ** current.
  2460. **
  2461. ** There are a couple of different ways this can happen. All are quite
  2462. ** obscure. When running in synchronous mode, this can only happen
  2463. ** if the page is on the free-list at the start of the transaction, then
  2464. ** populated, then moved using sqlite3PagerMovepage().
  2465. **
  2466. ** The solution is to add an in-memory page to the cache containing
  2467. ** the data just read from the sub-journal. Mark the page as dirty
  2468. ** and if the pager requires a journal-sync, then mark the page as
  2469. ** requiring a journal-sync before it is written.
  2470. */
  2471. Debug.Assert( isSavepnt != 0 );
  2472. Debug.Assert( pPager.doNotSpill == 0 );
  2473. pPager.doNotSpill++;
  2474. rc = sqlite3PagerAcquire( pPager, pgno, ref pPg, 1 );
  2475. Debug.Assert( pPager.doNotSpill == 1 );
  2476. pPager.doNotSpill--;
  2477. if ( rc != SQLITE_OK )
  2478. return rc;
  2479. pPg.flags &= ~PGHDR_NEED_READ;
  2480. sqlite3PcacheMakeDirty( pPg );
  2481. }
  2482. if ( pPg != null )
  2483. {
  2484. /* No page should ever be explicitly rolled back that is in use, except
  2485. ** for page 1 which is held in use in order to keep the lock on the
  2486. ** database active. However such a page may be rolled back as a result
  2487. ** of an internal error resulting in an automatic call to
  2488. ** sqlite3PagerRollback().
  2489. */
  2490. byte[] pData = pPg.pData;
  2491. Buffer.BlockCopy( aData, 0, pData, 0, pPager.pageSize );// memcpy(pData, (u8[])aData, pPager.pageSize);
  2492. pPager.xReiniter( pPg );
  2493. if ( isMainJrnl != 0 && ( 0 == isSavepnt || pOffset <= pPager.journalHdr ) )
  2494. {
  2495. /* If the contents of this page were just restored from the main
  2496. ** journal file, then its content must be as they were when the
  2497. ** transaction was first opened. In this case we can mark the page
  2498. ** as clean, since there will be no need to write it out to the
  2499. ** database.
  2500. **
  2501. ** There is one exception to this rule. If the page is being rolled
  2502. ** back as part of a savepoint (or statement) rollback from an
  2503. ** unsynced portion of the main journal file, then it is not safe
  2504. ** to mark the page as clean. This is because marking the page as
  2505. ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
  2506. ** already in the journal file (recorded in Pager.pInJournal) and
  2507. ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
  2508. ** again within this transaction, it will be marked as dirty but
  2509. ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
  2510. ** be written out into the database file before its journal file
  2511. ** segment is synced. If a crash occurs during or following this,
  2512. ** database corruption may ensue.
  2513. */
  2514. Debug.Assert( !pagerUseWal( pPager ) );
  2515. sqlite3PcacheMakeClean( pPg );
  2516. }
  2517. pager_set_pagehash( pPg );
  2518. /* If this was page 1, then restore the value of Pager.dbFileVers.
  2519. ** Do this before any decoding. */
  2520. if ( pgno == 1 )
  2521. {
  2522. Buffer.BlockCopy( pData, 24, pPager.dbFileVers, 0, pPager.dbFileVers.Length ); //memcpy(pPager.dbFileVers, ((u8*)pData)[24], sizeof(pPager.dbFileVers));
  2523. }
  2524. /* Decode the page just read from disk */
  2525. if ( CODEC1( pPager, pData, pPg.pgno, SQLITE_DECRYPT ) )
  2526. rc = SQLITE_NOMEM; //CODEC1(pPager, pData, pPg.pgno, 3, rc=SQLITE_NOMEM);
  2527. sqlite3PcacheRelease( pPg );
  2528. }
  2529. return rc;
  2530. }
  2531. /*
  2532. ** Parameter zMaster is the name of a master journal file. A single journal
  2533. ** file that referred to the master journal file has just been rolled back.
  2534. ** This routine checks if it is possible to delete the master journal file,
  2535. ** and does so if it is.
  2536. **
  2537. ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
  2538. ** available for use within this function.
  2539. **
  2540. ** When a master journal file is created, it is populated with the names
  2541. ** of all of its child journals, one after another, formatted as utf-8
  2542. ** encoded text. The end of each child journal file is marked with a
  2543. ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
  2544. ** file for a transaction involving two databases might be:
  2545. **
  2546. ** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
  2547. **
  2548. ** A master journal file may only be deleted once all of its child
  2549. ** journals have been rolled back.
  2550. **
  2551. ** This function reads the contents of the master-journal file into
  2552. ** memory and loops through each of the child journal names. For
  2553. ** each child journal, it checks if:
  2554. **
  2555. ** * if the child journal exists, and if so
  2556. ** * if the child journal contains a reference to master journal
  2557. ** file zMaster
  2558. **
  2559. ** If a child journal can be found that matches both of the criteria
  2560. ** above, this function returns without doing anything. Otherwise, if
  2561. ** no such child journal can be found, file zMaster is deleted from
  2562. ** the file-system using sqlite3OsDelete().
  2563. **
  2564. ** If an IO error within this function, an error code is returned. This
  2565. ** function allocates memory by calling sqlite3Malloc(). If an allocation
  2566. ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
  2567. ** occur, SQLITE_OK is returned.
  2568. **
  2569. ** TODO: This function allocates a single block of memory to load
  2570. ** the entire contents of the master journal file. This could be
  2571. ** a couple of kilobytes or so - potentially larger than the page
  2572. ** size.
  2573. */
  2574. static int pager_delmaster( Pager pPager, string zMaster )
  2575. {
  2576. sqlite3_vfs pVfs = pPager.pVfs;
  2577. int rc; /* Return code */
  2578. sqlite3_file pMaster; /* Malloc'd master-journal file descriptor */
  2579. sqlite3_file pJournal; /* Malloc'd child-journal file descriptor */
  2580. //string zMasterJournal = null; /* Contents of master journal file */
  2581. i64 nMasterJournal; /* Size of master journal file */
  2582. string zJournal; /* Pointer to one journal within MJ file */
  2583. string zMasterPtr; /* Space to hold MJ filename from a journal file */
  2584. int nMasterPtr; /* Amount of space allocated to zMasterPtr[] */
  2585. /* Allocate space for both the pJournal and pMaster file descriptors.
  2586. ** If successful, open the master journal file for reading.
  2587. */
  2588. pMaster = new sqlite3_file();// (sqlite3_file*)sqlite3MallocZero( pVfs.szOsFile * 2 );
  2589. pJournal = new sqlite3_file();// (sqlite3_file*)( ( (u8*)pMaster ) + pVfs.szOsFile );
  2590. //if ( null == pMaster )
  2591. //{
  2592. // rc = SQLITE_NOMEM;
  2593. //}
  2594. //else
  2595. {
  2596. const int flags = ( SQLITE_OPEN_READONLY | SQLITE_OPEN_MASTER_JOURNAL );
  2597. int iDummy = 0;
  2598. rc = sqlite3OsOpen( pVfs, zMaster, pMaster, flags, ref iDummy );
  2599. }
  2600. if ( rc != SQLITE_OK )
  2601. goto delmaster_out;
  2602. Debugger.Break(); //TODO --
  2603. /* Load the entire master journal file into space obtained from
  2604. ** sqlite3_malloc() and pointed to by zMasterJournal. Also obtain
  2605. ** sufficient space (in zMasterPtr) to hold the names of master
  2606. ** journal files extracted from regular rollback-journals.
  2607. */
  2608. //rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
  2609. //if (rc != SQLITE_OK) goto delmaster_out;
  2610. //nMasterPtr = pVfs.mxPathname + 1;
  2611. // zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
  2612. // if ( !zMasterJournal )
  2613. // {
  2614. // rc = SQLITE_NOMEM;
  2615. // goto delmaster_out;
  2616. // }
  2617. // zMasterPtr = &zMasterJournal[nMasterJournal+1];
  2618. // rc = sqlite3OsRead( pMaster, zMasterJournal, (int)nMasterJournal, 0 );
  2619. // if ( rc != SQLITE_OK ) goto delmaster_out;
  2620. // zMasterJournal[nMasterJournal] = 0;
  2621. // zJournal = zMasterJournal;
  2622. // while ( ( zJournal - zMasterJournal ) < nMasterJournal )
  2623. // {
  2624. // int exists;
  2625. // rc = sqlite3OsAccess( pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists );
  2626. // if ( rc != SQLITE_OK )
  2627. // {
  2628. // goto delmaster_out;
  2629. // }
  2630. // if ( exists )
  2631. // {
  2632. // /* One of the journals pointed to by the master journal exists.
  2633. // ** Open it and check if it points at the master journal. If
  2634. // ** so, return without deleting the master journal file.
  2635. // */
  2636. // int c;
  2637. // int flags = ( SQLITE_OPEN_READONLY | SQLITE_OPEN_MAIN_JOURNAL );
  2638. // rc = sqlite3OsOpen( pVfs, zJournal, pJournal, flags, 0 );
  2639. // if ( rc != SQLITE_OK )
  2640. // {
  2641. // goto delmaster_out;
  2642. // }
  2643. // rc = readMasterJournal( pJournal, zMasterPtr, nMasterPtr );
  2644. // sqlite3OsClose( pJournal );
  2645. // if ( rc != SQLITE_OK )
  2646. // {
  2647. // goto delmaster_out;
  2648. // }
  2649. // c = zMasterPtr[0] != 0 && strcmp( zMasterPtr, zMaster ) == 0;
  2650. // if ( c )
  2651. // {
  2652. // /* We have a match. Do not delete the master journal file. */
  2653. // goto delmaster_out;
  2654. // }
  2655. // }
  2656. // zJournal += ( sqlite3Strlen30( zJournal ) + 1 );
  2657. // }
  2658. //
  2659. //sqlite3OsClose(pMaster);
  2660. //rc = sqlite3OsDelete( pVfs, zMaster, 0 );
  2661. goto delmaster_out;
  2662. delmaster_out:
  2663. //sqlite3_free( ref zMasterJournal );
  2664. if ( pMaster != null )
  2665. {
  2666. sqlite3OsClose( pMaster );
  2667. Debug.Assert( !isOpen( pJournal ) );
  2668. //sqlite3_free( ref pMaster );
  2669. }
  2670. return rc;
  2671. }
  2672. /*
  2673. ** This function is used to change the actual size of the database
  2674. ** file in the file-system. This only happens when committing a transaction,
  2675. ** or rolling back a transaction (including rolling back a hot-journal).
  2676. **
  2677. ** If the main database file is not open, or the pager is not in either
  2678. ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
  2679. ** of the file is changed to nPage pages (nPage*pPager.pageSize bytes).
  2680. ** If the file on disk is currently larger than nPage pages, then use the VFS
  2681. ** xTruncate() method to truncate it.
  2682. **
  2683. ** Or, it might might be the case that the file on disk is smaller than
  2684. ** nPage pages. Some operating system implementations can get confused if
  2685. ** you try to truncate a file to some size that is larger than it
  2686. ** currently is, so detect this case and write a single zero byte to
  2687. ** the end of the new file instead.
  2688. **
  2689. ** If successful, return SQLITE_OK. If an IO error occurs while modifying
  2690. ** the database file, return the error code to the caller.
  2691. */
  2692. static int pager_truncate( Pager pPager, u32 nPage )
  2693. {
  2694. int rc = SQLITE_OK;
  2695. Debug.Assert( pPager.eState != PAGER_ERROR );
  2696. Debug.Assert( pPager.eState != PAGER_READER );
  2697. if ( isOpen( pPager.fd )
  2698. && ( pPager.eState >= PAGER_WRITER_DBMOD || pPager.eState == PAGER_OPEN )
  2699. )
  2700. {
  2701. i64 currentSize = 0, newSize;
  2702. int szPage = pPager.pageSize;
  2703. Debug.Assert( pPager.eLock == EXCLUSIVE_LOCK );
  2704. /* TODO: Is it safe to use Pager.dbFileSize here? */
  2705. rc = sqlite3OsFileSize( pPager.fd, ref currentSize );
  2706. newSize = szPage * nPage;
  2707. if ( rc == SQLITE_OK && currentSize != newSize )
  2708. {
  2709. if ( currentSize > newSize )
  2710. {
  2711. rc = sqlite3OsTruncate( pPager.fd, newSize );
  2712. }
  2713. else
  2714. {
  2715. byte[] pTmp = pPager.pTmpSpace;
  2716. Array.Clear( pTmp, 0, szPage );//memset( pTmp, 0, szPage );
  2717. testcase( ( newSize - szPage ) < currentSize );
  2718. testcase( ( newSize - szPage ) == currentSize );
  2719. testcase( ( newSize - szPage ) > currentSize );
  2720. rc = sqlite3OsWrite( pPager.fd, pTmp, szPage, newSize - szPage );
  2721. }
  2722. if ( rc == SQLITE_OK )
  2723. {
  2724. pPager.dbSize = nPage;
  2725. }
  2726. }
  2727. }
  2728. return rc;
  2729. }
  2730. /*
  2731. ** Set the value of the Pager.sectorSize variable for the given
  2732. ** pager based on the value returned by the xSectorSize method
  2733. ** of the open database file. The sector size will be used used
  2734. ** to determine the size and alignment of journal header and
  2735. ** master journal pointers within created journal files.
  2736. **
  2737. ** For temporary files the effective sector size is always 512 bytes.
  2738. **
  2739. ** Otherwise, for non-temporary files, the effective sector size is
  2740. ** the value returned by the xSectorSize() method rounded up to 512 if
  2741. ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
  2742. ** is greater than MAX_SECTOR_SIZE.
  2743. */
  2744. static void setSectorSize( Pager pPager )
  2745. {
  2746. Debug.Assert( isOpen( pPager.fd ) || pPager.tempFile );
  2747. if ( !pPager.tempFile )
  2748. {
  2749. /* Sector size doesn't matter for temporary files. Also, the file
  2750. ** may not have been opened yet, in which case the OsSectorSize()
  2751. ** call will segfault.
  2752. */
  2753. pPager.sectorSize = (u32)sqlite3OsSectorSize( pPager.fd );
  2754. }
  2755. if ( pPager.sectorSize < 32 )
  2756. {
  2757. Debug.Assert( MAX_SECTOR_SIZE >= 512 );
  2758. pPager.sectorSize = 512;
  2759. }
  2760. if ( pPager.sectorSize > MAX_SECTOR_SIZE )
  2761. {
  2762. pPager.sectorSize = MAX_SECTOR_SIZE;
  2763. }
  2764. }
  2765. /*
  2766. ** Playback the journal and thus restore the database file to
  2767. ** the state it was in before we started making changes.
  2768. **
  2769. ** The journal file format is as follows:
  2770. **
  2771. ** (1) 8 byte prefix. A copy of aJournalMagic[].
  2772. ** (2) 4 byte big-endian integer which is the number of valid page records
  2773. ** in the journal. If this value is 0xffffffff, then compute the
  2774. ** number of page records from the journal size.
  2775. ** (3) 4 byte big-endian integer which is the initial value for the
  2776. ** sanity checksum.
  2777. ** (4) 4 byte integer which is the number of pages to truncate the
  2778. ** database to during a rollback.
  2779. ** (5) 4 byte big-endian integer which is the sector size. The header
  2780. ** is this many bytes in size.
  2781. ** (6) 4 byte big-endian integer which is the page size.
  2782. ** (7) zero padding out to the next sector size.
  2783. ** (8) Zero or more pages instances, each as follows:
  2784. **
  2785. ** When we speak of the journal header, we mean the first 7 items above.
  2786. ** Each entry in the journal is an instance of the 8th item.
  2787. **
  2788. ** Call the value from the second bullet "nRec". nRec is the number of
  2789. ** valid page entries in the journal. In most cases, you can compute the
  2790. ** value of nRec from the size of the journal file. But if a power
  2791. ** failure occurred while the journal was being written, it could be the
  2792. ** case that the size of the journal file had already been increased but
  2793. ** the extra entries had not yet made it safely to disk. In such a case,
  2794. ** the value of nRec computed from the file size would be too large. For
  2795. ** that reason, we always use the nRec value in the header.
  2796. **
  2797. ** If the nRec value is 0xffffffff it means that nRec should be computed
  2798. ** from the file size. This value is used when the user selects the
  2799. ** no-sync option for the journal. A power failure could lead to corruption
  2800. ** in this case. But for things like temporary table (which will be
  2801. ** deleted when the power is restored) we don't care.
  2802. **
  2803. ** If the file opened as the journal file is not a well-formed
  2804. ** journal file then all pages up to the first corrupted page are rolled
  2805. ** back (or no pages if the journal header is corrupted). The journal file
  2806. ** is then deleted and SQLITE_OK returned, just as if no corruption had
  2807. ** been encountered.
  2808. **
  2809. ** If an I/O or malloc() error occurs, the journal-file is not deleted
  2810. ** and an error code is returned.
  2811. **
  2812. ** The isHot parameter indicates that we are trying to rollback a journal
  2813. ** that might be a hot journal. Or, it could be that the journal is
  2814. ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
  2815. ** If the journal really is hot, reset the pager cache prior rolling
  2816. ** back any content. If the journal is merely persistent, no reset is
  2817. ** needed.
  2818. */
  2819. static int pager_playback( Pager pPager, int isHot )
  2820. {
  2821. sqlite3_vfs pVfs = pPager.pVfs;
  2822. i64 szJ = 0; /* Size of the journal file in bytes */
  2823. u32 nRec = 0; /* Number of Records in the journal */
  2824. u32 u; /* Unsigned loop counter */
  2825. u32 mxPg = 0; /* Size of the original file in pages */
  2826. int rc; /* Result code of a subroutine */
  2827. int res = 1; /* Value returned by sqlite3OsAccess() */
  2828. byte[] zMaster = null; /* Name of master journal file if any */
  2829. int needPagerReset; /* True to reset page prior to first page rollback */
  2830. /* Figure out how many records are in the journal. Abort early if
  2831. ** the journal is empty.
  2832. */
  2833. Debug.Assert( isOpen( pPager.jfd ) );
  2834. rc = sqlite3OsFileSize( pPager.jfd, ref szJ );
  2835. if ( rc != SQLITE_OK )
  2836. {
  2837. goto end_playback;
  2838. }
  2839. /* Read the master journal name from the journal, if it is present.
  2840. ** If a master journal file name is specified, but the file is not
  2841. ** present on disk, then the journal is not hot and does not need to be
  2842. ** played back.
  2843. **
  2844. ** TODO: Technically the following is an error because it assumes that
  2845. ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
  2846. ** (pPager.pageSize >= pPager.pVfs.mxPathname+1). Using os_unix.c,
  2847. ** mxPathname is 512, which is the same as the minimum allowable value
  2848. ** for pageSize.
  2849. */
  2850. zMaster = new byte[pPager.pVfs.mxPathname + 1];// pPager.pTmpSpace );
  2851. rc = readMasterJournal( pPager.jfd, zMaster, (u32)pPager.pVfs.mxPathname + 1 );
  2852. if ( rc == SQLITE_OK && zMaster[0] != 0 )
  2853. {
  2854. rc = sqlite3OsAccess( pVfs, Encoding.UTF8.GetString( zMaster, 0, zMaster.Length ), SQLITE_ACCESS_EXISTS, ref res );
  2855. }
  2856. zMaster = null;
  2857. if ( rc != SQLITE_OK || res == 0 )
  2858. {
  2859. goto end_playback;
  2860. }
  2861. pPager.journalOff = 0;
  2862. needPagerReset = isHot;
  2863. /* This loop terminates either when a readJournalHdr() or
  2864. ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
  2865. ** occurs.
  2866. */
  2867. while ( true )
  2868. {
  2869. /* Read the next journal header from the journal file. If there are
  2870. ** not enough bytes left in the journal file for a complete header, or
  2871. ** it is corrupted, then a process must have failed while writing it.
  2872. ** This indicates nothing more needs to be rolled back.
  2873. */
  2874. rc = readJournalHdr( pPager, isHot, szJ, out nRec, out mxPg );
  2875. if ( rc != SQLITE_OK )
  2876. {
  2877. if ( rc == SQLITE_DONE )
  2878. {
  2879. rc = SQLITE_OK;
  2880. }
  2881. goto end_playback;
  2882. }
  2883. /* If nRec is 0xffffffff, then this journal was created by a process
  2884. ** working in no-sync mode. This means that the rest of the journal
  2885. ** file consists of pages, there are no more journal headers. Compute
  2886. ** the value of nRec based on this assumption.
  2887. */
  2888. if ( nRec == 0xffffffff )
  2889. {
  2890. Debug.Assert( pPager.journalOff == JOURNAL_HDR_SZ( pPager ) );
  2891. nRec = (u32)( ( szJ - JOURNAL_HDR_SZ( pPager ) ) / JOURNAL_PG_SZ( pPager ) );
  2892. }
  2893. /* If nRec is 0 and this rollback is of a transaction created by this
  2894. ** process and if this is the final header in the journal, then it means
  2895. ** that this part of the journal was being filled but has not yet been
  2896. ** synced to disk. Compute the number of pages based on the remaining
  2897. ** size of the file.
  2898. **
  2899. ** The third term of the test was added to fix ticket #2565.
  2900. ** When rolling back a hot journal, nRec==0 always means that the next
  2901. ** chunk of the journal contains zero pages to be rolled back. But
  2902. ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
  2903. ** the journal, it means that the journal might contain additional
  2904. ** pages that need to be rolled back and that the number of pages
  2905. ** should be computed based on the journal file size.
  2906. */
  2907. if ( nRec == 0 && 0 == isHot &&
  2908. pPager.journalHdr + JOURNAL_HDR_SZ( pPager ) == pPager.journalOff )
  2909. {
  2910. nRec = (u32)( ( szJ - pPager.journalOff ) / JOURNAL_PG_SZ( pPager ) );
  2911. }
  2912. /* If this is the first header read from the journal, truncate the
  2913. ** database file back to its original size.
  2914. */
  2915. if ( pPager.journalOff == JOURNAL_HDR_SZ( pPager ) )
  2916. {
  2917. rc = pager_truncate( pPager, mxPg );
  2918. if ( rc != SQLITE_OK )
  2919. {
  2920. goto end_playback;
  2921. }
  2922. pPager.dbSize = mxPg;
  2923. }
  2924. /* Copy original pages out of the journal and back into the
  2925. ** database file and/or page cache.
  2926. */
  2927. for ( u = 0; u < nRec; u++ )
  2928. {
  2929. if ( needPagerReset != 0 )
  2930. {
  2931. pager_reset( pPager );
  2932. needPagerReset = 0;
  2933. }
  2934. rc = pager_playback_one_page( pPager, ref pPager.journalOff, null, 1, 0 );
  2935. if ( rc != SQLITE_OK )
  2936. {
  2937. if ( rc == SQLITE_DONE )
  2938. {
  2939. rc = SQLITE_OK;
  2940. pPager.journalOff = szJ;
  2941. break;
  2942. }
  2943. else if ( rc == SQLITE_IOERR_SHORT_READ )
  2944. {
  2945. /* If the journal has been truncated, simply stop reading and
  2946. ** processing the journal. This might happen if the journal was
  2947. ** not completely written and synced prior to a crash. In that
  2948. ** case, the database should have never been written in the
  2949. ** first place so it is OK to simply abandon the rollback. */
  2950. rc = SQLITE_OK;
  2951. goto end_playback;
  2952. }
  2953. else
  2954. {
  2955. /* If we are unable to rollback, quit and return the error
  2956. ** code. This will cause the pager to enter the error state
  2957. ** so that no further harm will be done. Perhaps the next
  2958. ** process to come along will be able to rollback the database.
  2959. */
  2960. goto end_playback;
  2961. }
  2962. }
  2963. }
  2964. }
  2965. /*NOTREACHED*/
  2966. end_playback:
  2967. /* Following a rollback, the database file should be back in its original
  2968. ** state prior to the start of the transaction, so invoke the
  2969. ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
  2970. ** assertion that the transaction counter was modified.
  2971. */
  2972. sqlite3_int64 iDummy = 0;
  2973. Debug.Assert(
  2974. pPager.fd.pMethods == null ||
  2975. sqlite3OsFileControl( pPager.fd, SQLITE_FCNTL_DB_UNCHANGED, ref iDummy ) >= SQLITE_OK
  2976. );
  2977. /* If this playback is happening automatically as a result of an IO or
  2978. ** malloc error that occurred after the change-counter was updated but
  2979. ** before the transaction was committed, then the change-counter
  2980. ** modification may just have been reverted. If this happens in exclusive
  2981. ** mode, then subsequent transactions performed by the connection will not
  2982. ** update the change-counter at all. This may lead to cache inconsistency
  2983. ** problems for other processes at some point in the future. So, just
  2984. ** in case this has happened, clear the changeCountDone flag now.
  2985. */
  2986. pPager.changeCountDone = pPager.tempFile;
  2987. if ( rc == SQLITE_OK )
  2988. {
  2989. zMaster = new byte[pPager.pVfs.mxPathname + 1];//pPager.pTmpSpace );
  2990. rc = readMasterJournal( pPager.jfd, zMaster, (u32)pPager.pVfs.mxPathname + 1 );
  2991. testcase( rc != SQLITE_OK );
  2992. }
  2993. if ( rc == SQLITE_OK
  2994. && ( pPager.eState >= PAGER_WRITER_DBMOD || pPager.eState == PAGER_OPEN )
  2995. )
  2996. {
  2997. rc = sqlite3PagerSync( pPager );
  2998. }
  2999. if ( rc == SQLITE_OK )
  3000. {
  3001. rc = pager_end_transaction( pPager, zMaster[0] != '\0' ? 1 : 0 );
  3002. testcase( rc != SQLITE_OK );
  3003. }
  3004. if ( rc == SQLITE_OK && zMaster[0] != '\0' && res != 0 )
  3005. {
  3006. /* If there was a master journal and this routine will return success,
  3007. ** see if it is possible to delete the master journal.
  3008. */
  3009. rc = pager_delmaster( pPager, Encoding.UTF8.GetString( zMaster, 0, zMaster.Length ) );
  3010. testcase( rc != SQLITE_OK );
  3011. }
  3012. /* The Pager.sectorSize variable may have been updated while rolling
  3013. ** back a journal created by a process with a different sector size
  3014. ** value. Reset it to the correct value for this process.
  3015. */
  3016. setSectorSize( pPager );
  3017. return rc;
  3018. }
  3019. /*
  3020. ** Read the content for page pPg out of the database file and into
  3021. ** pPg.pData. A shared lock or greater must be held on the database
  3022. ** file before this function is called.
  3023. **
  3024. ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
  3025. ** the value read from the database file.
  3026. **
  3027. ** If an IO error occurs, then the IO error is returned to the caller.
  3028. ** Otherwise, SQLITE_OK is returned.
  3029. */
  3030. static int readDbPage( PgHdr pPg )
  3031. {
  3032. Pager pPager = pPg.pPager; /* Pager object associated with page pPg */
  3033. Pgno pgno = pPg.pgno; /* Page number to read */
  3034. int rc = SQLITE_OK; /* Return code */
  3035. int isInWal = 0; /* True if page is in log file */
  3036. int pgsz = pPager.pageSize; /* Number of bytes to read */
  3037. Debug.Assert( pPager.eState >= PAGER_READER &&
  3038. #if SQLITE_OMIT_MEMORYDB
  3039. 0 == MEMDB
  3040. #else
  3041. 0 == pPager.memDb
  3042. #endif
  3043. );
  3044. Debug.Assert( isOpen( pPager.fd ) );
  3045. if ( NEVER( !isOpen( pPager.fd ) ) )
  3046. {
  3047. Debug.Assert( pPager.tempFile );
  3048. Array.Clear( pPg.pData, 0, pPager.pageSize );// memset(pPg.pData, 0, pPager.pageSize);
  3049. return SQLITE_OK;
  3050. }
  3051. if ( pagerUseWal( pPager ) )
  3052. {
  3053. /* Try to pull the page from the write-ahead log. */
  3054. rc = sqlite3WalRead( pPager.pWal, pgno, ref isInWal, pgsz, pPg.pData );
  3055. }
  3056. if ( rc == SQLITE_OK && 0 == isInWal )
  3057. {
  3058. i64 iOffset = ( pgno - 1 ) * (i64)pPager.pageSize;
  3059. rc = sqlite3OsRead( pPager.fd, pPg.pData, pgsz, iOffset );
  3060. if ( rc == SQLITE_IOERR_SHORT_READ )
  3061. {
  3062. rc = SQLITE_OK;
  3063. }
  3064. }
  3065. if ( pgno == 1 )
  3066. {
  3067. if ( rc != 0 )
  3068. {
  3069. /* If the read is unsuccessful, set the dbFileVers[] to something
  3070. ** that will never be a valid file version. dbFileVers[] is a copy
  3071. ** of bytes 24..39 of the database. Bytes 28..31 should always be
  3072. ** zero or the size of the database in page. Bytes 32..35 and 35..39
  3073. ** should be page numbers which are never 0xffffffff. So filling
  3074. ** pPager.dbFileVers[] with all 0xff bytes should suffice.
  3075. **
  3076. ** For an encrypted database, the situation is more complex: bytes
  3077. ** 24..39 of the database are white noise. But the probability of
  3078. ** white noising equaling 16 bytes of 0xff is vanishingly small so
  3079. ** we should still be ok.
  3080. */
  3081. for ( int i = 0; i < pPager.dbFileVers.Length; pPager.dbFileVers[i++] = 0xff )
  3082. ; // memset(pPager.dbFileVers, 0xff, sizeof(pPager.dbFileVers));
  3083. }
  3084. else
  3085. {
  3086. //u8[] dbFileVers = pPg.pData[24];
  3087. Buffer.BlockCopy( pPg.pData, 24, pPager.dbFileVers, 0, pPager.dbFileVers.Length ); //memcpy(&pPager.dbFileVers, dbFileVers, sizeof(pPager.dbFileVers));
  3088. }
  3089. }
  3090. if ( CODEC1( pPager, pPg.pData, pgno, SQLITE_DECRYPT ) )
  3091. rc = SQLITE_NOMEM;//CODEC1(pPager, pPg.pData, pgno, 3, rc = SQLITE_NOMEM);
  3092. #if SQLITE_TEST
  3093. // PAGER_INCR(ref sqlite3_pager_readdb_count);
  3094. #if !TCLSH
  3095. PAGER_INCR( ref sqlite3_pager_readdb_count );
  3096. #else
  3097. int iValue;
  3098. iValue = sqlite3_pager_readdb_count.iValue;
  3099. PAGER_INCR( ref iValue );
  3100. sqlite3_pager_readdb_count.iValue = iValue;
  3101. #endif
  3102. PAGER_INCR( ref pPager.nRead );
  3103. #endif
  3104. IOTRACE( "PGIN %p %d\n", pPager, pgno );
  3105. PAGERTRACE( "FETCH %d page %d hash(%08x)\n",
  3106. PAGERID( pPager ), pgno, pager_pagehash( pPg ) );
  3107. return rc;
  3108. }
  3109. /*
  3110. ** Update the value of the change-counter at offsets 24 and 92 in
  3111. ** the header and the sqlite version number at offset 96.
  3112. **
  3113. ** This is an unconditional update. See also the pager_incr_changecounter()
  3114. ** routine which only updates the change-counter if the update is actually
  3115. ** needed, as determined by the pPager.changeCountDone state variable.
  3116. */
  3117. static void pager_write_changecounter( PgHdr pPg )
  3118. {
  3119. u32 change_counter;
  3120. /* Increment the value just read and write it back to byte 24. */
  3121. change_counter = sqlite3Get4byte( pPg.pPager.dbFileVers, 0 ) + 1;
  3122. put32bits( pPg.pData, 24, change_counter );
  3123. /* Also store the SQLite version number in bytes 96..99 and in
  3124. ** bytes 92..95 store the change counter for which the version number
  3125. ** is valid. */
  3126. put32bits( pPg.pData, 92, change_counter );
  3127. put32bits( pPg.pData, 96, SQLITE_VERSION_NUMBER );
  3128. }
  3129. #if !SQLITE_OMIT_WAL
  3130. /*
  3131. ** This function is invoked once for each page that has already been
  3132. ** written into the log file when a WAL transaction is rolled back.
  3133. ** Parameter iPg is the page number of said page. The pCtx argument
  3134. ** is actually a pointer to the Pager structure.
  3135. **
  3136. ** If page iPg is present in the cache, and has no outstanding references,
  3137. ** it is discarded. Otherwise, if there are one or more outstanding
  3138. ** references, the page content is reloaded from the database. If the
  3139. ** attempt to reload content from the database is required and fails,
  3140. ** return an SQLite error code. Otherwise, SQLITE_OK.
  3141. */
  3142. static int pagerUndoCallback(void *pCtx, Pgno iPg){
  3143. int rc = SQLITE_OK;
  3144. Pager *pPager = (Pager *)pCtx;
  3145. PgHdr *pPg;
  3146. pPg = sqlite3PagerLookup(pPager, iPg);
  3147. if( pPg ){
  3148. if( sqlite3PcachePageRefcount(pPg)==1 ){
  3149. sqlite3PcacheDrop(pPg);
  3150. }else{
  3151. rc = readDbPage(pPg);
  3152. if( rc==SQLITE_OK ){
  3153. pPager.xReiniter(pPg);
  3154. }
  3155. sqlite3PagerUnref(pPg);
  3156. }
  3157. }
  3158. /* Normally, if a transaction is rolled back, any backup processes are
  3159. ** updated as data is copied out of the rollback journal and into the
  3160. ** database. This is not generally possible with a WAL database, as
  3161. ** rollback involves simply truncating the log file. Therefore, if one
  3162. ** or more frames have already been written to the log (and therefore
  3163. ** also copied into the backup databases) as part of this transaction,
  3164. ** the backups must be restarted.
  3165. */
  3166. sqlite3BackupRestart(pPager.pBackup);
  3167. return rc;
  3168. }
  3169. /*
  3170. ** This function is called to rollback a transaction on a WAL database.
  3171. */
  3172. static int pagerRollbackWal(Pager *pPager){
  3173. int rc; /* Return Code */
  3174. PgHdr *pList; /* List of dirty pages to revert */
  3175. /* For all pages in the cache that are currently dirty or have already
  3176. ** been written (but not committed) to the log file, do one of the
  3177. ** following:
  3178. **
  3179. ** + Discard the cached page (if refcount==0), or
  3180. ** + Reload page content from the database (if refcount>0).
  3181. */
  3182. pPager.dbSize = pPager.dbOrigSize;
  3183. rc = sqlite3WalUndo(pPager.pWal, pagerUndoCallback, (void *)pPager);
  3184. pList = sqlite3PcacheDirtyList(pPager.pPCache);
  3185. while( pList && rc==SQLITE_OK ){
  3186. PgHdr *pNext = pList->pDirty;
  3187. rc = pagerUndoCallback((void *)pPager, pList->pgno);
  3188. pList = pNext;
  3189. }
  3190. return rc;
  3191. }
  3192. /*
  3193. ** This function is a wrapper around sqlite3WalFrames(). As well as logging
  3194. ** the contents of the list of pages headed by pList (connected by pDirty),
  3195. ** this function notifies any active backup processes that the pages have
  3196. ** changed.
  3197. **
  3198. ** The list of pages passed into this routine is always sorted by page number.
  3199. ** Hence, if page 1 appears anywhere on the list, it will be the first page.
  3200. */
  3201. static int pagerWalFrames(
  3202. Pager *pPager, /* Pager object */
  3203. PgHdr *pList, /* List of frames to log */
  3204. Pgno nTruncate, /* Database size after this commit */
  3205. int isCommit, /* True if this is a commit */
  3206. int syncFlags /* Flags to pass to OsSync() (or 0) */
  3207. ){
  3208. int rc; /* Return code */
  3209. #if (SQLITE_DEBUG) || (SQLITE_CHECK_PAGES)
  3210. PgHdr *p; /* For looping over pages */
  3211. #endif
  3212. assert( pPager.pWal );
  3213. #if SQLITE_DEBUG
  3214. /* Verify that the page list is in accending order */
  3215. for(p=pList; p && p->pDirty; p=p->pDirty){
  3216. assert( p->pgno < p->pDirty->pgno );
  3217. }
  3218. #endif
  3219. if( isCommit ){
  3220. /* If a WAL transaction is being committed, there is no point in writing
  3221. ** any pages with page numbers greater than nTruncate into the WAL file.
  3222. ** They will never be read by any client. So remove them from the pDirty
  3223. ** list here. */
  3224. PgHdr *p;
  3225. PgHdr **ppNext = &pList;
  3226. for(p=pList; (*ppNext = p); p=p->pDirty){
  3227. if( p->pgno<=nTruncate ) ppNext = &p->pDirty;
  3228. }
  3229. assert( pList );
  3230. }
  3231. if( pList->pgno==1 ) pager_write_changecounter(pList);
  3232. rc = sqlite3WalFrames(pPager.pWal,
  3233. pPager.pageSize, pList, nTruncate, isCommit, syncFlags
  3234. );
  3235. if( rc==SQLITE_OK && pPager.pBackup ){
  3236. PgHdr *p;
  3237. for(p=pList; p; p=p->pDirty){
  3238. sqlite3BackupUpdate(pPager.pBackup, p->pgno, (u8 *)p->pData);
  3239. }
  3240. }
  3241. #if SQLITE_CHECK_PAGES
  3242. pList = sqlite3PcacheDirtyList(pPager.pPCache);
  3243. for(p=pList; p; p=p->pDirty){
  3244. pager_set_pagehash(p);
  3245. }
  3246. #endif
  3247. return rc;
  3248. }
  3249. /*
  3250. ** Begin a read transaction on the WAL.
  3251. **
  3252. ** This routine used to be called "pagerOpenSnapshot()" because it essentially
  3253. ** makes a snapshot of the database at the current point in time and preserves
  3254. ** that snapshot for use by the reader in spite of concurrently changes by
  3255. ** other writers or checkpointers.
  3256. */
  3257. static int pagerBeginReadTransaction(Pager *pPager){
  3258. int rc; /* Return code */
  3259. int changed = 0; /* True if cache must be reset */
  3260. assert( pagerUseWal(pPager) );
  3261. assert( pPager.eState==PAGER_OPEN || pPager.eState==PAGER_READER );
  3262. /* sqlite3WalEndReadTransaction() was not called for the previous
  3263. ** transaction in locking_mode=EXCLUSIVE. So call it now. If we
  3264. ** are in locking_mode=NORMAL and EndRead() was previously called,
  3265. ** the duplicate call is harmless.
  3266. */
  3267. sqlite3WalEndReadTransaction(pPager.pWal);
  3268. rc = sqlite3WalBeginReadTransaction(pPager.pWal, &changed);
  3269. if( rc!=SQLITE_OK || changed ){
  3270. pager_reset(pPager);
  3271. }
  3272. return rc;
  3273. }
  3274. #endif
  3275. /*
  3276. ** This function is called as part of the transition from PAGER_OPEN
  3277. ** to PAGER_READER state to determine the size of the database file
  3278. ** in pages (assuming the page size currently stored in Pager.pageSize).
  3279. **
  3280. ** If no error occurs, SQLITE_OK is returned and the size of the database
  3281. ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
  3282. ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
  3283. */
  3284. static int pagerPagecount( Pager pPager, ref Pgno pnPage )
  3285. {
  3286. Pgno nPage; /* Value to return via *pnPage */
  3287. /* Query the WAL sub-system for the database size. The WalDbsize()
  3288. ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
  3289. ** if the database size is not available. The database size is not
  3290. ** available from the WAL sub-system if the log file is empty or
  3291. ** contains no valid committed transactions.
  3292. */
  3293. Debug.Assert( pPager.eState == PAGER_OPEN );
  3294. Debug.Assert( pPager.eLock >= SHARED_LOCK || pPager.noReadlock != 0 );
  3295. nPage = sqlite3WalDbsize( pPager.pWal );
  3296. /* If the database size was not available from the WAL sub-system,
  3297. ** determine it based on the size of the database file. If the size
  3298. ** of the database file is not an integer multiple of the page-size,
  3299. ** round down to the nearest page. Except, any file larger than 0
  3300. ** bytes in size is considered to contain at least one page.
  3301. */
  3302. if ( nPage == 0 )
  3303. {
  3304. i64 n = 0; /* Size of db file in bytes */
  3305. Debug.Assert( isOpen( pPager.fd ) || pPager.tempFile );
  3306. if ( isOpen( pPager.fd ) )
  3307. {
  3308. int rc = sqlite3OsFileSize( pPager.fd, ref n );
  3309. if ( rc != SQLITE_OK )
  3310. {
  3311. return rc;
  3312. }
  3313. }
  3314. nPage = (Pgno)( n / pPager.pageSize );
  3315. if ( nPage == 0 && n > 0 )
  3316. {
  3317. nPage = 1;
  3318. }
  3319. }
  3320. /* If the current number of pages in the file is greater than the
  3321. ** configured maximum pager number, increase the allowed limit so
  3322. ** that the file can be read.
  3323. */
  3324. if ( nPage > pPager.mxPgno )
  3325. {
  3326. pPager.mxPgno = (Pgno)nPage;
  3327. }
  3328. pnPage = nPage;
  3329. return SQLITE_OK;
  3330. }
  3331. #if !SQLITE_OMIT_WAL
  3332. /*
  3333. ** Check if the *-wal file that corresponds to the database opened by pPager
  3334. ** exists if the database is not empy, or verify that the *-wal file does
  3335. ** not exist (by deleting it) if the database file is empty.
  3336. **
  3337. ** If the database is not empty and the *-wal file exists, open the pager
  3338. ** in WAL mode. If the database is empty or if no *-wal file exists and
  3339. ** if no error occurs, make sure Pager.journalMode is not set to
  3340. ** PAGER_JOURNALMODE_WAL.
  3341. **
  3342. ** Return SQLITE_OK or an error code.
  3343. **
  3344. ** The caller must hold a SHARED lock on the database file to call this
  3345. ** function. Because an EXCLUSIVE lock on the db file is required to delete
  3346. ** a WAL on a none-empty database, this ensures there is no race condition
  3347. ** between the xAccess() below and an xDelete() being executed by some
  3348. ** other connection.
  3349. */
  3350. static int pagerOpenWalIfPresent(Pager *pPager){
  3351. int rc = SQLITE_OK;
  3352. Debug.Assert( pPager.eState==PAGER_OPEN );
  3353. Debug.Assert( pPager.eLock>=SHARED_LOCK || pPager.noReadlock );
  3354. if( !pPager.tempFile ){
  3355. int isWal; /* True if WAL file exists */
  3356. Pgno nPage; /* Size of the database file */
  3357. rc = pagerPagecount(pPager, &nPage);
  3358. if( rc ) return rc;
  3359. if( nPage==0 ){
  3360. rc = sqlite3OsDelete(pPager.pVfs, pPager.zWal, 0);
  3361. isWal = 0;
  3362. }else{
  3363. rc = sqlite3OsAccess(
  3364. pPager.pVfs, pPager.zWal, SQLITE_ACCESS_EXISTS, &isWal
  3365. );
  3366. }
  3367. if( rc==SQLITE_OK ){
  3368. if( isWal ){
  3369. testcase( sqlite3PcachePagecount(pPager.pPCache)==0 );
  3370. rc = sqlite3PagerOpenWal(pPager, 0);
  3371. }else if( pPager.journalMode==PAGER_JOURNALMODE_WAL ){
  3372. pPager.journalMode = PAGER_JOURNALMODE_DELETE;
  3373. }
  3374. }
  3375. }
  3376. return rc;
  3377. }
  3378. #endif
  3379. /*
  3380. ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
  3381. ** the entire master journal file. The case pSavepoint==NULL occurs when
  3382. ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
  3383. ** savepoint.
  3384. **
  3385. ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
  3386. ** being rolled back), then the rollback consists of up to three stages,
  3387. ** performed in the order specified:
  3388. **
  3389. ** * Pages are played back from the main journal starting at byte
  3390. ** offset PagerSavepoint.iOffset and continuing to
  3391. ** PagerSavepoint.iHdrOffset, or to the end of the main journal
  3392. ** file if PagerSavepoint.iHdrOffset is zero.
  3393. **
  3394. ** * If PagerSavepoint.iHdrOffset is not zero, then pages are played
  3395. ** back starting from the journal header immediately following
  3396. ** PagerSavepoint.iHdrOffset to the end of the main journal file.
  3397. **
  3398. ** * Pages are then played back from the sub-journal file, starting
  3399. ** with the PagerSavepoint.iSubRec and continuing to the end of
  3400. ** the journal file.
  3401. **
  3402. ** Throughout the rollback process, each time a page is rolled back, the
  3403. ** corresponding bit is set in a bitvec structure (variable pDone in the
  3404. ** implementation below). This is used to ensure that a page is only
  3405. ** rolled back the first time it is encountered in either journal.
  3406. **
  3407. ** If pSavepoint is NULL, then pages are only played back from the main
  3408. ** journal file. There is no need for a bitvec in this case.
  3409. **
  3410. ** In either case, before playback commences the Pager.dbSize variable
  3411. ** is reset to the value that it held at the start of the savepoint
  3412. ** (or transaction). No page with a page-number greater than this value
  3413. ** is played back. If one is encountered it is simply skipped.
  3414. */
  3415. static int pagerPlaybackSavepoint( Pager pPager, PagerSavepoint pSavepoint )
  3416. {
  3417. i64 szJ; /* Effective size of the main journal */
  3418. i64 iHdrOff; /* End of first segment of main-journal records */
  3419. int rc = SQLITE_OK; /* Return code */
  3420. Bitvec pDone = null; /* Bitvec to ensure pages played back only once */
  3421. Debug.Assert( pPager.eState != PAGER_ERROR );
  3422. Debug.Assert( pPager.eState >= PAGER_WRITER_LOCKED );
  3423. /* Allocate a bitvec to use to store the set of pages rolled back */
  3424. if ( pSavepoint != null )
  3425. {
  3426. pDone = sqlite3BitvecCreate( pSavepoint.nOrig );
  3427. //if ( null == pDone )
  3428. //{
  3429. // return SQLITE_NOMEM;
  3430. //}
  3431. }
  3432. /* Set the database size back to the value it was before the savepoint
  3433. ** being reverted was opened.
  3434. */
  3435. pPager.dbSize = pSavepoint != null ? pSavepoint.nOrig : pPager.dbOrigSize;
  3436. pPager.changeCountDone = pPager.tempFile;
  3437. if ( !pSavepoint && pagerUseWal( pPager ) )
  3438. {
  3439. return pagerRollbackWal( pPager );
  3440. }
  3441. /* Use pPager.journalOff as the effective size of the main rollback
  3442. ** journal. The actual file might be larger than this in
  3443. ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST. But anything
  3444. ** past pPager.journalOff is off-limits to us.
  3445. */
  3446. szJ = pPager.journalOff;
  3447. Debug.Assert( pagerUseWal( pPager ) == false || szJ == 0 );
  3448. /* Begin by rolling back records from the main journal starting at
  3449. ** PagerSavepoint.iOffset and continuing to the next journal header.
  3450. ** There might be records in the main journal that have a page number
  3451. ** greater than the current database size (pPager.dbSize) but those
  3452. ** will be skipped automatically. Pages are added to pDone as they
  3453. ** are played back.
  3454. */
  3455. if ( pSavepoint != null && !pagerUseWal( pPager ) )
  3456. {
  3457. iHdrOff = pSavepoint.iHdrOffset != 0 ? pSavepoint.iHdrOffset : szJ;
  3458. pPager.journalOff = pSavepoint.iOffset;
  3459. while ( rc == SQLITE_OK && pPager.journalOff < iHdrOff )
  3460. {
  3461. rc = pager_playback_one_page( pPager, ref pPager.journalOff, pDone, 1, 1 );
  3462. }
  3463. Debug.Assert( rc != SQLITE_DONE );
  3464. }
  3465. else
  3466. {
  3467. pPager.journalOff = 0;
  3468. }
  3469. /* Continue rolling back records out of the main journal starting at
  3470. ** the first journal header seen and continuing until the effective end
  3471. ** of the main journal file. Continue to skip out-of-range pages and
  3472. ** continue adding pages rolled back to pDone.
  3473. */
  3474. while ( rc == SQLITE_OK && pPager.journalOff < szJ )
  3475. {
  3476. u32 ii; /* Loop counter */
  3477. u32 nJRec; /* Number of Journal Records */
  3478. u32 dummy;
  3479. rc = readJournalHdr( pPager, 0, (int)szJ, out nJRec, out dummy );
  3480. Debug.Assert( rc != SQLITE_DONE );
  3481. /*
  3482. ** The "pPager.journalHdr+JOURNAL_HDR_SZ(pPager)==pPager.journalOff"
  3483. ** test is related to ticket #2565. See the discussion in the
  3484. ** pager_playback() function for additional information.
  3485. */
  3486. if ( nJRec == 0
  3487. && pPager.journalHdr + JOURNAL_HDR_SZ( pPager ) >= pPager.journalOff
  3488. )
  3489. {
  3490. nJRec = (u32)( ( szJ - pPager.journalOff ) / JOURNAL_PG_SZ( pPager ) );
  3491. }
  3492. for ( ii = 0; rc == SQLITE_OK && ii < nJRec && pPager.journalOff < szJ; ii++ )
  3493. {
  3494. rc = pager_playback_one_page( pPager, ref pPager.journalOff, pDone, 1, 1 );
  3495. }
  3496. Debug.Assert( rc != SQLITE_DONE );
  3497. }
  3498. Debug.Assert( rc != SQLITE_OK || pPager.journalOff >= szJ );
  3499. /* Finally, rollback pages from the sub-journal. Page that were
  3500. ** previously rolled back out of the main journal (and are hence in pDone)
  3501. ** will be skipped. Out-of-range pages are also skipped.
  3502. */
  3503. if ( pSavepoint != null )
  3504. {
  3505. u32 ii; /* Loop counter */
  3506. i64 offset = pSavepoint.iSubRec * ( 4 + pPager.pageSize );
  3507. if ( pagerUseWal( pPager ) )
  3508. {
  3509. rc = sqlite3WalSavepointUndo( pPager.pWal, pSavepoint.aWalData );
  3510. }
  3511. for ( ii = pSavepoint.iSubRec; rc == SQLITE_OK && ii < pPager.nSubRec; ii++ )
  3512. {
  3513. Debug.Assert( offset == ii * ( 4 + pPager.pageSize ) );
  3514. rc = pager_playback_one_page( pPager, ref offset, pDone, 0, 1 );
  3515. }
  3516. Debug.Assert( rc != SQLITE_DONE );
  3517. }
  3518. sqlite3BitvecDestroy( ref pDone );
  3519. if ( rc == SQLITE_OK )
  3520. {
  3521. pPager.journalOff = (int)szJ;
  3522. }
  3523. return rc;
  3524. }
  3525. /*
  3526. ** Change the maximum number of in-memory pages that are allowed.
  3527. */
  3528. static void sqlite3PagerSetCachesize( Pager pPager, int mxPage )
  3529. {
  3530. sqlite3PcacheSetCachesize( pPager.pPCache, mxPage );
  3531. }
  3532. /*
  3533. ** Adjust the robustness of the database to damage due to OS crashes
  3534. ** or power failures by changing the number of syncs()s when writing
  3535. ** the rollback journal. There are three levels:
  3536. **
  3537. ** OFF sqlite3OsSync() is never called. This is the default
  3538. ** for temporary and transient files.
  3539. **
  3540. ** NORMAL The journal is synced once before writes begin on the
  3541. ** database. This is normally adequate protection, but
  3542. ** it is theoretically possible, though very unlikely,
  3543. ** that an inopertune power failure could leave the journal
  3544. ** in a state which would cause damage to the database
  3545. ** when it is rolled back.
  3546. **
  3547. ** FULL The journal is synced twice before writes begin on the
  3548. ** database (with some additional information - the nRec field
  3549. ** of the journal header - being written in between the two
  3550. ** syncs). If we assume that writing a
  3551. ** single disk sector is atomic, then this mode provides
  3552. ** assurance that the journal will not be corrupted to the
  3553. ** point of causing damage to the database during rollback.
  3554. **
  3555. ** The above is for a rollback-journal mode. For WAL mode, OFF continues
  3556. ** to mean that no syncs ever occur. NORMAL means that the WAL is synced
  3557. ** prior to the start of checkpoint and that the database file is synced
  3558. ** at the conclusion of the checkpoint if the entire content of the WAL
  3559. ** was written back into the database. But no sync operations occur for
  3560. ** an ordinary commit in NORMAL mode with WAL. FULL means that the WAL
  3561. ** file is synced following each commit operation, in addition to the
  3562. ** syncs associated with NORMAL.
  3563. **
  3564. ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL. The
  3565. ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
  3566. ** using fcntl(F_FULLFSYNC). SQLITE_SYNC_NORMAL means to do an
  3567. ** ordinary fsync() call. There is no difference between SQLITE_SYNC_FULL
  3568. ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX. But the
  3569. ** synchronous=FULL versus synchronous=NORMAL setting determines when
  3570. ** the xSync primitive is called and is relevant to all platforms.
  3571. **
  3572. ** Numeric values associated with these states are OFF==1, NORMAL=2,
  3573. ** and FULL=3.
  3574. */
  3575. #if !SQLITE_OMIT_PAGER_PRAGMAS
  3576. static void sqlite3PagerSetSafetyLevel(
  3577. Pager pPager, /* The pager to set safety level for */
  3578. int level, /* PRAGMA synchronous. 1=OFF, 2=NORMAL, 3=FULL */
  3579. int bFullFsync, /* PRAGMA fullfsync */
  3580. int bCkptFullFsync /* PRAGMA checkpoint_fullfsync */
  3581. )
  3582. {
  3583. Debug.Assert( level >= 1 && level <= 3 );
  3584. pPager.noSync = ( level == 1 || pPager.tempFile );
  3585. pPager.fullSync = ( level == 3 && !pPager.tempFile );
  3586. if ( pPager.noSync )
  3587. {
  3588. pPager.syncFlags = 0;
  3589. pPager.ckptSyncFlags = 0;
  3590. }
  3591. else if ( bFullFsync != 0 )
  3592. {
  3593. pPager.syncFlags = SQLITE_SYNC_FULL;
  3594. pPager.ckptSyncFlags = SQLITE_SYNC_FULL;
  3595. }
  3596. else if ( bCkptFullFsync != 0 )
  3597. {
  3598. pPager.syncFlags = SQLITE_SYNC_NORMAL;
  3599. pPager.ckptSyncFlags = SQLITE_SYNC_FULL;
  3600. }
  3601. else
  3602. {
  3603. pPager.syncFlags = SQLITE_SYNC_NORMAL;
  3604. pPager.ckptSyncFlags = SQLITE_SYNC_NORMAL;
  3605. }
  3606. }
  3607. #endif
  3608. /*
  3609. ** The following global variable is incremented whenever the library
  3610. ** attempts to open a temporary file. This information is used for
  3611. ** testing and analysis only.
  3612. */
  3613. #if SQLITE_TEST
  3614. #if !TCLSH
  3615. static int sqlite3_opentemp_count = 0;
  3616. #else
  3617. static tcl.lang.Var.SQLITE3_GETSET sqlite3_opentemp_count = new tcl.lang.Var.SQLITE3_GETSET( "sqlite3_opentemp_count" );
  3618. #endif
  3619. #endif
  3620. /*
  3621. ** Open a temporary file.
  3622. **
  3623. ** Write the file descriptor into *pFile. Return SQLITE_OK on success
  3624. ** or some other error code if we fail. The OS will automatically
  3625. ** delete the temporary file when it is closed.
  3626. **
  3627. ** The flags passed to the VFS layer xOpen() call are those specified
  3628. ** by parameter vfsFlags ORed with the following:
  3629. **
  3630. ** SQLITE_OPEN_READWRITE
  3631. ** SQLITE_OPEN_CREATE
  3632. ** SQLITE_OPEN_EXCLUSIVE
  3633. ** SQLITE_OPEN_DELETEONCLOSE
  3634. */
  3635. static int pagerOpentemp(
  3636. Pager pPager, /* The pager object */
  3637. ref sqlite3_file pFile, /* Write the file descriptor here */
  3638. int vfsFlags /* Flags passed through to the VFS */
  3639. )
  3640. {
  3641. int rc; /* Return code */
  3642. #if SQLITE_TEST
  3643. #if !TCLSH
  3644. sqlite3_opentemp_count++; /* Used for testing and analysis only */
  3645. #else
  3646. sqlite3_opentemp_count.iValue++; /* Used for testing and analysis only */
  3647. #endif
  3648. #endif
  3649. vfsFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  3650. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
  3651. int dummy = 0;
  3652. rc = sqlite3OsOpen( pPager.pVfs, null, pFile, vfsFlags, ref dummy );
  3653. Debug.Assert( rc != SQLITE_OK || isOpen( pFile ) );
  3654. return rc;
  3655. }
  3656. /*
  3657. ** Set the busy handler function.
  3658. **
  3659. ** The pager invokes the busy-handler if sqlite3OsLock() returns
  3660. ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
  3661. ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
  3662. ** lock. It does *not* invoke the busy handler when upgrading from
  3663. ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
  3664. ** (which occurs during hot-journal rollback). Summary:
  3665. **
  3666. ** Transition | Invokes xBusyHandler
  3667. ** --------------------------------------------------------
  3668. ** NO_LOCK . SHARED_LOCK | Yes
  3669. ** SHARED_LOCK . RESERVED_LOCK | No
  3670. ** SHARED_LOCK . EXCLUSIVE_LOCK | No
  3671. ** RESERVED_LOCK . EXCLUSIVE_LOCK | Yes
  3672. **
  3673. ** If the busy-handler callback returns non-zero, the lock is
  3674. ** retried. If it returns zero, then the SQLITE_BUSY error is
  3675. ** returned to the caller of the pager API function.
  3676. */
  3677. static void sqlite3PagerSetBusyhandler(
  3678. Pager pPager, /* Pager object */
  3679. dxBusyHandler xBusyHandler, /* Pointer to busy-handler function */
  3680. //int (*xBusyHandler)(void *),
  3681. object pBusyHandlerArg /* Argument to pass to xBusyHandler */
  3682. )
  3683. {
  3684. pPager.xBusyHandler = xBusyHandler;
  3685. pPager.pBusyHandlerArg = pBusyHandlerArg;
  3686. }
  3687. /*
  3688. ** Change the page size used by the Pager object. The new page size
  3689. ** is passed in *pPageSize.
  3690. **
  3691. ** If the pager is in the error state when this function is called, it
  3692. ** is a no-op. The value returned is the error state error code (i.e.
  3693. ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
  3694. **
  3695. ** Otherwise, if all of the following are true:
  3696. **
  3697. ** * the new page size (value of *pPageSize) is valid (a power
  3698. ** of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
  3699. **
  3700. ** * there are no outstanding page references, and
  3701. **
  3702. ** * the database is either not an in-memory database or it is
  3703. ** an in-memory database that currently consists of zero pages.
  3704. **
  3705. ** then the pager object page size is set to *pPageSize.
  3706. **
  3707. ** If the page size is changed, then this function uses sqlite3PagerMalloc()
  3708. ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
  3709. ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
  3710. ** In all other cases, SQLITE_OK is returned.
  3711. **
  3712. ** If the page size is not changed, either because one of the enumerated
  3713. ** conditions above is not true, the pager was in error state when this
  3714. ** function was called, or because the memory allocation attempt failed,
  3715. ** then *pPageSize is set to the old, retained page size before returning.
  3716. */
  3717. static int sqlite3PagerSetPagesize( Pager pPager, ref u32 pPageSize, int nReserve )
  3718. {
  3719. int rc = SQLITE_OK;
  3720. /* It is not possible to do a full assert_pager_state() here, as this
  3721. ** function may be called from within PagerOpen(), before the state
  3722. ** of the Pager object is internally consistent.
  3723. **
  3724. ** At one point this function returned an error if the pager was in
  3725. ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
  3726. ** there is at least one outstanding page reference, this function
  3727. ** is a no-op for that case anyhow.
  3728. */
  3729. u32 pageSize = pPageSize;
  3730. Debug.Assert( pageSize == 0 || ( pageSize >= 512 && pageSize <= SQLITE_MAX_PAGE_SIZE ) );
  3731. if ( ( pPager.memDb == 0 || pPager.dbSize == 0 )
  3732. && sqlite3PcacheRefCount( pPager.pPCache ) == 0
  3733. && pageSize != 0 && pageSize != (u32)pPager.pageSize
  3734. )
  3735. {
  3736. //char *pNew = NULL; /* New temp space */
  3737. i64 nByte = 0;
  3738. if ( pPager.eState > PAGER_OPEN && isOpen( pPager.fd ) )
  3739. {
  3740. rc = sqlite3OsFileSize( pPager.fd, ref nByte );
  3741. }
  3742. //if ( rc == SQLITE_OK )
  3743. //{
  3744. //pNew = (char *)sqlite3PageMalloc(pageSize);
  3745. //if( !pNew ) rc = SQLITE_NOMEM;
  3746. //}
  3747. if ( rc == SQLITE_OK )
  3748. {
  3749. pager_reset( pPager );
  3750. pPager.dbSize = (Pgno)( nByte / pageSize );
  3751. pPager.pageSize = (int)pageSize;
  3752. sqlite3PageFree( ref pPager.pTmpSpace );
  3753. pPager.pTmpSpace = sqlite3Malloc( pageSize );// pNew;
  3754. sqlite3PcacheSetPageSize( pPager.pPCache, (int)pageSize );
  3755. }
  3756. }
  3757. pPageSize = (u32)pPager.pageSize;
  3758. if ( rc == SQLITE_OK )
  3759. {
  3760. if ( nReserve < 0 )
  3761. nReserve = pPager.nReserve;
  3762. Debug.Assert( nReserve >= 0 && nReserve < 1000 );
  3763. pPager.nReserve = (i16)nReserve;
  3764. pagerReportSize( pPager );
  3765. }
  3766. return rc;
  3767. }
  3768. /*
  3769. ** Return a pointer to the "temporary page" buffer held internally
  3770. ** by the pager. This is a buffer that is big enough to hold the
  3771. ** entire content of a database page. This buffer is used internally
  3772. ** during rollback and will be overwritten whenever a rollback
  3773. ** occurs. But other modules are free to use it too, as long as
  3774. ** no rollbacks are happening.
  3775. */
  3776. static byte[] sqlite3PagerTempSpace( Pager pPager )
  3777. {
  3778. return pPager.pTmpSpace;
  3779. }
  3780. /*
  3781. ** Attempt to set the maximum database page count if mxPage is positive.
  3782. ** Make no changes if mxPage is zero or negative. And never reduce the
  3783. ** maximum page count below the current size of the database.
  3784. **
  3785. ** Regardless of mxPage, return the current maximum page count.
  3786. */
  3787. static Pgno sqlite3PagerMaxPageCount( Pager pPager, int mxPage )
  3788. {
  3789. if ( mxPage > 0 )
  3790. {
  3791. pPager.mxPgno = (Pgno)mxPage;
  3792. }
  3793. Debug.Assert( pPager.eState != PAGER_OPEN ); /* Called only by OP_MaxPgcnt */
  3794. Debug.Assert( pPager.mxPgno >= pPager.dbSize ); /* OP_MaxPgcnt enforces this */
  3795. return pPager.mxPgno;
  3796. }
  3797. /*
  3798. ** The following set of routines are used to disable the simulated
  3799. ** I/O error mechanism. These routines are used to avoid simulated
  3800. ** errors in places where we do not care about errors.
  3801. **
  3802. ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
  3803. ** and generate no code.
  3804. */
  3805. #if SQLITE_TEST
  3806. //extern int sqlite3_io_error_pending;
  3807. //extern int sqlite3_io_error_hit;
  3808. static int saved_cnt;
  3809. static void disable_simulated_io_errors()
  3810. {
  3811. #if !TCLSH
  3812. saved_cnt = sqlite3_io_error_pending;
  3813. sqlite3_io_error_pending = -1;
  3814. #else
  3815. saved_cnt = sqlite3_io_error_pending.iValue;
  3816. sqlite3_io_error_pending.iValue = -1;
  3817. #endif
  3818. }
  3819. static void enable_simulated_io_errors()
  3820. {
  3821. #if !TCLSH
  3822. sqlite3_io_error_pending = saved_cnt;
  3823. #else
  3824. sqlite3_io_error_pending.iValue = saved_cnt;
  3825. #endif
  3826. }
  3827. #else
  3828. //# define disable_simulated_io_errors()
  3829. //# define enable_simulated_io_errors()
  3830. #endif
  3831. /*
  3832. ** Read the first N bytes from the beginning of the file into memory
  3833. ** that pDest points to.
  3834. **
  3835. ** If the pager was opened on a transient file (zFilename==""), or
  3836. ** opened on a file less than N bytes in size, the output buffer is
  3837. ** zeroed and SQLITE_OK returned. The rationale for this is that this
  3838. ** function is used to read database headers, and a new transient or
  3839. ** zero sized database has a header than consists entirely of zeroes.
  3840. **
  3841. ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
  3842. ** the error code is returned to the caller and the contents of the
  3843. ** output buffer undefined.
  3844. */
  3845. static int sqlite3PagerReadFileheader( Pager pPager, int N, byte[] pDest )
  3846. {
  3847. int rc = SQLITE_OK;
  3848. Array.Clear( pDest, 0, N ); //memset(pDest, 0, N);
  3849. Debug.Assert( isOpen( pPager.fd ) || pPager.tempFile );
  3850. /* This routine is only called by btree immediately after creating
  3851. ** the Pager object. There has not been an opportunity to transition
  3852. ** to WAL mode yet.
  3853. */
  3854. Debug.Assert( !pagerUseWal( pPager ) );
  3855. if ( isOpen( pPager.fd ) )
  3856. {
  3857. IOTRACE( "DBHDR %p 0 %d\n", pPager, N );
  3858. rc = sqlite3OsRead( pPager.fd, pDest, N, 0 );
  3859. if ( rc == SQLITE_IOERR_SHORT_READ )
  3860. {
  3861. rc = SQLITE_OK;
  3862. }
  3863. }
  3864. return rc;
  3865. }
  3866. /*
  3867. ** This function may only be called when a read-transaction is open on
  3868. ** the pager. It returns the total number of pages in the database.
  3869. **
  3870. ** However, if the file is between 1 and <page-size> bytes in size, then
  3871. ** this is considered a 1 page file.
  3872. */
  3873. static void sqlite3PagerPagecount( Pager pPager, out Pgno pnPage )
  3874. {
  3875. Debug.Assert( pPager.eState >= PAGER_READER );
  3876. Debug.Assert( pPager.eState != PAGER_WRITER_FINISHED );
  3877. pnPage = pPager.dbSize;
  3878. }
  3879. /*
  3880. ** Try to obtain a lock of type locktype on the database file. If
  3881. ** a similar or greater lock is already held, this function is a no-op
  3882. ** (returning SQLITE_OK immediately).
  3883. **
  3884. ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
  3885. ** the busy callback if the lock is currently not available. Repeat
  3886. ** until the busy callback returns false or until the attempt to
  3887. ** obtain the lock succeeds.
  3888. **
  3889. ** Return SQLITE_OK on success and an error code if we cannot obtain
  3890. ** the lock. If the lock is obtained successfully, set the Pager.state
  3891. ** variable to locktype before returning.
  3892. */
  3893. static int pager_wait_on_lock( Pager pPager, int locktype )
  3894. {
  3895. int rc; /* Return code */
  3896. /* Check that this is either a no-op (because the requested lock is
  3897. ** already held, or one of the transistions that the busy-handler
  3898. ** may be invoked during, according to the comment above
  3899. ** sqlite3PagerSetBusyhandler().
  3900. */
  3901. Debug.Assert( ( pPager.eLock >= locktype )
  3902. || ( pPager.eLock == NO_LOCK && locktype == SHARED_LOCK )
  3903. || ( pPager.eLock == RESERVED_LOCK && locktype == EXCLUSIVE_LOCK )
  3904. );
  3905. do
  3906. {
  3907. rc = pagerLockDb( pPager, locktype );
  3908. } while ( rc == SQLITE_BUSY && pPager.xBusyHandler( pPager.pBusyHandlerArg ) != 0 );
  3909. return rc;
  3910. }
  3911. /*
  3912. ** Function assertTruncateConstraint(pPager) checks that one of the
  3913. ** following is true for all dirty pages currently in the page-cache:
  3914. **
  3915. ** a) The page number is less than or equal to the size of the
  3916. ** current database image, in pages, OR
  3917. **
  3918. ** b) if the page content were written at this time, it would not
  3919. ** be necessary to write the current content out to the sub-journal
  3920. ** (as determined by function subjRequiresPage()).
  3921. **
  3922. ** If the condition asserted by this function were not true, and the
  3923. ** dirty page were to be discarded from the cache via the pagerStress()
  3924. ** routine, pagerStress() would not write the current page content to
  3925. ** the database file. If a savepoint transaction were rolled back after
  3926. ** this happened, the correct behaviour would be to restore the current
  3927. ** content of the page. However, since this content is not present in either
  3928. ** the database file or the portion of the rollback journal and
  3929. ** sub-journal rolled back the content could not be restored and the
  3930. ** database image would become corrupt. It is therefore fortunate that
  3931. ** this circumstance cannot arise.
  3932. */
  3933. #if SQLITE_DEBUG
  3934. static void assertTruncateConstraintCb( PgHdr pPg )
  3935. {
  3936. Debug.Assert( ( pPg.flags & PGHDR_DIRTY ) != 0 );
  3937. Debug.Assert( !subjRequiresPage( pPg ) || pPg.pgno <= pPg.pPager.dbSize );
  3938. }
  3939. static void assertTruncateConstraint( Pager pPager )
  3940. {
  3941. sqlite3PcacheIterateDirty( pPager.pPCache, assertTruncateConstraintCb );
  3942. }
  3943. #else
  3944. //# define assertTruncateConstraint(pPager)
  3945. static void assertTruncateConstraintCb(PgHdr pPg) { }
  3946. static void assertTruncateConstraint(Pager pPager) { }
  3947. #endif
  3948. /*
  3949. ** Truncate the in-memory database file image to nPage pages. This
  3950. ** function does not actually modify the database file on disk. It
  3951. ** just sets the internal state of the pager object so that the
  3952. ** truncation will be done when the current transaction is committed.
  3953. */
  3954. static void sqlite3PagerTruncateImage( Pager pPager, u32 nPage )
  3955. {
  3956. Debug.Assert( pPager.dbSize >= nPage );
  3957. Debug.Assert( pPager.eState >= PAGER_WRITER_CACHEMOD );
  3958. pPager.dbSize = nPage;
  3959. assertTruncateConstraint( pPager );
  3960. }
  3961. /*
  3962. ** This function is called before attempting a hot-journal rollback. It
  3963. ** syncs the journal file to disk, then sets pPager.journalHdr to the
  3964. ** size of the journal file so that the pager_playback() routine knows
  3965. ** that the entire journal file has been synced.
  3966. **
  3967. ** Syncing a hot-journal to disk before attempting to roll it back ensures
  3968. ** that if a power-failure occurs during the rollback, the process that
  3969. ** attempts rollback following system recovery sees the same journal
  3970. ** content as this process.
  3971. **
  3972. ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
  3973. ** an SQLite error code.
  3974. */
  3975. static int pagerSyncHotJournal( Pager pPager )
  3976. {
  3977. int rc = SQLITE_OK;
  3978. if ( !pPager.noSync )
  3979. {
  3980. rc = sqlite3OsSync( pPager.jfd, SQLITE_SYNC_NORMAL );
  3981. }
  3982. if ( rc == SQLITE_OK )
  3983. {
  3984. rc = sqlite3OsFileSize( pPager.jfd, ref pPager.journalHdr );
  3985. }
  3986. return rc;
  3987. }
  3988. /*
  3989. ** Shutdown the page cache. Free all memory and close all files.
  3990. **
  3991. ** If a transaction was in progress when this routine is called, that
  3992. ** transaction is rolled back. All outstanding pages are invalidated
  3993. ** and their memory is freed. Any attempt to use a page associated
  3994. ** with this page cache after this function returns will likely
  3995. ** result in a coredump.
  3996. **
  3997. ** This function always succeeds. If a transaction is active an attempt
  3998. ** is made to roll it back. If an error occurs during the rollback
  3999. ** a hot journal may be left in the filesystem but no error is returned
  4000. ** to the caller.
  4001. */
  4002. static int sqlite3PagerClose( Pager pPager )
  4003. {
  4004. #if SQLITE_TEST
  4005. disable_simulated_io_errors();
  4006. #endif
  4007. sqlite3BeginBenignMalloc();
  4008. /* pPager.errCode = 0; */
  4009. pPager.exclusiveMode = false;
  4010. #if !SQLITE_OMIT_WAL
  4011. u8[] pTmp = pPager.pTmpSpace;
  4012. sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
  4013. pPager.pWal = 0;
  4014. #endif
  4015. pager_reset( pPager );
  4016. #if SQLITE_OMIT_MEMORYDB
  4017. if ( 1 == MEMDB )
  4018. #else
  4019. if ( 1 == pPager.memDb )
  4020. #endif
  4021. {
  4022. pager_unlock( pPager );
  4023. }
  4024. else
  4025. {
  4026. /* If it is open, sync the journal file before calling UnlockAndRollback.
  4027. ** If this is not done, then an unsynced portion of the open journal
  4028. ** file may be played back into the database. If a power failure occurs
  4029. ** while this is happening, the database could become corrupt.
  4030. **
  4031. ** If an error occurs while trying to sync the journal, shift the pager
  4032. ** into the ERROR state. This causes UnlockAndRollback to unlock the
  4033. ** database and close the journal file without attempting to roll it
  4034. ** back or finalize it. The next database user will have to do hot-journal
  4035. ** rollback before accessing the database file.
  4036. */
  4037. if ( isOpen( pPager.jfd ) )
  4038. {
  4039. pager_error( pPager, pagerSyncHotJournal( pPager ) );
  4040. }
  4041. pagerUnlockAndRollback( pPager );
  4042. }
  4043. sqlite3EndBenignMalloc();
  4044. #if SQLITE_TEST
  4045. enable_simulated_io_errors();
  4046. #endif
  4047. PAGERTRACE( "CLOSE %d\n", PAGERID( pPager ) );
  4048. IOTRACE( "CLOSE %p\n", pPager );
  4049. sqlite3OsClose( pPager.jfd );
  4050. sqlite3OsClose( pPager.fd );
  4051. //sqlite3_free( ref pTmp );
  4052. sqlite3PcacheClose( pPager.pPCache );
  4053. #if SQLITE_HAS_CODEC
  4054. if ( pPager.xCodecFree != null )
  4055. pPager.xCodecFree( ref pPager.pCodec );
  4056. #endif
  4057. Debug.Assert( null == pPager.aSavepoint && !pPager.pInJournal );
  4058. Debug.Assert( !isOpen( pPager.jfd ) && !isOpen( pPager.sjfd ) );
  4059. //sqlite3_free( ref pPager );
  4060. return SQLITE_OK;
  4061. }
  4062. #if !NDEBUG || SQLITE_TEST
  4063. /*
  4064. ** Return the page number for page pPg.
  4065. */
  4066. static Pgno sqlite3PagerPagenumber( DbPage pPg )
  4067. {
  4068. return pPg.pgno;
  4069. }
  4070. #else
  4071. static Pgno sqlite3PagerPagenumber( DbPage pPg ) { return pPg.pgno; }
  4072. #endif
  4073. /*
  4074. ** Increment the reference count for page pPg.
  4075. */
  4076. static void sqlite3PagerRef( DbPage pPg )
  4077. {
  4078. sqlite3PcacheRef( pPg );
  4079. }
  4080. /*
  4081. ** Sync the journal. In other words, make sure all the pages that have
  4082. ** been written to the journal have actually reached the surface of the
  4083. ** disk and can be restored in the event of a hot-journal rollback.
  4084. **
  4085. ** If the Pager.noSync flag is set, then this function is a no-op.
  4086. ** Otherwise, the actions required depend on the journal-mode and the
  4087. ** device characteristics of the the file-system, as follows:
  4088. **
  4089. ** * If the journal file is an in-memory journal file, no action need
  4090. ** be taken.
  4091. **
  4092. ** * Otherwise, if the device does not support the SAFE_APPEND property,
  4093. ** then the nRec field of the most recently written journal header
  4094. ** is updated to contain the number of journal records that have
  4095. ** been written following it. If the pager is operating in full-sync
  4096. ** mode, then the journal file is synced before this field is updated.
  4097. **
  4098. ** * If the device does not support the SEQUENTIAL property, then
  4099. ** journal file is synced.
  4100. **
  4101. ** Or, in pseudo-code:
  4102. **
  4103. ** if( NOT <in-memory journal> ){
  4104. ** if( NOT SAFE_APPEND ){
  4105. ** if( <full-sync mode> ) xSync(<journal file>);
  4106. ** <update nRec field>
  4107. ** }
  4108. ** if( NOT SEQUENTIAL ) xSync(<journal file>);
  4109. ** }
  4110. **
  4111. ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
  4112. ** page currently held in memory before returning SQLITE_OK. If an IO
  4113. ** error is encountered, then the IO error code is returned to the caller.
  4114. */
  4115. static int syncJournal( Pager pPager, int newHdr )
  4116. {
  4117. int rc = SQLITE_OK;
  4118. Debug.Assert( pPager.eState == PAGER_WRITER_CACHEMOD
  4119. || pPager.eState == PAGER_WRITER_DBMOD
  4120. );
  4121. Debug.Assert( assert_pager_state( pPager ) );
  4122. Debug.Assert( !pagerUseWal( pPager ) );
  4123. rc = sqlite3PagerExclusiveLock( pPager );
  4124. if ( rc != SQLITE_OK )
  4125. return rc;
  4126. if ( !pPager.noSync )
  4127. {
  4128. Debug.Assert( !pPager.tempFile );
  4129. if ( isOpen( pPager.jfd ) && pPager.journalMode != PAGER_JOURNALMODE_MEMORY )
  4130. {
  4131. int iDc = sqlite3OsDeviceCharacteristics( pPager.fd );
  4132. Debug.Assert( isOpen( pPager.jfd ) );
  4133. if ( 0 == ( iDc & SQLITE_IOCAP_SAFE_APPEND ) )
  4134. {
  4135. /* This block deals with an obscure problem. If the last connection
  4136. ** that wrote to this database was operating in persistent-journal
  4137. ** mode, then the journal file may at this point actually be larger
  4138. ** than Pager.journalOff bytes. If the next thing in the journal
  4139. ** file happens to be a journal-header (written as part of the
  4140. ** previous connection's transaction), and a crash or power-failure
  4141. ** occurs after nRec is updated but before this connection writes
  4142. ** anything else to the journal file (or commits/rolls back its
  4143. ** transaction), then SQLite may become confused when doing the
  4144. ** hot-journal rollback following recovery. It may roll back all
  4145. ** of this connections data, then proceed to rolling back the old,
  4146. ** out-of-date data that follows it. Database corruption.
  4147. **
  4148. ** To work around this, if the journal file does appear to contain
  4149. ** a valid header following Pager.journalOff, then write a 0x00
  4150. ** byte to the start of it to prevent it from being recognized.
  4151. **
  4152. ** Variable iNextHdrOffset is set to the offset at which this
  4153. ** problematic header will occur, if it exists. aMagic is used
  4154. ** as a temporary buffer to inspect the first couple of bytes of
  4155. ** the potential journal header.
  4156. */
  4157. i64 iNextHdrOffset;
  4158. u8[] aMagic = new u8[8];
  4159. u8[] zHeader = new u8[aJournalMagic.Length + 4];
  4160. aJournalMagic.CopyTo( zHeader, 0 );// memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  4161. put32bits( zHeader, aJournalMagic.Length, pPager.nRec );
  4162. iNextHdrOffset = journalHdrOffset( pPager );
  4163. rc = sqlite3OsRead( pPager.jfd, aMagic, 8, iNextHdrOffset );
  4164. if ( rc == SQLITE_OK && 0 == memcmp( aMagic, aJournalMagic, 8 ) )
  4165. {
  4166. u8[] zerobyte = new u8[1];
  4167. rc = sqlite3OsWrite( pPager.jfd, zerobyte, 1, iNextHdrOffset );
  4168. }
  4169. if ( rc != SQLITE_OK && rc != SQLITE_IOERR_SHORT_READ )
  4170. {
  4171. return rc;
  4172. }
  4173. /* Write the nRec value into the journal file header. If in
  4174. ** full-synchronous mode, sync the journal first. This ensures that
  4175. ** all data has really hit the disk before nRec is updated to mark
  4176. ** it as a candidate for rollback.
  4177. **
  4178. ** This is not required if the persistent media supports the
  4179. ** SAFE_APPEND property. Because in this case it is not possible
  4180. ** for garbage data to be appended to the file, the nRec field
  4181. ** is populated with 0xFFFFFFFF when the journal header is written
  4182. ** and never needs to be updated.
  4183. */
  4184. if ( pPager.fullSync && 0 == ( iDc & SQLITE_IOCAP_SEQUENTIAL ) )
  4185. {
  4186. PAGERTRACE( "SYNC journal of %d\n", PAGERID( pPager ) );
  4187. IOTRACE( "JSYNC %p\n", pPager );
  4188. rc = sqlite3OsSync( pPager.jfd, pPager.syncFlags );
  4189. if ( rc != SQLITE_OK )
  4190. return rc;
  4191. }
  4192. IOTRACE( "JHDR %p %lld\n", pPager, pPager.journalHdr );
  4193. rc = sqlite3OsWrite(
  4194. pPager.jfd, zHeader, zHeader.Length, pPager.journalHdr
  4195. );
  4196. if ( rc != SQLITE_OK )
  4197. return rc;
  4198. }
  4199. if ( 0 == ( iDc & SQLITE_IOCAP_SEQUENTIAL ) )
  4200. {
  4201. PAGERTRACE( "SYNC journal of %d\n", PAGERID( pPager ) );
  4202. IOTRACE( "JSYNC %p\n", pPager );
  4203. rc = sqlite3OsSync( pPager.jfd, pPager.syncFlags |
  4204. ( pPager.syncFlags == SQLITE_SYNC_FULL ? SQLITE_SYNC_DATAONLY : 0 )
  4205. );
  4206. if ( rc != SQLITE_OK )
  4207. return rc;
  4208. }
  4209. pPager.journalHdr = pPager.journalOff;
  4210. if ( newHdr != 0 && 0 == ( iDc & SQLITE_IOCAP_SAFE_APPEND ) )
  4211. {
  4212. pPager.nRec = 0;
  4213. rc = writeJournalHdr( pPager );
  4214. if ( rc != SQLITE_OK )
  4215. return rc;
  4216. }
  4217. }
  4218. else
  4219. {
  4220. pPager.journalHdr = pPager.journalOff;
  4221. }
  4222. }
  4223. /* Unless the pager is in noSync mode, the journal file was just
  4224. ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
  4225. ** all pages.
  4226. */
  4227. sqlite3PcacheClearSyncFlags( pPager.pPCache );
  4228. pPager.eState = PAGER_WRITER_DBMOD;
  4229. Debug.Assert( assert_pager_state( pPager ) );
  4230. return SQLITE_OK;
  4231. }
  4232. /*
  4233. ** The argument is the first in a linked list of dirty pages connected
  4234. ** by the PgHdr.pDirty pointer. This function writes each one of the
  4235. ** in-memory pages in the list to the database file. The argument may
  4236. ** be NULL, representing an empty list. In this case this function is
  4237. ** a no-op.
  4238. **
  4239. ** The pager must hold at least a RESERVED lock when this function
  4240. ** is called. Before writing anything to the database file, this lock
  4241. ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
  4242. ** SQLITE_BUSY is returned and no data is written to the database file.
  4243. **
  4244. ** If the pager is a temp-file pager and the actual file-system file
  4245. ** is not yet open, it is created and opened before any data is
  4246. ** written out.
  4247. **
  4248. ** Once the lock has been upgraded and, if necessary, the file opened,
  4249. ** the pages are written out to the database file in list order. Writing
  4250. ** a page is skipped if it meets either of the following criteria:
  4251. **
  4252. ** * The page number is greater than Pager.dbSize, or
  4253. ** * The PGHDR_DONT_WRITE flag is set on the page.
  4254. **
  4255. ** If writing out a page causes the database file to grow, Pager.dbFileSize
  4256. ** is updated accordingly. If page 1 is written out, then the value cached
  4257. ** in Pager.dbFileVers[] is updated to match the new value stored in
  4258. ** the database file.
  4259. **
  4260. ** If everything is successful, SQLITE_OK is returned. If an IO error
  4261. ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
  4262. ** be obtained, SQLITE_BUSY is returned.
  4263. */
  4264. static int pager_write_pagelist( Pager pPager, PgHdr pList )
  4265. {
  4266. int rc = SQLITE_OK; /* Return code */
  4267. /* This function is only called for rollback pagers in WRITER_DBMOD state. */
  4268. Debug.Assert( !pagerUseWal( pPager ) );
  4269. Debug.Assert( pPager.eState == PAGER_WRITER_DBMOD );
  4270. Debug.Assert( pPager.eLock == EXCLUSIVE_LOCK );
  4271. /* If the file is a temp-file has not yet been opened, open it now. It
  4272. ** is not possible for rc to be other than SQLITE_OK if this branch
  4273. ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
  4274. */
  4275. if ( !isOpen( pPager.fd ) )
  4276. {
  4277. Debug.Assert( pPager.tempFile && rc == SQLITE_OK );
  4278. rc = pagerOpentemp( pPager, ref pPager.fd, (int)pPager.vfsFlags );
  4279. }
  4280. /* Before the first write, give the VFS a hint of what the final
  4281. ** file size will be.
  4282. */
  4283. Debug.Assert( rc != SQLITE_OK || isOpen( pPager.fd ) );
  4284. if ( rc == SQLITE_OK && pPager.dbSize > pPager.dbHintSize )
  4285. {
  4286. sqlite3_int64 szFile = pPager.pageSize * (sqlite3_int64)pPager.dbSize;
  4287. sqlite3OsFileControl( pPager.fd, SQLITE_FCNTL_SIZE_HINT, ref szFile );
  4288. pPager.dbHintSize = pPager.dbSize;
  4289. }
  4290. while ( rc == SQLITE_OK && pList )
  4291. {
  4292. Pgno pgno = pList.pgno;
  4293. /* If there are dirty pages in the page cache with page numbers greater
  4294. ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
  4295. ** make the file smaller (presumably by auto-vacuum code). Do not write
  4296. ** any such pages to the file.
  4297. **
  4298. ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
  4299. ** set (set by sqlite3PagerDontWrite()).
  4300. */
  4301. if ( pList.pgno <= pPager.dbSize && 0 == ( pList.flags & PGHDR_DONT_WRITE ) )
  4302. {
  4303. i64 offset = ( pList.pgno - 1 ) * (i64)pPager.pageSize; /* Offset to write */
  4304. byte[] pData = null; /* Data to write */
  4305. Debug.Assert( ( pList.flags & PGHDR_NEED_SYNC ) == 0 );
  4306. if ( pList.pgno == 1 )
  4307. pager_write_changecounter( pList );
  4308. /* Encode the database */
  4309. if ( CODEC2( pPager, pList.pData, pgno, SQLITE_ENCRYPT_WRITE_CTX, ref pData ) )
  4310. return SQLITE_NOMEM;// CODEC2(pPager, pList.pData, pgno, 6, return SQLITE_NOMEM, pData);
  4311. /* Write out the page data. */
  4312. rc = sqlite3OsWrite( pPager.fd, pData, pPager.pageSize, offset );
  4313. /* If page 1 was just written, update Pager.dbFileVers to match
  4314. ** the value now stored in the database file. If writing this
  4315. ** page caused the database file to grow, update dbFileSize.
  4316. */
  4317. if ( pgno == 1 )
  4318. {
  4319. Buffer.BlockCopy( pData, 24, pPager.dbFileVers, 0, pPager.dbFileVers.Length );// memcpy(pPager.dbFileVers, pData[24], pPager.dbFileVers).Length;
  4320. }
  4321. if ( pgno > pPager.dbFileSize )
  4322. {
  4323. pPager.dbFileSize = pgno;
  4324. }
  4325. /* Update any backup objects copying the contents of this pager. */
  4326. sqlite3BackupUpdate( pPager.pBackup, pgno, pList.pData );
  4327. PAGERTRACE( "STORE %d page %d hash(%08x)\n",
  4328. PAGERID( pPager ), pgno, pager_pagehash( pList ) );
  4329. IOTRACE( "PGOUT %p %d\n", pPager, pgno );
  4330. #if SQLITE_TEST
  4331. #if !TCLSH
  4332. PAGER_INCR( ref sqlite3_pager_writedb_count );
  4333. #else
  4334. int iValue;
  4335. iValue = sqlite3_pager_writedb_count.iValue;
  4336. PAGER_INCR( ref iValue );
  4337. sqlite3_pager_writedb_count.iValue = iValue;
  4338. #endif
  4339. PAGER_INCR( ref pPager.nWrite );
  4340. #endif
  4341. }
  4342. else
  4343. {
  4344. PAGERTRACE( "NOSTORE %d page %d\n", PAGERID( pPager ), pgno );
  4345. }
  4346. pager_set_pagehash( pList );
  4347. pList = pList.pDirty;
  4348. }
  4349. return rc;
  4350. }
  4351. /*
  4352. ** Ensure that the sub-journal file is open. If it is already open, this
  4353. ** function is a no-op.
  4354. **
  4355. ** SQLITE_OK is returned if everything goes according to plan. An
  4356. ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
  4357. ** fails.
  4358. */
  4359. static int openSubJournal( Pager pPager )
  4360. {
  4361. int rc = SQLITE_OK;
  4362. if ( !isOpen( pPager.sjfd ) )
  4363. {
  4364. if ( pPager.journalMode == PAGER_JOURNALMODE_MEMORY || pPager.subjInMemory != 0 )
  4365. {
  4366. sqlite3MemJournalOpen( pPager.sjfd );
  4367. }
  4368. else
  4369. {
  4370. rc = pagerOpentemp( pPager, ref pPager.sjfd, SQLITE_OPEN_SUBJOURNAL );
  4371. }
  4372. }
  4373. return rc;
  4374. }
  4375. /*
  4376. ** Append a record of the current state of page pPg to the sub-journal.
  4377. ** It is the callers responsibility to use subjRequiresPage() to check
  4378. ** that it is really required before calling this function.
  4379. **
  4380. ** If successful, set the bit corresponding to pPg.pgno in the bitvecs
  4381. ** for all open savepoints before returning.
  4382. **
  4383. ** This function returns SQLITE_OK if everything is successful, an IO
  4384. ** error code if the attempt to write to the sub-journal fails, or
  4385. ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
  4386. ** bitvec.
  4387. */
  4388. static int subjournalPage( PgHdr pPg )
  4389. {
  4390. int rc = SQLITE_OK;
  4391. Pager pPager = pPg.pPager;
  4392. if ( pPager.journalMode != PAGER_JOURNALMODE_OFF )
  4393. {
  4394. /* Open the sub-journal, if it has not already been opened */
  4395. Debug.Assert( pPager.useJournal != 0 );
  4396. Debug.Assert( isOpen( pPager.jfd ) || pagerUseWal( pPager ) );
  4397. Debug.Assert( isOpen( pPager.sjfd ) || pPager.nSubRec == 0 );
  4398. Debug.Assert( pagerUseWal( pPager )
  4399. || pageInJournal( pPg )
  4400. || pPg.pgno > pPager.dbOrigSize
  4401. );
  4402. rc = openSubJournal( pPager );
  4403. /* If the sub-journal was opened successfully (or was already open),
  4404. ** write the journal record into the file. */
  4405. if ( rc == SQLITE_OK )
  4406. {
  4407. byte[] pData = pPg.pData;
  4408. i64 offset = pPager.nSubRec * ( 4 + pPager.pageSize );
  4409. byte[] pData2 = null;
  4410. if ( CODEC2( pPager, pData, pPg.pgno, SQLITE_ENCRYPT_READ_CTX, ref pData2 ) )
  4411. return SQLITE_NOMEM;//CODEC2(pPager, pData, pPg.pgno, 7, return SQLITE_NOMEM, pData2);
  4412. PAGERTRACE( "STMT-JOURNAL %d page %d\n", PAGERID( pPager ), pPg.pgno );
  4413. rc = write32bits( pPager.sjfd, offset, pPg.pgno );
  4414. if ( rc == SQLITE_OK )
  4415. {
  4416. rc = sqlite3OsWrite( pPager.sjfd, pData2, pPager.pageSize, offset + 4 );
  4417. }
  4418. }
  4419. }
  4420. if ( rc == SQLITE_OK )
  4421. {
  4422. pPager.nSubRec++;
  4423. Debug.Assert( pPager.nSavepoint > 0 );
  4424. rc = addToSavepointBitvecs( pPager, pPg.pgno );
  4425. }
  4426. return rc;
  4427. }
  4428. /*
  4429. ** This function is called by the pcache layer when it has reached some
  4430. ** soft memory limit. The first argument is a pointer to a Pager object
  4431. ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
  4432. ** database). The second argument is a reference to a page that is
  4433. ** currently dirty but has no outstanding references. The page
  4434. ** is always associated with the Pager object passed as the first
  4435. ** argument.
  4436. **
  4437. ** The job of this function is to make pPg clean by writing its contents
  4438. ** out to the database file, if possible. This may involve syncing the
  4439. ** journal file.
  4440. **
  4441. ** If successful, sqlite3PcacheMakeClean() is called on the page and
  4442. ** SQLITE_OK returned. If an IO error occurs while trying to make the
  4443. ** page clean, the IO error code is returned. If the page cannot be
  4444. ** made clean for some other reason, but no error occurs, then SQLITE_OK
  4445. ** is returned by sqlite3PcacheMakeClean() is not called.
  4446. */
  4447. static int pagerStress( object p, PgHdr pPg )
  4448. {
  4449. Pager pPager = (Pager)p;
  4450. int rc = SQLITE_OK;
  4451. Debug.Assert( pPg.pPager == pPager );
  4452. Debug.Assert( ( pPg.flags & PGHDR_DIRTY ) != 0 );
  4453. /* The doNotSyncSpill flag is set during times when doing a sync of
  4454. ** journal (and adding a new header) is not allowed. This occurs
  4455. ** during calls to sqlite3PagerWrite() while trying to journal multiple
  4456. ** pages belonging to the same sector.
  4457. **
  4458. ** The doNotSpill flag inhibits all cache spilling regardless of whether
  4459. ** or not a sync is required. This is set during a rollback.
  4460. **
  4461. ** Spilling is also prohibited when in an error state since that could
  4462. ** lead to database corruption. In the current implementaton it
  4463. ** is impossible for sqlite3PCacheFetch() to be called with createFlag==1
  4464. ** while in the error state, hence it is impossible for this routine to
  4465. ** be called in the error state. Nevertheless, we include a NEVER()
  4466. ** test for the error state as a safeguard against future changes.
  4467. */
  4468. if ( NEVER( pPager.errCode != 0 ) )
  4469. return SQLITE_OK;
  4470. if ( pPager.doNotSpill != 0 )
  4471. return SQLITE_OK;
  4472. if ( pPager.doNotSyncSpill != 0 && ( pPg.flags & PGHDR_NEED_SYNC ) != 0 )
  4473. {
  4474. return SQLITE_OK;
  4475. }
  4476. pPg.pDirty = null;
  4477. if ( pagerUseWal( pPager ) )
  4478. {
  4479. /* Write a single frame for this page to the log. */
  4480. if ( subjRequiresPage( pPg ) )
  4481. {
  4482. rc = subjournalPage( pPg );
  4483. }
  4484. if ( rc == SQLITE_OK )
  4485. {
  4486. rc = pagerWalFrames( pPager, pPg, 0, 0, 0 );
  4487. }
  4488. }
  4489. else
  4490. {
  4491. /* Sync the journal file if required. */
  4492. if ( ( pPg.flags & PGHDR_NEED_SYNC ) != 0
  4493. || pPager.eState == PAGER_WRITER_CACHEMOD
  4494. )
  4495. {
  4496. rc = syncJournal( pPager, 1 );
  4497. }
  4498. /* If the page number of this page is larger than the current size of
  4499. ** the database image, it may need to be written to the sub-journal.
  4500. ** This is because the call to pager_write_pagelist() below will not
  4501. ** actually write data to the file in this case.
  4502. **
  4503. ** Consider the following sequence of events:
  4504. **
  4505. ** BEGIN;
  4506. ** <journal page X>
  4507. ** <modify page X>
  4508. ** SAVEPOINT sp;
  4509. ** <shrink database file to Y pages>
  4510. ** pagerStress(page X)
  4511. ** ROLLBACK TO sp;
  4512. **
  4513. ** If (X>Y), then when pagerStress is called page X will not be written
  4514. ** out to the database file, but will be dropped from the cache. Then,
  4515. ** following the "ROLLBACK TO sp" statement, reading page X will read
  4516. ** data from the database file. This will be the copy of page X as it
  4517. ** was when the transaction started, not as it was when "SAVEPOINT sp"
  4518. ** was executed.
  4519. **
  4520. ** The solution is to write the current data for page X into the
  4521. ** sub-journal file now (if it is not already there), so that it will
  4522. ** be restored to its current value when the "ROLLBACK TO sp" is
  4523. ** executed.
  4524. */
  4525. if ( NEVER(
  4526. rc == SQLITE_OK && pPg.pgno > pPager.dbSize && subjRequiresPage( pPg )
  4527. ) )
  4528. {
  4529. rc = subjournalPage( pPg );
  4530. }
  4531. /* Write the contents of the page out to the database file. */
  4532. if ( rc == SQLITE_OK )
  4533. {
  4534. Debug.Assert( ( pPg.flags & PGHDR_NEED_SYNC ) == 0 );
  4535. rc = pager_write_pagelist( pPager, pPg );
  4536. }
  4537. }
  4538. /* Mark the page as clean. */
  4539. if ( rc == SQLITE_OK )
  4540. {
  4541. PAGERTRACE( "STRESS %d page %d\n", PAGERID( pPager ), pPg.pgno );
  4542. sqlite3PcacheMakeClean( pPg );
  4543. }
  4544. return pager_error( pPager, rc );
  4545. }
  4546. /*
  4547. ** Allocate and initialize a new Pager object and put a pointer to it
  4548. ** in *ppPager. The pager should eventually be freed by passing it
  4549. ** to sqlite3PagerClose().
  4550. **
  4551. ** The zFilename argument is the path to the database file to open.
  4552. ** If zFilename is NULL then a randomly-named temporary file is created
  4553. ** and used as the file to be cached. Temporary files are be deleted
  4554. ** automatically when they are closed. If zFilename is ":memory:" then
  4555. ** all information is held in cache. It is never written to disk.
  4556. ** This can be used to implement an in-memory database.
  4557. **
  4558. ** The nExtra parameter specifies the number of bytes of space allocated
  4559. ** along with each page reference. This space is available to the user
  4560. ** via the sqlite3PagerGetExtra() API.
  4561. **
  4562. ** The flags argument is used to specify properties that affect the
  4563. ** operation of the pager. It should be passed some bitwise combination
  4564. ** of the PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK flags.
  4565. **
  4566. ** The vfsFlags parameter is a bitmask to pass to the flags parameter
  4567. ** of the xOpen() method of the supplied VFS when opening files.
  4568. **
  4569. ** If the pager object is allocated and the specified file opened
  4570. ** successfully, SQLITE_OK is returned and *ppPager set to point to
  4571. ** the new pager object. If an error occurs, *ppPager is set to NULL
  4572. ** and error code returned. This function may return SQLITE_NOMEM
  4573. ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
  4574. ** various SQLITE_IO_XXX errors.
  4575. */
  4576. static int sqlite3PagerOpen(
  4577. sqlite3_vfs pVfs, /* The virtual file system to use */
  4578. out Pager ppPager, /* OUT: Return the Pager structure here */
  4579. string zFilename, /* Name of the database file to open */
  4580. int nExtra, /* Extra bytes append to each in-memory page */
  4581. int flags, /* flags controlling this file */
  4582. int vfsFlags, /* flags passed through to sqlite3_vfs.xOpen() */
  4583. dxReiniter xReinit /* Function to reinitialize pages */
  4584. )
  4585. {
  4586. u8 pPtr;
  4587. Pager pPager = null; /* Pager object to allocate and return */
  4588. int rc = SQLITE_OK; /* Return code */
  4589. u8 tempFile = 0; /* True for temp files (incl. in-memory files) */ // Needs to be u8 for later tests
  4590. u8 memDb = 0; /* True if this is an in-memory file */
  4591. bool readOnly = false; /* True if this is a read-only file */
  4592. int journalFileSize; /* Bytes to allocate for each journal fd */
  4593. StringBuilder zPathname = null; /* Full path to database file */
  4594. int nPathname = 0; /* Number of bytes in zPathname */
  4595. bool useJournal = ( flags & PAGER_OMIT_JOURNAL ) == 0; /* False to omit journal */
  4596. bool noReadlock = ( flags & PAGER_NO_READLOCK ) != 0; /* True to omit read-lock */
  4597. int pcacheSize = sqlite3PcacheSize(); /* Bytes to allocate for PCache */
  4598. u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE; /* Default page size */
  4599. string zUri = null; /* URI args to copy */
  4600. int nUri = 0; /* Number of bytes of URI args at *zUri */
  4601. /* Figure out how much space is required for each journal file-handle
  4602. ** (there are two of them, the main journal and the sub-journal). This
  4603. ** is the maximum space required for an in-memory journal file handle
  4604. ** and a regular journal file-handle. Note that a "regular journal-handle"
  4605. ** may be a wrapper capable of caching the first portion of the journal
  4606. ** file in memory to implement the atomic-write optimization (see
  4607. ** source file journal.c).
  4608. */
  4609. if ( sqlite3JournalSize( pVfs ) > sqlite3MemJournalSize() )
  4610. {
  4611. journalFileSize = ROUND8( sqlite3JournalSize( pVfs ) );
  4612. }
  4613. else
  4614. {
  4615. journalFileSize = ROUND8( sqlite3MemJournalSize() );
  4616. }
  4617. /* Set the output variable to NULL in case an error occurs. */
  4618. ppPager = null;
  4619. #if !SQLITE_OMIT_MEMORYDB
  4620. if ( ( flags & PAGER_MEMORY ) != 0 )
  4621. {
  4622. memDb = 1;
  4623. zFilename = null;
  4624. }
  4625. #endif
  4626. /* Compute and store the full pathname in an allocated buffer pointed
  4627. ** to by zPathname, length nPathname. Or, if this is a temporary file,
  4628. ** leave both nPathname and zPathname set to 0.
  4629. */
  4630. if ( !String.IsNullOrEmpty( zFilename ) )
  4631. {
  4632. nPathname = pVfs.mxPathname + 1;
  4633. zPathname = new StringBuilder( nPathname * 2 );// sqlite3Malloc( nPathname * 2 );
  4634. //if ( zPathname == null )
  4635. //{
  4636. // return SQLITE_NOMEM;
  4637. //}
  4638. //zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
  4639. rc = sqlite3OsFullPathname( pVfs, zFilename, nPathname, zPathname );
  4640. nPathname = sqlite3Strlen30( zPathname );
  4641. zUri = zFilename;
  4642. //string z = zUri = zFilename;//.Substring(sqlite3Strlen30( zFilename ) );
  4643. //while ( *z )
  4644. //{
  4645. // z += sqlite3Strlen30( z ) + 1;
  4646. // z += sqlite3Strlen30( z ) + 1;
  4647. //}
  4648. //nUri = zUri.Length;// &z[1] - zUri;
  4649. if ( rc == SQLITE_OK && nPathname + 8 > pVfs.mxPathname )
  4650. {
  4651. /* This branch is taken when the journal path required by
  4652. ** the database being opened will be more than pVfs.mxPathname
  4653. ** bytes in length. This means the database cannot be opened,
  4654. ** as it will not be possible to open the journal file or even
  4655. ** check for a hot-journal before reading.
  4656. */
  4657. rc = SQLITE_CANTOPEN_BKPT();
  4658. }
  4659. if ( rc != SQLITE_OK )
  4660. {
  4661. //sqlite3_free( ref zPathname );
  4662. return rc;
  4663. }
  4664. }
  4665. /* Allocate memory for the Pager structure, PCache object, the
  4666. ** three file descriptors, the database file name and the journal
  4667. ** file name. The layout in memory is as follows:
  4668. **
  4669. ** Pager object (sizeof(Pager) bytes)
  4670. ** PCache object (sqlite3PcacheSize() bytes)
  4671. ** Database file handle (pVfs.szOsFile bytes)
  4672. ** Sub-journal file handle (journalFileSize bytes)
  4673. ** Main journal file handle (journalFileSize bytes)
  4674. ** Database file name (nPathname+1 bytes)
  4675. ** Journal file name (nPathname+8+1 bytes)
  4676. */
  4677. //pPtr = (u8 *)sqlite3MallocZero(
  4678. // ROUND8(sizeof(*pPager)) + /* Pager structure */
  4679. // ROUND8(pcacheSize) + /* PCache object */
  4680. // ROUND8(pVfs.szOsFile) + /* The main db file */
  4681. // journalFileSize * 2 + /* The two journal files */
  4682. // nPathname + 1 + nUri + /* zFilename */
  4683. // nPathname + 8 + 1 /* zJournal */
  4684. //#if !SQLITE_OMIT_WAL
  4685. // + nPathname + 4 + 1 /* zWal */
  4686. //#endif
  4687. //);
  4688. // Debug.Assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)));
  4689. //if( !pPtr ){
  4690. // //sqlite3_free(zPathname);
  4691. // return SQLITE_NOMEM;
  4692. //}
  4693. pPager = new Pager();//(Pager*)(pPtr);
  4694. pPager.pPCache = new PCache();//(PCache*)(pPtr += ROUND8(sizeof(*pPager)));
  4695. pPager.fd = new sqlite3_file();//(sqlite3_file*)(pPtr += ROUND8(pcacheSize));
  4696. pPager.sjfd = new sqlite3_file();//(sqlite3_file*)(pPtr += ROUND8(pVfs.szOsFile));
  4697. pPager.jfd = new sqlite3_file();//(sqlite3_file*)(pPtr += journalFileSize);
  4698. //pPager.zFilename = (char*)(pPtr += journalFileSize);
  4699. //Debug.Assert( EIGHT_BYTE_ALIGNMENT(pPager.jfd) );
  4700. /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
  4701. if ( zPathname != null )
  4702. {
  4703. Debug.Assert( nPathname > 0 );
  4704. //pPager.zJournal = (char*)(pPtr += nPathname + 1 + nUri);
  4705. //memcpy(pPager.zFilename, zPathname, nPathname);
  4706. pPager.zFilename = zPathname.ToString();
  4707. zUri = pPager.zFilename;//.Substring( nPathname + 1 );//memcpy( &pPager.zFilename[nPathname + 1], zUri, nUri );
  4708. //memcpy(pPager.zJournal, zPathname, nPathname);
  4709. //memcpy(&pPager.zJournal[nPathname], "-journal", 8);
  4710. pPager.zJournal = pPager.zFilename + "-journal";
  4711. sqlite3FileSuffix3( pPager.zFilename, pPager.zJournal );
  4712. #if !SQLITE_OMIT_WAL
  4713. pPager.zWal = &pPager.zJournal[nPathname+8+1];
  4714. memcpy(pPager.zWal, zPathname, nPathname);
  4715. memcpy(&pPager.zWal[nPathname], "-wal", 4);
  4716. sqlite3FileSuffix3(pPager.zFilename, pPager.zWal);
  4717. #endif
  4718. //sqlite3_free( ref zPathname );
  4719. }
  4720. else
  4721. {
  4722. pPager.zFilename = "";
  4723. }
  4724. pPager.pVfs = pVfs;
  4725. pPager.vfsFlags = (u32)vfsFlags;
  4726. /* Open the pager file.
  4727. */
  4728. if ( !String.IsNullOrEmpty( zFilename ) )
  4729. {
  4730. int fout = 0; /* VFS flags returned by xOpen() */
  4731. rc = sqlite3OsOpen( pVfs, zFilename, pPager.fd, vfsFlags, ref fout );
  4732. Debug.Assert( 0 == memDb );
  4733. readOnly = ( fout & SQLITE_OPEN_READONLY ) != 0;
  4734. /* If the file was successfully opened for read/write access,
  4735. ** choose a default page size in case we have to create the
  4736. ** database file. The default page size is the maximum of:
  4737. **
  4738. ** + SQLITE_DEFAULT_PAGE_SIZE,
  4739. ** + The value returned by sqlite3OsSectorSize()
  4740. ** + The largest page size that can be written atomically.
  4741. */
  4742. if ( rc == SQLITE_OK && !readOnly )
  4743. {
  4744. setSectorSize( pPager );
  4745. Debug.Assert( SQLITE_DEFAULT_PAGE_SIZE <= SQLITE_MAX_DEFAULT_PAGE_SIZE );
  4746. if ( szPageDflt < pPager.sectorSize )
  4747. {
  4748. if ( pPager.sectorSize > SQLITE_MAX_DEFAULT_PAGE_SIZE )
  4749. {
  4750. szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
  4751. }
  4752. else
  4753. {
  4754. szPageDflt = (u32)pPager.sectorSize;
  4755. }
  4756. }
  4757. #if SQLITE_ENABLE_ATOMIC_WRITE
  4758. {
  4759. int iDc = sqlite3OsDeviceCharacteristics(pPager.fd);
  4760. int ii;
  4761. Debug.Assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  4762. Debug.Assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  4763. Debug.Assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
  4764. for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
  4765. if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
  4766. szPageDflt = ii;
  4767. }
  4768. }
  4769. }
  4770. #endif
  4771. }
  4772. }
  4773. else
  4774. {
  4775. /* If a temporary file is requested, it is not opened immediately.
  4776. ** In this case we accept the default page size and delay actually
  4777. ** opening the file until the first call to OsWrite().
  4778. **
  4779. ** This branch is also run for an in-memory database. An in-memory
  4780. ** database is the same as a temp-file that is never written out to
  4781. ** disk and uses an in-memory rollback journal.
  4782. */
  4783. tempFile = 1;
  4784. pPager.eState = PAGER_READER;
  4785. pPager.eLock = EXCLUSIVE_LOCK;
  4786. readOnly = ( vfsFlags & SQLITE_OPEN_READONLY ) != 0;
  4787. }
  4788. /* The following call to PagerSetPagesize() serves to set the value of
  4789. ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
  4790. */
  4791. if ( rc == SQLITE_OK )
  4792. {
  4793. Debug.Assert( pPager.memDb == 0 );
  4794. rc = sqlite3PagerSetPagesize( pPager, ref szPageDflt, -1 );
  4795. testcase( rc != SQLITE_OK );
  4796. }
  4797. /* If an error occurred in either of the blocks above, free the
  4798. ** Pager structure and close the file.
  4799. */
  4800. if ( rc != SQLITE_OK )
  4801. {
  4802. Debug.Assert( null == pPager.pTmpSpace );
  4803. sqlite3OsClose( pPager.fd );
  4804. //sqlite3_free( ref pPager );
  4805. return rc;
  4806. }
  4807. /* Initialize the PCache object. */
  4808. Debug.Assert( nExtra < 1000 );
  4809. nExtra = ROUND8( nExtra );
  4810. sqlite3PcacheOpen( (int)szPageDflt, nExtra, 0 == memDb,
  4811. 0 == memDb ? (dxStress)pagerStress : null, pPager, pPager.pPCache );
  4812. PAGERTRACE( "OPEN %d %s\n", FILEHANDLEID( pPager.fd ), pPager.zFilename );
  4813. IOTRACE( "OPEN %p %s\n", pPager, pPager.zFilename );
  4814. pPager.useJournal = (u8)( useJournal ? 1 : 0 );
  4815. pPager.noReadlock = (u8)( noReadlock && readOnly ? 1 : 0 );
  4816. /* pPager.stmtOpen = 0; */
  4817. /* pPager.stmtInUse = 0; */
  4818. /* pPager.nRef = 0; */
  4819. /* pPager.stmtSize = 0; */
  4820. /* pPager.stmtJSize = 0; */
  4821. /* pPager.nPage = 0; */
  4822. pPager.mxPgno = SQLITE_MAX_PAGE_COUNT;
  4823. /* pPager.state = PAGER_UNLOCK; */
  4824. #if FALSE
  4825. Debug.Assert(pPager.state == (tempFile != 0 ? PAGER_EXCLUSIVE : PAGER_UNLOCK));
  4826. #endif
  4827. /* pPager.errMask = 0; */
  4828. pPager.tempFile = tempFile != 0;
  4829. Debug.Assert( tempFile == PAGER_LOCKINGMODE_NORMAL
  4830. || tempFile == PAGER_LOCKINGMODE_EXCLUSIVE );
  4831. Debug.Assert( PAGER_LOCKINGMODE_EXCLUSIVE == 1 );
  4832. pPager.exclusiveMode = tempFile != 0;
  4833. pPager.changeCountDone = pPager.tempFile;
  4834. pPager.memDb = memDb;
  4835. pPager.readOnly = readOnly;
  4836. Debug.Assert( useJournal || pPager.tempFile );
  4837. pPager.noSync = pPager.tempFile;
  4838. pPager.fullSync = pPager.noSync;
  4839. pPager.syncFlags = (byte)( pPager.noSync ? 0 : SQLITE_SYNC_NORMAL );
  4840. pPager.ckptSyncFlags = pPager.syncFlags;
  4841. /* pPager.pFirst = 0; */
  4842. /* pPager.pFirstSynced = 0; */
  4843. /* pPager.pLast = 0; */
  4844. pPager.nExtra = (u16)nExtra;
  4845. pPager.journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
  4846. Debug.Assert( isOpen( pPager.fd ) || tempFile != 0 );
  4847. setSectorSize( pPager );
  4848. if ( !useJournal )
  4849. {
  4850. pPager.journalMode = PAGER_JOURNALMODE_OFF;
  4851. }
  4852. else if ( memDb != 0 )
  4853. {
  4854. pPager.journalMode = PAGER_JOURNALMODE_MEMORY;
  4855. }
  4856. /* pPager.xBusyHandler = 0; */
  4857. /* pPager.pBusyHandlerArg = 0; */
  4858. pPager.xReiniter = xReinit;
  4859. /* memset(pPager.aHash, 0, sizeof(pPager.aHash)); */
  4860. ppPager = pPager;
  4861. return SQLITE_OK;
  4862. }
  4863. /*
  4864. ** This function is called after transitioning from PAGER_UNLOCK to
  4865. ** PAGER_SHARED state. It tests if there is a hot journal present in
  4866. ** the file-system for the given pager. A hot journal is one that
  4867. ** needs to be played back. According to this function, a hot-journal
  4868. ** file exists if the following criteria are met:
  4869. **
  4870. ** * The journal file exists in the file system, and
  4871. ** * No process holds a RESERVED or greater lock on the database file, and
  4872. ** * The database file itself is greater than 0 bytes in size, and
  4873. ** * The first byte of the journal file exists and is not 0x00.
  4874. **
  4875. ** If the current size of the database file is 0 but a journal file
  4876. ** exists, that is probably an old journal left over from a prior
  4877. ** database with the same name. In this case the journal file is
  4878. ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
  4879. ** is returned.
  4880. **
  4881. ** This routine does not check if there is a master journal filename
  4882. ** at the end of the file. If there is, and that master journal file
  4883. ** does not exist, then the journal file is not really hot. In this
  4884. ** case this routine will return a false-positive. The pager_playback()
  4885. ** routine will discover that the journal file is not really hot and
  4886. ** will not roll it back.
  4887. **
  4888. ** If a hot-journal file is found to exist, *pExists is set to 1 and
  4889. ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
  4890. ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
  4891. ** to determine whether or not a hot-journal file exists, the IO error
  4892. ** code is returned and the value of *pExists is undefined.
  4893. */
  4894. static int hasHotJournal( Pager pPager, ref int pExists )
  4895. {
  4896. sqlite3_vfs pVfs = pPager.pVfs;
  4897. int rc = SQLITE_OK; /* Return code */
  4898. int exists = 1; /* True if a journal file is present */
  4899. int jrnlOpen = isOpen( pPager.jfd ) ? 1 : 0;
  4900. Debug.Assert( pPager.useJournal != 0 );
  4901. Debug.Assert( isOpen( pPager.fd ) );
  4902. Debug.Assert( pPager.eState == PAGER_OPEN );
  4903. Debug.Assert( jrnlOpen == 0 || ( sqlite3OsDeviceCharacteristics( pPager.jfd ) &
  4904. SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
  4905. ) != 0 );
  4906. pExists = 0;
  4907. if ( 0 == jrnlOpen )
  4908. {
  4909. rc = sqlite3OsAccess( pVfs, pPager.zJournal, SQLITE_ACCESS_EXISTS, ref exists );
  4910. }
  4911. if ( rc == SQLITE_OK && exists != 0 )
  4912. {
  4913. int locked = 0; /* True if some process holds a RESERVED lock */
  4914. /* Race condition here: Another process might have been holding the
  4915. ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
  4916. ** call above, but then delete the journal and drop the lock before
  4917. ** we get to the following sqlite3OsCheckReservedLock() call. If that
  4918. ** is the case, this routine might think there is a hot journal when
  4919. ** in fact there is none. This results in a false-positive which will
  4920. ** be dealt with by the playback routine. Ticket #3883.
  4921. */
  4922. rc = sqlite3OsCheckReservedLock( pPager.fd, ref locked );
  4923. if ( rc == SQLITE_OK && locked == 0 )
  4924. {
  4925. Pgno nPage = 0; /* Number of pages in database file */
  4926. /* Check the size of the database file. If it consists of 0 pages,
  4927. ** then delete the journal file. See the header comment above for
  4928. ** the reasoning here. Delete the obsolete journal file under
  4929. ** a RESERVED lock to avoid race conditions and to avoid violating
  4930. ** [H33020].
  4931. */
  4932. rc = pagerPagecount( pPager, ref nPage );
  4933. if ( rc == SQLITE_OK )
  4934. {
  4935. if ( nPage == 0 )
  4936. {
  4937. sqlite3BeginBenignMalloc();
  4938. if ( pagerLockDb( pPager, RESERVED_LOCK ) == SQLITE_OK )
  4939. {
  4940. sqlite3OsDelete( pVfs, pPager.zJournal, 0 );
  4941. if ( !pPager.exclusiveMode )
  4942. pagerUnlockDb( pPager, SHARED_LOCK );
  4943. }
  4944. sqlite3EndBenignMalloc();
  4945. }
  4946. else
  4947. {
  4948. /* The journal file exists and no other connection has a reserved
  4949. ** or greater lock on the database file. Now check that there is
  4950. ** at least one non-zero bytes at the start of the journal file.
  4951. ** If there is, then we consider this journal to be hot. If not,
  4952. ** it can be ignored.
  4953. */
  4954. if ( 0 == jrnlOpen )
  4955. {
  4956. int f = SQLITE_OPEN_READONLY | SQLITE_OPEN_MAIN_JOURNAL;
  4957. rc = sqlite3OsOpen( pVfs, pPager.zJournal, pPager.jfd, f, ref f );
  4958. }
  4959. if ( rc == SQLITE_OK )
  4960. {
  4961. u8[] first = new u8[1];
  4962. rc = sqlite3OsRead( pPager.jfd, first, 1, 0 );
  4963. if ( rc == SQLITE_IOERR_SHORT_READ )
  4964. {
  4965. rc = SQLITE_OK;
  4966. }
  4967. if ( 0 == jrnlOpen )
  4968. {
  4969. sqlite3OsClose( pPager.jfd );
  4970. }
  4971. pExists = ( first[0] != 0 ) ? 1 : 0;
  4972. }
  4973. else if ( rc == SQLITE_CANTOPEN )
  4974. {
  4975. /* If we cannot open the rollback journal file in order to see if
  4976. ** its has a zero header, that might be due to an I/O error, or
  4977. ** it might be due to the race condition described above and in
  4978. ** ticket #3883. Either way, assume that the journal is hot.
  4979. ** This might be a false positive. But if it is, then the
  4980. ** automatic journal playback and recovery mechanism will deal
  4981. ** with it under an EXCLUSIVE lock where we do not need to
  4982. ** worry so much with race conditions.
  4983. */
  4984. pExists = 1;
  4985. rc = SQLITE_OK;
  4986. }
  4987. }
  4988. }
  4989. }
  4990. }
  4991. return rc;
  4992. }
  4993. /*
  4994. ** This function is called to obtain a shared lock on the database file.
  4995. ** It is illegal to call sqlite3PagerAcquire() until after this function
  4996. ** has been successfully called. If a shared-lock is already held when
  4997. ** this function is called, it is a no-op.
  4998. **
  4999. ** The following operations are also performed by this function.
  5000. **
  5001. ** 1) If the pager is currently in PAGER_OPEN state (no lock held
  5002. ** on the database file), then an attempt is made to obtain a
  5003. ** SHARED lock on the database file. Immediately after obtaining
  5004. ** the SHARED lock, the file-system is checked for a hot-journal,
  5005. ** which is played back if present. Following any hot-journal
  5006. ** rollback, the contents of the cache are validated by checking
  5007. ** the 'change-counter' field of the database file header and
  5008. ** discarded if they are found to be invalid.
  5009. **
  5010. ** 2) If the pager is running in exclusive-mode, and there are currently
  5011. ** no outstanding references to any pages, and is in the error state,
  5012. ** then an attempt is made to clear the error state by discarding
  5013. ** the contents of the page cache and rolling back any open journal
  5014. ** file.
  5015. **
  5016. ** If everything is successful, SQLITE_OK is returned. If an IO error
  5017. ** occurs while locking the database, checking for a hot-journal file or
  5018. ** rolling back a journal file, the IO error code is returned.
  5019. */
  5020. static int sqlite3PagerSharedLock( Pager pPager )
  5021. {
  5022. int rc = SQLITE_OK; /* Return code */
  5023. /* This routine is only called from b-tree and only when there are no
  5024. ** outstanding pages. This implies that the pager state should either
  5025. ** be OPEN or READER. READER is only possible if the pager is or was in
  5026. ** exclusive access mode.
  5027. */
  5028. Debug.Assert( sqlite3PcacheRefCount( pPager.pPCache ) == 0 );
  5029. Debug.Assert( assert_pager_state( pPager ) );
  5030. Debug.Assert( pPager.eState == PAGER_OPEN || pPager.eState == PAGER_READER );
  5031. if ( NEVER(
  5032. #if SQLITE_OMIT_MEMORYDB
  5033. 0!=MEMDB
  5034. #else
  5035. 0 != pPager.memDb
  5036. #endif
  5037. && pPager.errCode != 0 ) )
  5038. {
  5039. return pPager.errCode;
  5040. }
  5041. if ( !pagerUseWal( pPager ) && pPager.eState == PAGER_OPEN )
  5042. {
  5043. int bHotJournal = 1; /* True if there exists a hot journal-file */
  5044. Debug.Assert(
  5045. #if SQLITE_OMIT_MEMORYDB
  5046. 0==MEMDB
  5047. #else
  5048. 0 == pPager.memDb
  5049. #endif
  5050. );
  5051. Debug.Assert( pPager.noReadlock == 0 || pPager.readOnly );
  5052. if ( pPager.noReadlock == 0 )
  5053. {
  5054. rc = pager_wait_on_lock( pPager, SHARED_LOCK );
  5055. if ( rc != SQLITE_OK )
  5056. {
  5057. Debug.Assert( pPager.eLock == NO_LOCK || pPager.eLock == UNKNOWN_LOCK );
  5058. goto failed;
  5059. }
  5060. }
  5061. /* If a journal file exists, and there is no RESERVED lock on the
  5062. ** database file, then it either needs to be played back or deleted.
  5063. */
  5064. if ( pPager.eLock <= SHARED_LOCK )
  5065. {
  5066. rc = hasHotJournal( pPager, ref bHotJournal );
  5067. }
  5068. if ( rc != SQLITE_OK )
  5069. {
  5070. goto failed;
  5071. }
  5072. if ( bHotJournal != 0 )
  5073. {
  5074. /* Get an EXCLUSIVE lock on the database file. At this point it is
  5075. ** important that a RESERVED lock is not obtained on the way to the
  5076. ** EXCLUSIVE lock. If it were, another process might open the
  5077. ** database file, detect the RESERVED lock, and conclude that the
  5078. ** database is safe to read while this process is still rolling the
  5079. ** hot-journal back.
  5080. **
  5081. ** Because the intermediate RESERVED lock is not requested, any
  5082. ** other process attempting to access the database file will get to
  5083. ** this point in the code and fail to obtain its own EXCLUSIVE lock
  5084. ** on the database file.
  5085. **
  5086. ** Unless the pager is in locking_mode=exclusive mode, the lock is
  5087. ** downgraded to SHARED_LOCK before this function returns.
  5088. */
  5089. rc = pagerLockDb( pPager, EXCLUSIVE_LOCK );
  5090. if ( rc != SQLITE_OK )
  5091. {
  5092. goto failed;
  5093. }
  5094. /* If it is not already open and the file exists on disk, open the
  5095. ** journal for read/write access. Write access is required because
  5096. ** in exclusive-access mode the file descriptor will be kept open
  5097. ** and possibly used for a transaction later on. Also, write-access
  5098. ** is usually required to finalize the journal in journal_mode=persist
  5099. ** mode (and also for journal_mode=truncate on some systems).
  5100. **
  5101. ** If the journal does not exist, it usually means that some
  5102. ** other connection managed to get in and roll it back before
  5103. ** this connection obtained the exclusive lock above. Or, it
  5104. ** may mean that the pager was in the error-state when this
  5105. ** function was called and the journal file does not exist.
  5106. */
  5107. if ( !isOpen( pPager.jfd ) )
  5108. {
  5109. sqlite3_vfs pVfs = pPager.pVfs;
  5110. int bExists = 0; /* True if journal file exists */
  5111. rc = sqlite3OsAccess(
  5112. pVfs, pPager.zJournal, SQLITE_ACCESS_EXISTS, ref bExists );
  5113. if ( rc == SQLITE_OK && bExists != 0 )
  5114. {
  5115. int fout = 0;
  5116. int f = SQLITE_OPEN_READWRITE | SQLITE_OPEN_MAIN_JOURNAL;
  5117. Debug.Assert( !pPager.tempFile );
  5118. rc = sqlite3OsOpen( pVfs, pPager.zJournal, pPager.jfd, f, ref fout );
  5119. Debug.Assert( rc != SQLITE_OK || isOpen( pPager.jfd ) );
  5120. if ( rc == SQLITE_OK && ( fout & SQLITE_OPEN_READONLY ) != 0 )
  5121. {
  5122. rc = SQLITE_CANTOPEN_BKPT();
  5123. sqlite3OsClose( pPager.jfd );
  5124. }
  5125. }
  5126. }
  5127. /* Playback and delete the journal. Drop the database write
  5128. ** lock and reacquire the read lock. Purge the cache before
  5129. ** playing back the hot-journal so that we don't end up with
  5130. ** an inconsistent cache. Sync the hot journal before playing
  5131. ** it back since the process that crashed and left the hot journal
  5132. ** probably did not sync it and we are required to always sync
  5133. ** the journal before playing it back.
  5134. */
  5135. if ( isOpen( pPager.jfd ) )
  5136. {
  5137. Debug.Assert( rc == SQLITE_OK );
  5138. rc = pagerSyncHotJournal( pPager );
  5139. if ( rc == SQLITE_OK )
  5140. {
  5141. rc = pager_playback( pPager, 1 );
  5142. pPager.eState = PAGER_OPEN;
  5143. }
  5144. }
  5145. else if ( !pPager.exclusiveMode )
  5146. {
  5147. pagerUnlockDb( pPager, SHARED_LOCK );
  5148. }
  5149. if ( rc != SQLITE_OK )
  5150. {
  5151. /* This branch is taken if an error occurs while trying to open
  5152. ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
  5153. ** pager_unlock() routine will be called before returning to unlock
  5154. ** the file. If the unlock attempt fails, then Pager.eLock must be
  5155. ** set to UNKNOWN_LOCK (see the comment above the #define for
  5156. ** UNKNOWN_LOCK above for an explanation).
  5157. **
  5158. ** In order to get pager_unlock() to do this, set Pager.eState to
  5159. ** PAGER_ERROR now. This is not actually counted as a transition
  5160. ** to ERROR state in the state diagram at the top of this file,
  5161. ** since we know that the same call to pager_unlock() will very
  5162. ** shortly transition the pager object to the OPEN state. Calling
  5163. ** assert_pager_state() would fail now, as it should not be possible
  5164. ** to be in ERROR state when there are zero outstanding page
  5165. ** references.
  5166. */
  5167. pager_error( pPager, rc );
  5168. goto failed;
  5169. }
  5170. Debug.Assert( pPager.eState == PAGER_OPEN );
  5171. Debug.Assert( ( pPager.eLock == SHARED_LOCK )
  5172. || ( pPager.exclusiveMode && pPager.eLock > SHARED_LOCK )
  5173. );
  5174. }
  5175. if ( !pPager.tempFile
  5176. && ( pPager.pBackup != null || sqlite3PcachePagecount( pPager.pPCache ) > 0 )
  5177. )
  5178. {
  5179. /* The shared-lock has just been acquired on the database file
  5180. ** and there are already pages in the cache (from a previous
  5181. ** read or write transaction). Check to see if the database
  5182. ** has been modified. If the database has changed, flush the
  5183. ** cache.
  5184. **
  5185. ** Database changes is detected by looking at 15 bytes beginning
  5186. ** at offset 24 into the file. The first 4 of these 16 bytes are
  5187. ** a 32-bit counter that is incremented with each change. The
  5188. ** other bytes change randomly with each file change when
  5189. ** a codec is in use.
  5190. **
  5191. ** There is a vanishingly small chance that a change will not be
  5192. ** detected. The chance of an undetected change is so small that
  5193. ** it can be neglected.
  5194. */
  5195. Pgno nPage = 0;
  5196. byte[] dbFileVers = new byte[pPager.dbFileVers.Length];
  5197. rc = pagerPagecount( pPager, ref nPage );
  5198. if ( rc != 0 )
  5199. goto failed;
  5200. if ( nPage > 0 )
  5201. {
  5202. IOTRACE( "CKVERS %p %d\n", pPager, dbFileVers.Length );
  5203. rc = sqlite3OsRead( pPager.fd, dbFileVers, dbFileVers.Length, 24 );
  5204. if ( rc != SQLITE_OK )
  5205. {
  5206. goto failed;
  5207. }
  5208. }
  5209. else
  5210. {
  5211. Array.Clear( dbFileVers, 0, dbFileVers.Length );// memset( dbFileVers, 0, sizeof( dbFileVers ) );
  5212. }
  5213. if ( memcmp( pPager.dbFileVers, dbFileVers, dbFileVers.Length ) != 0 )
  5214. {
  5215. pager_reset( pPager );
  5216. }
  5217. }
  5218. /* If there is a WAL file in the file-system, open this database in WAL
  5219. ** mode. Otherwise, the following function call is a no-op.
  5220. */
  5221. rc = pagerOpenWalIfPresent( pPager );
  5222. #if !SQLITE_OMIT_WAL
  5223. Debug.Assert( pPager.pWal == null || rc == SQLITE_OK );
  5224. #endif
  5225. }
  5226. if ( pagerUseWal( pPager ) )
  5227. {
  5228. Debug.Assert( rc == SQLITE_OK );
  5229. rc = pagerBeginReadTransaction( pPager );
  5230. }
  5231. if ( pPager.eState == PAGER_OPEN && rc == SQLITE_OK )
  5232. {
  5233. rc = pagerPagecount( pPager, ref pPager.dbSize );
  5234. }
  5235. failed:
  5236. if ( rc != SQLITE_OK )
  5237. {
  5238. Debug.Assert(
  5239. #if SQLITE_OMIT_MEMORYDB
  5240. 0==MEMDB
  5241. #else
  5242. 0 == pPager.memDb
  5243. #endif
  5244. );
  5245. pager_unlock( pPager );
  5246. Debug.Assert( pPager.eState == PAGER_OPEN );
  5247. }
  5248. else
  5249. {
  5250. pPager.eState = PAGER_READER;
  5251. }
  5252. return rc;
  5253. }
  5254. /*
  5255. ** If the reference count has reached zero, rollback any active
  5256. ** transaction and unlock the pager.
  5257. **
  5258. ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
  5259. ** the rollback journal, the unlock is not performed and there is
  5260. ** nothing to rollback, so this routine is a no-op.
  5261. */
  5262. static void pagerUnlockIfUnused( Pager pPager )
  5263. {
  5264. if ( sqlite3PcacheRefCount( pPager.pPCache ) == 0 )
  5265. {
  5266. pagerUnlockAndRollback( pPager );
  5267. }
  5268. }
  5269. /*
  5270. ** Acquire a reference to page number pgno in pager pPager (a page
  5271. ** reference has type DbPage*). If the requested reference is
  5272. ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
  5273. **
  5274. ** If the requested page is already in the cache, it is returned.
  5275. ** Otherwise, a new page object is allocated and populated with data
  5276. ** read from the database file. In some cases, the pcache module may
  5277. ** choose not to allocate a new page object and may reuse an existing
  5278. ** object with no outstanding references.
  5279. **
  5280. ** The extra data appended to a page is always initialized to zeros the
  5281. ** first time a page is loaded into memory. If the page requested is
  5282. ** already in the cache when this function is called, then the extra
  5283. ** data is left as it was when the page object was last used.
  5284. **
  5285. ** If the database image is smaller than the requested page or if a
  5286. ** non-zero value is passed as the noContent parameter and the
  5287. ** requested page is not already stored in the cache, then no
  5288. ** actual disk read occurs. In this case the memory image of the
  5289. ** page is initialized to all zeros.
  5290. **
  5291. ** If noContent is true, it means that we do not care about the contents
  5292. ** of the page. This occurs in two seperate scenarios:
  5293. **
  5294. ** a) When reading a free-list leaf page from the database, and
  5295. **
  5296. ** b) When a savepoint is being rolled back and we need to load
  5297. ** a new page into the cache to be filled with the data read
  5298. ** from the savepoint journal.
  5299. **
  5300. ** If noContent is true, then the data returned is zeroed instead of
  5301. ** being read from the database. Additionally, the bits corresponding
  5302. ** to pgno in Pager.pInJournal (bitvec of pages already written to the
  5303. ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
  5304. ** savepoints are set. This means if the page is made writable at any
  5305. ** point in the future, using a call to sqlite3PagerWrite(), its contents
  5306. ** will not be journaled. This saves IO.
  5307. **
  5308. ** The acquisition might fail for several reasons. In all cases,
  5309. ** an appropriate error code is returned and *ppPage is set to NULL.
  5310. **
  5311. ** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt
  5312. ** to find a page in the in-memory cache first. If the page is not already
  5313. ** in memory, this routine goes to disk to read it in whereas Lookup()
  5314. ** just returns 0. This routine acquires a read-lock the first time it
  5315. ** has to go to disk, and could also playback an old journal if necessary.
  5316. ** Since Lookup() never goes to disk, it never has to deal with locks
  5317. ** or journal files.
  5318. */
  5319. // Under C# from the header file
  5320. //#define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
  5321. static int sqlite3PagerGet(
  5322. Pager pPager, /* The pager open on the database file */
  5323. u32 pgno, /* Page number to fetch */
  5324. ref DbPage ppPage /* Write a pointer to the page here */
  5325. )
  5326. {
  5327. return sqlite3PagerAcquire( pPager, pgno, ref ppPage, 0 );
  5328. }
  5329. static int sqlite3PagerAcquire(
  5330. Pager pPager, /* The pager open on the database file */
  5331. u32 pgno, /* Page number to fetch */
  5332. ref DbPage ppPage, /* Write a pointer to the page here */
  5333. u8 noContent /* Do not bother reading content from disk if true */
  5334. )
  5335. {
  5336. int rc;
  5337. PgHdr pPg = null;
  5338. Debug.Assert( pPager.eState >= PAGER_READER );
  5339. Debug.Assert( assert_pager_state( pPager ) );
  5340. if ( pgno == 0 )
  5341. {
  5342. return SQLITE_CORRUPT_BKPT();
  5343. }
  5344. /* If the pager is in the error state, return an error immediately.
  5345. ** Otherwise, request the page from the PCache layer. */
  5346. if ( pPager.errCode != SQLITE_OK )
  5347. {
  5348. rc = pPager.errCode;
  5349. }
  5350. else
  5351. {
  5352. rc = sqlite3PcacheFetch( pPager.pPCache, pgno, 1, ref ppPage );
  5353. }
  5354. if ( rc != SQLITE_OK )
  5355. {
  5356. /* Either the call to sqlite3PcacheFetch() returned an error or the
  5357. ** pager was already in the error-state when this function was called.
  5358. ** Set pPg to 0 and jump to the exception handler. */
  5359. pPg = null;
  5360. goto pager_acquire_err;
  5361. }
  5362. Debug.Assert( ( ppPage ).pgno == pgno );
  5363. Debug.Assert( ( ppPage ).pPager == pPager || ( ppPage ).pPager == null );
  5364. if ( ( ppPage ).pPager != null && 0 == noContent )
  5365. {
  5366. /* In this case the pcache already contains an initialized copy of
  5367. ** the page. Return without further ado. */
  5368. Debug.Assert( pgno <= PAGER_MAX_PGNO && pgno != PAGER_MJ_PGNO( pPager ) );
  5369. PAGER_INCR( ref pPager.nHit );
  5370. return SQLITE_OK;
  5371. }
  5372. else
  5373. {
  5374. /* The pager cache has created a new page. Its content needs to
  5375. ** be initialized. */
  5376. #if SQLITE_TEST
  5377. PAGER_INCR( ref pPager.nMiss );
  5378. #endif
  5379. pPg = ppPage;
  5380. pPg.pPager = pPager;
  5381. pPg.pExtra = new MemPage();//memset(pPg.pExtra, 0, pPager.nExtra);
  5382. /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
  5383. ** number greater than this, or the unused locking-page, is requested. */
  5384. if ( pgno > PAGER_MAX_PGNO || pgno == PAGER_MJ_PGNO( pPager ) )
  5385. {
  5386. rc = SQLITE_CORRUPT_BKPT();
  5387. goto pager_acquire_err;
  5388. }
  5389. if (
  5390. #if SQLITE_OMIT_MEMORYDB
  5391. 1==MEMDB
  5392. #else
  5393. pPager.memDb != 0
  5394. #endif
  5395. || pPager.dbSize < pgno || noContent != 0 || !isOpen( pPager.fd ) )
  5396. {
  5397. if ( pgno > pPager.mxPgno )
  5398. {
  5399. rc = SQLITE_FULL;
  5400. goto pager_acquire_err;
  5401. }
  5402. if ( noContent != 0 )
  5403. {
  5404. /* Failure to set the bits in the InJournal bit-vectors is benign.
  5405. ** It merely means that we might do some extra work to journal a
  5406. ** page that does not need to be journaled. Nevertheless, be sure
  5407. ** to test the case where a malloc error occurs while trying to set
  5408. ** a bit in a bit vector.
  5409. */
  5410. sqlite3BeginBenignMalloc();
  5411. if ( pgno <= pPager.dbOrigSize )
  5412. {
  5413. #if !NDEBUG || SQLITE_COVERAGE_TEST
  5414. rc = sqlite3BitvecSet( pPager.pInJournal, pgno ); //TESTONLY( rc = ) sqlite3BitvecSet(pPager.pInJournal, pgno);
  5415. #else
  5416. sqlite3BitvecSet(pPager.pInJournal, pgno);
  5417. #endif
  5418. testcase( rc == SQLITE_NOMEM );
  5419. }
  5420. #if !NDEBUG || SQLITE_COVERAGE_TEST
  5421. rc = addToSavepointBitvecs( pPager, pgno ); //TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
  5422. #else
  5423. addToSavepointBitvecs(pPager, pgno);
  5424. #endif
  5425. testcase( rc == SQLITE_NOMEM );
  5426. sqlite3EndBenignMalloc();
  5427. }
  5428. //memset(pPg.pData, 0, pPager.pageSize);
  5429. Array.Clear( pPg.pData, 0, pPager.pageSize );
  5430. IOTRACE( "ZERO %p %d\n", pPager, pgno );
  5431. }
  5432. else
  5433. {
  5434. Debug.Assert( pPg.pPager == pPager );
  5435. rc = readDbPage( pPg );
  5436. if ( rc != SQLITE_OK )
  5437. {
  5438. goto pager_acquire_err;
  5439. }
  5440. }
  5441. pager_set_pagehash( pPg );
  5442. }
  5443. return SQLITE_OK;
  5444. pager_acquire_err:
  5445. Debug.Assert( rc != SQLITE_OK );
  5446. if ( pPg != null )
  5447. {
  5448. sqlite3PcacheDrop( pPg );
  5449. }
  5450. pagerUnlockIfUnused( pPager );
  5451. ppPage = null;
  5452. return rc;
  5453. }
  5454. /*
  5455. ** Acquire a page if it is already in the in-memory cache. Do
  5456. ** not read the page from disk. Return a pointer to the page,
  5457. ** or 0 if the page is not in cache.
  5458. **
  5459. ** See also sqlite3PagerGet(). The difference between this routine
  5460. ** and sqlite3PagerGet() is that _get() will go to the disk and read
  5461. ** in the page if the page is not already in cache. This routine
  5462. ** returns NULL if the page is not in cache or if a disk I/O error
  5463. ** has ever happened.
  5464. */
  5465. static DbPage sqlite3PagerLookup( Pager pPager, u32 pgno )
  5466. {
  5467. PgHdr pPg = null;
  5468. Debug.Assert( pPager != null );
  5469. Debug.Assert( pgno != 0 );
  5470. Debug.Assert( pPager.pPCache != null );
  5471. Debug.Assert( pPager.eState >= PAGER_READER && pPager.eState != PAGER_ERROR );
  5472. sqlite3PcacheFetch( pPager.pPCache, pgno, 0, ref pPg );
  5473. return pPg;
  5474. }
  5475. /*
  5476. ** Release a page reference.
  5477. **
  5478. ** If the number of references to the page drop to zero, then the
  5479. ** page is added to the LRU list. When all references to all pages
  5480. ** are released, a rollback occurs and the lock on the database is
  5481. ** removed.
  5482. */
  5483. static void sqlite3PagerUnref( DbPage pPg )
  5484. {
  5485. if ( pPg != null )
  5486. {
  5487. Pager pPager = pPg.pPager;
  5488. sqlite3PcacheRelease( pPg );
  5489. pagerUnlockIfUnused( pPager );
  5490. }
  5491. }
  5492. /*
  5493. ** This function is called at the start of every write transaction.
  5494. ** There must already be a RESERVED or EXCLUSIVE lock on the database
  5495. ** file when this routine is called.
  5496. **
  5497. ** Open the journal file for pager pPager and write a journal header
  5498. ** to the start of it. If there are active savepoints, open the sub-journal
  5499. ** as well. This function is only used when the journal file is being
  5500. ** opened to write a rollback log for a transaction. It is not used
  5501. ** when opening a hot journal file to roll it back.
  5502. **
  5503. ** If the journal file is already open (as it may be in exclusive mode),
  5504. ** then this function just writes a journal header to the start of the
  5505. ** already open file.
  5506. **
  5507. ** Whether or not the journal file is opened by this function, the
  5508. ** Pager.pInJournal bitvec structure is allocated.
  5509. **
  5510. ** Return SQLITE_OK if everything is successful. Otherwise, return
  5511. ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
  5512. ** an IO error code if opening or writing the journal file fails.
  5513. */
  5514. static int pager_open_journal( Pager pPager )
  5515. {
  5516. int rc = SQLITE_OK; /* Return code */
  5517. sqlite3_vfs pVfs = pPager.pVfs; /* Local cache of vfs pointer */
  5518. Debug.Assert( pPager.eState == PAGER_WRITER_LOCKED );
  5519. Debug.Assert( assert_pager_state( pPager ) );
  5520. Debug.Assert( pPager.pInJournal == null );
  5521. /* If already in the error state, this function is a no-op. But on
  5522. ** the other hand, this routine is never called if we are already in
  5523. ** an error state. */
  5524. if ( NEVER( pPager.errCode ) != 0 )
  5525. return pPager.errCode;
  5526. if ( !pagerUseWal( pPager ) && pPager.journalMode != PAGER_JOURNALMODE_OFF )
  5527. {
  5528. pPager.pInJournal = sqlite3BitvecCreate( pPager.dbSize );
  5529. //if (pPager.pInJournal == null)
  5530. //{
  5531. // return SQLITE_NOMEM;
  5532. //}
  5533. /* Open the journal file if it is not already open. */
  5534. if ( !isOpen( pPager.jfd ) )
  5535. {
  5536. if ( pPager.journalMode == PAGER_JOURNALMODE_MEMORY )
  5537. {
  5538. sqlite3MemJournalOpen( pPager.jfd );
  5539. }
  5540. else
  5541. {
  5542. int flags = /* VFS flags to open journal file */
  5543. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  5544. ( pPager.tempFile ?
  5545. ( SQLITE_OPEN_DELETEONCLOSE | SQLITE_OPEN_TEMP_JOURNAL ) :
  5546. ( SQLITE_OPEN_MAIN_JOURNAL )
  5547. );
  5548. #if SQLITE_ENABLE_ATOMIC_WRITE
  5549. rc = sqlite3JournalOpen(
  5550. pVfs, pPager.zJournal, pPager.jfd, flags, jrnlBufferSize(pPager)
  5551. );
  5552. #else
  5553. int int0 = 0;
  5554. rc = sqlite3OsOpen( pVfs, pPager.zJournal, pPager.jfd, flags, ref int0 );
  5555. #endif
  5556. }
  5557. Debug.Assert( rc != SQLITE_OK || isOpen( pPager.jfd ) );
  5558. }
  5559. /* Write the first journal header to the journal file and open
  5560. ** the sub-journal if necessary.
  5561. */
  5562. if ( rc == SQLITE_OK )
  5563. {
  5564. /* TODO: Check if all of these are really required. */
  5565. pPager.nRec = 0;
  5566. pPager.journalOff = 0;
  5567. pPager.setMaster = 0;
  5568. pPager.journalHdr = 0;
  5569. rc = writeJournalHdr( pPager );
  5570. }
  5571. }
  5572. if ( rc != SQLITE_OK )
  5573. {
  5574. sqlite3BitvecDestroy( ref pPager.pInJournal );
  5575. pPager.pInJournal = null;
  5576. }
  5577. else
  5578. {
  5579. Debug.Assert( pPager.eState == PAGER_WRITER_LOCKED );
  5580. pPager.eState = PAGER_WRITER_CACHEMOD;
  5581. }
  5582. return rc;
  5583. }
  5584. /*
  5585. ** Begin a write-transaction on the specified pager object. If a
  5586. ** write-transaction has already been opened, this function is a no-op.
  5587. **
  5588. ** If the exFlag argument is false, then acquire at least a RESERVED
  5589. ** lock on the database file. If exFlag is true, then acquire at least
  5590. ** an EXCLUSIVE lock. If such a lock is already held, no locking
  5591. ** functions need be called.
  5592. **
  5593. ** If the subjInMemory argument is non-zero, then any sub-journal opened
  5594. ** within this transaction will be opened as an in-memory file. This
  5595. ** has no effect if the sub-journal is already opened (as it may be when
  5596. ** running in exclusive mode) or if the transaction does not require a
  5597. ** sub-journal. If the subjInMemory argument is zero, then any required
  5598. ** sub-journal is implemented in-memory if pPager is an in-memory database,
  5599. ** or using a temporary file otherwise.
  5600. */
  5601. static int sqlite3PagerBegin( Pager pPager, bool exFlag, int subjInMemory )
  5602. {
  5603. int rc = SQLITE_OK;
  5604. if ( pPager.errCode != 0 )
  5605. return pPager.errCode;
  5606. Debug.Assert( pPager.eState >= PAGER_READER && pPager.eState < PAGER_ERROR );
  5607. pPager.subjInMemory = (u8)subjInMemory;
  5608. if ( ALWAYS( pPager.eState == PAGER_READER ) )
  5609. {
  5610. Debug.Assert( pPager.pInJournal == null );
  5611. if ( pagerUseWal( pPager ) )
  5612. {
  5613. /* If the pager is configured to use locking_mode=exclusive, and an
  5614. ** exclusive lock on the database is not already held, obtain it now.
  5615. */
  5616. if ( pPager.exclusiveMode && sqlite3WalExclusiveMode( pPager.pWal, -1 ) )
  5617. {
  5618. rc = pagerLockDb( pPager, EXCLUSIVE_LOCK );
  5619. if ( rc != SQLITE_OK )
  5620. {
  5621. return rc;
  5622. }
  5623. sqlite3WalExclusiveMode( pPager.pWal, 1 );
  5624. }
  5625. /* Grab the write lock on the log file. If successful, upgrade to
  5626. ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
  5627. ** The busy-handler is not invoked if another connection already
  5628. ** holds the write-lock. If possible, the upper layer will call it.
  5629. */
  5630. rc = sqlite3WalBeginWriteTransaction( pPager.pWal );
  5631. }
  5632. else
  5633. {
  5634. /* Obtain a RESERVED lock on the database file. If the exFlag parameter
  5635. ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
  5636. ** busy-handler callback can be used when upgrading to the EXCLUSIVE
  5637. ** lock, but not when obtaining the RESERVED lock.
  5638. */
  5639. rc = pagerLockDb( pPager, RESERVED_LOCK );
  5640. if ( rc == SQLITE_OK && exFlag )
  5641. {
  5642. rc = pager_wait_on_lock( pPager, EXCLUSIVE_LOCK );
  5643. }
  5644. }
  5645. if ( rc == SQLITE_OK )
  5646. {
  5647. /* Change to WRITER_LOCKED state.
  5648. **
  5649. ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
  5650. ** when it has an open transaction, but never to DBMOD or FINISHED.
  5651. ** This is because in those states the code to roll back savepoint
  5652. ** transactions may copy data from the sub-journal into the database
  5653. ** file as well as into the page cache. Which would be incorrect in
  5654. ** WAL mode.
  5655. */
  5656. pPager.eState = PAGER_WRITER_LOCKED;
  5657. pPager.dbHintSize = pPager.dbSize;
  5658. pPager.dbFileSize = pPager.dbSize;
  5659. pPager.dbOrigSize = pPager.dbSize;
  5660. pPager.journalOff = 0;
  5661. }
  5662. Debug.Assert( rc == SQLITE_OK || pPager.eState == PAGER_READER );
  5663. Debug.Assert( rc != SQLITE_OK || pPager.eState == PAGER_WRITER_LOCKED );
  5664. Debug.Assert( assert_pager_state( pPager ) );
  5665. }
  5666. PAGERTRACE( "TRANSACTION %d\n", PAGERID( pPager ) );
  5667. return rc;
  5668. }
  5669. /*
  5670. ** Mark a single data page as writeable. The page is written into the
  5671. ** main journal or sub-journal as required. If the page is written into
  5672. ** one of the journals, the corresponding bit is set in the
  5673. ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
  5674. ** of any open savepoints as appropriate.
  5675. */
  5676. static int pager_write( PgHdr pPg )
  5677. {
  5678. byte[] pData = pPg.pData;
  5679. Pager pPager = pPg.pPager;
  5680. int rc = SQLITE_OK;
  5681. /* This routine is not called unless a write-transaction has already
  5682. ** been started. The journal file may or may not be open at this point.
  5683. ** It is never called in the ERROR state.
  5684. */
  5685. Debug.Assert( pPager.eState == PAGER_WRITER_LOCKED
  5686. || pPager.eState == PAGER_WRITER_CACHEMOD
  5687. || pPager.eState == PAGER_WRITER_DBMOD
  5688. );
  5689. Debug.Assert( assert_pager_state( pPager ) );
  5690. /* If an error has been previously detected, report the same error
  5691. ** again. This should not happen, but the check provides robustness. */
  5692. if ( NEVER( pPager.errCode ) != 0 )
  5693. return pPager.errCode;
  5694. /* Higher-level routines never call this function if database is not
  5695. ** writable. But check anyway, just for robustness. */
  5696. if ( NEVER( pPager.readOnly ) )
  5697. return SQLITE_PERM;
  5698. #if SQLITE_CHECK_PAGES
  5699. CHECK_PAGE(pPg);
  5700. #endif
  5701. /* The journal file needs to be opened. Higher level routines have already
  5702. ** obtained the necessary locks to begin the write-transaction, but the
  5703. ** rollback journal might not yet be open. Open it now if this is the case.
  5704. **
  5705. ** This is done before calling sqlite3PcacheMakeDirty() on the page.
  5706. ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
  5707. ** an error might occur and the pager would end up in WRITER_LOCKED state
  5708. ** with pages marked as dirty in the cache.
  5709. */
  5710. if ( pPager.eState == PAGER_WRITER_LOCKED )
  5711. {
  5712. rc = pager_open_journal( pPager );
  5713. if ( rc != SQLITE_OK )
  5714. return rc;
  5715. }
  5716. Debug.Assert( pPager.eState >= PAGER_WRITER_CACHEMOD );
  5717. Debug.Assert( assert_pager_state( pPager ) );
  5718. /* Mark the page as dirty. If the page has already been written
  5719. ** to the journal then we can return right away.
  5720. */
  5721. sqlite3PcacheMakeDirty( pPg );
  5722. if ( pageInJournal( pPg ) && !subjRequiresPage( pPg ) )
  5723. {
  5724. Debug.Assert( !pagerUseWal( pPager ) );
  5725. }
  5726. else
  5727. {
  5728. /* The transaction journal now exists and we have a RESERVED or an
  5729. ** EXCLUSIVE lock on the main database file. Write the current page to
  5730. ** the transaction journal if it is not there already.
  5731. */
  5732. if ( !pageInJournal( pPg ) && !pagerUseWal( pPager ) )
  5733. {
  5734. Debug.Assert( pagerUseWal( pPager ) == false );
  5735. if ( pPg.pgno <= pPager.dbOrigSize && isOpen( pPager.jfd ) )
  5736. {
  5737. u32 cksum;
  5738. byte[] pData2 = null;
  5739. i64 iOff = pPager.journalOff;
  5740. /* We should never write to the journal file the page that
  5741. ** contains the database locks. The following Debug.Assert verifies
  5742. ** that we do not. */
  5743. Debug.Assert( pPg.pgno != ( ( PENDING_BYTE / ( pPager.pageSize ) ) + 1 ) );//PAGER_MJ_PGNO(pPager) );
  5744. Debug.Assert( pPager.journalHdr <= pPager.journalOff );
  5745. if ( CODEC2( pPager, pData, pPg.pgno, SQLITE_ENCRYPT_READ_CTX, ref pData2 ) )
  5746. return SQLITE_NOMEM; // CODEC2(pPager, pData, pPg.pgno, 7, return SQLITE_NOMEM, pData2);
  5747. cksum = pager_cksum( pPager, pData2 );
  5748. /* Even if an IO or diskfull error occurred while journalling the
  5749. ** page in the block above, set the need-sync flag for the page.
  5750. ** Otherwise, when the transaction is rolled back, the logic in
  5751. ** playback_one_page() will think that the page needs to be restored
  5752. ** in the database file. And if an IO error occurs while doing so,
  5753. ** then corruption may follow.
  5754. */
  5755. pPg.flags |= PGHDR_NEED_SYNC;
  5756. rc = write32bits( pPager.jfd, iOff, pPg.pgno );
  5757. if ( rc != SQLITE_OK )
  5758. return rc;
  5759. rc = sqlite3OsWrite( pPager.jfd, pData2, pPager.pageSize, iOff + 4 );
  5760. if ( rc != SQLITE_OK )
  5761. return rc;
  5762. rc = write32bits( pPager.jfd, iOff + pPager.pageSize + 4, cksum );
  5763. if ( rc != SQLITE_OK )
  5764. return rc;
  5765. IOTRACE( "JOUT %p %d %lld %d\n", pPager, pPg.pgno,
  5766. pPager.journalOff, pPager.pageSize );
  5767. #if SQLITE_TEST
  5768. #if !TCLSH
  5769. PAGER_INCR( ref sqlite3_pager_writej_count );
  5770. #else
  5771. int iValue = sqlite3_pager_writej_count.iValue;
  5772. PAGER_INCR( ref iValue );
  5773. sqlite3_pager_writej_count.iValue = iValue;
  5774. #endif
  5775. #endif
  5776. PAGERTRACE( "JOURNAL %d page %d needSync=%d hash(%08x)\n",
  5777. PAGERID( pPager ), pPg.pgno,
  5778. ( ( pPg.flags & PGHDR_NEED_SYNC ) != 0 ? 1 : 0 ), pager_pagehash( pPg ) );
  5779. pPager.journalOff += 8 + pPager.pageSize;
  5780. pPager.nRec++;
  5781. Debug.Assert( pPager.pInJournal != null );
  5782. rc = sqlite3BitvecSet( pPager.pInJournal, pPg.pgno );
  5783. testcase( rc == SQLITE_NOMEM );
  5784. Debug.Assert( rc == SQLITE_OK || rc == SQLITE_NOMEM );
  5785. rc |= addToSavepointBitvecs( pPager, pPg.pgno );
  5786. if ( rc != SQLITE_OK )
  5787. {
  5788. Debug.Assert( rc == SQLITE_NOMEM );
  5789. return rc;
  5790. }
  5791. }
  5792. else
  5793. {
  5794. if ( pPager.eState != PAGER_WRITER_DBMOD )
  5795. {
  5796. pPg.flags |= PGHDR_NEED_SYNC;
  5797. }
  5798. PAGERTRACE( "APPEND %d page %d needSync=%d\n",
  5799. PAGERID( pPager ), pPg.pgno,
  5800. ( ( pPg.flags & PGHDR_NEED_SYNC ) != 0 ? 1 : 0 ) );
  5801. }
  5802. }
  5803. /* If the statement journal is open and the page is not in it,
  5804. ** then write the current page to the statement journal. Note that
  5805. ** the statement journal format differs from the standard journal format
  5806. ** in that it omits the checksums and the header.
  5807. */
  5808. if ( subjRequiresPage( pPg ) )
  5809. {
  5810. rc = subjournalPage( pPg );
  5811. }
  5812. }
  5813. /* Update the database size and return.
  5814. */
  5815. if ( pPager.dbSize < pPg.pgno )
  5816. {
  5817. pPager.dbSize = pPg.pgno;
  5818. }
  5819. return rc;
  5820. }
  5821. /*
  5822. ** Mark a data page as writeable. This routine must be called before
  5823. ** making changes to a page. The caller must check the return value
  5824. ** of this function and be careful not to change any page data unless
  5825. ** this routine returns SQLITE_OK.
  5826. **
  5827. ** The difference between this function and pager_write() is that this
  5828. ** function also deals with the special case where 2 or more pages
  5829. ** fit on a single disk sector. In this case all co-resident pages
  5830. ** must have been written to the journal file before returning.
  5831. **
  5832. ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
  5833. ** as appropriate. Otherwise, SQLITE_OK.
  5834. */
  5835. static int sqlite3PagerWrite( DbPage pDbPage )
  5836. {
  5837. int rc = SQLITE_OK;
  5838. PgHdr pPg = pDbPage;
  5839. Pager pPager = pPg.pPager;
  5840. u32 nPagePerSector = (u32)( pPager.sectorSize / pPager.pageSize );
  5841. Debug.Assert( pPager.eState >= PAGER_WRITER_LOCKED );
  5842. Debug.Assert( pPager.eState != PAGER_ERROR );
  5843. Debug.Assert( assert_pager_state( pPager ) );
  5844. if ( nPagePerSector > 1 )
  5845. {
  5846. Pgno nPageCount = 0; /* Total number of pages in database file */
  5847. Pgno pg1; /* First page of the sector pPg is located on. */
  5848. Pgno nPage = 0; /* Number of pages starting at pg1 to journal */
  5849. int ii; /* Loop counter */
  5850. bool needSync = false; /* True if any page has PGHDR_NEED_SYNC */
  5851. /* Set the doNotSyncSpill flag to 1. This is because we cannot allow
  5852. ** a journal header to be written between the pages journaled by
  5853. ** this function.
  5854. */
  5855. Debug.Assert(
  5856. #if SQLITE_OMIT_MEMORYDB
  5857. 0==MEMDB
  5858. #else
  5859. 0 == pPager.memDb
  5860. #endif
  5861. );
  5862. Debug.Assert( pPager.doNotSyncSpill == 0 );
  5863. pPager.doNotSyncSpill++;
  5864. /* This trick assumes that both the page-size and sector-size are
  5865. ** an integer power of 2. It sets variable pg1 to the identifier
  5866. ** of the first page of the sector pPg is located on.
  5867. */
  5868. pg1 = (u32)( ( pPg.pgno - 1 ) & ~( nPagePerSector - 1 ) ) + 1;
  5869. nPageCount = pPager.dbSize;
  5870. if ( pPg.pgno > nPageCount )
  5871. {
  5872. nPage = ( pPg.pgno - pg1 ) + 1;
  5873. }
  5874. else if ( ( pg1 + nPagePerSector - 1 ) > nPageCount )
  5875. {
  5876. nPage = nPageCount + 1 - pg1;
  5877. }
  5878. else
  5879. {
  5880. nPage = nPagePerSector;
  5881. }
  5882. Debug.Assert( nPage > 0 );
  5883. Debug.Assert( pg1 <= pPg.pgno );
  5884. Debug.Assert( ( pg1 + nPage ) > pPg.pgno );
  5885. for ( ii = 0; ii < nPage && rc == SQLITE_OK; ii++ )
  5886. {
  5887. u32 pg = (u32)( pg1 + ii );
  5888. PgHdr pPage = new PgHdr();
  5889. if ( pg == pPg.pgno || sqlite3BitvecTest( pPager.pInJournal, pg ) == 0 )
  5890. {
  5891. if ( pg != ( ( PENDING_BYTE / ( pPager.pageSize ) ) + 1 ) ) //PAGER_MJ_PGNO(pPager))
  5892. {
  5893. rc = sqlite3PagerGet( pPager, pg, ref pPage );
  5894. if ( rc == SQLITE_OK )
  5895. {
  5896. rc = pager_write( pPage );
  5897. if ( ( pPage.flags & PGHDR_NEED_SYNC ) != 0 )
  5898. {
  5899. needSync = true;
  5900. }
  5901. sqlite3PagerUnref( pPage );
  5902. }
  5903. }
  5904. }
  5905. else if ( ( pPage = pager_lookup( pPager, pg ) ) != null )
  5906. {
  5907. if ( ( pPage.flags & PGHDR_NEED_SYNC ) != 0 )
  5908. {
  5909. needSync = true;
  5910. }
  5911. sqlite3PagerUnref( pPage );
  5912. }
  5913. }
  5914. /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
  5915. ** starting at pg1, then it needs to be set for all of them. Because
  5916. ** writing to any of these nPage pages may damage the others, the
  5917. ** journal file must contain sync()ed copies of all of them
  5918. ** before any of them can be written out to the database file.
  5919. */
  5920. if ( rc == SQLITE_OK && needSync )
  5921. {
  5922. Debug.Assert(
  5923. #if SQLITE_OMIT_MEMORYDB
  5924. 0==MEMDB
  5925. #else
  5926. 0 == pPager.memDb
  5927. #endif
  5928. );
  5929. for ( ii = 0; ii < nPage; ii++ )
  5930. {
  5931. PgHdr pPage = pager_lookup( pPager, (u32)( pg1 + ii ) );
  5932. if ( pPage != null )
  5933. {
  5934. pPage.flags |= PGHDR_NEED_SYNC;
  5935. sqlite3PagerUnref( pPage );
  5936. }
  5937. }
  5938. }
  5939. Debug.Assert( pPager.doNotSyncSpill == 1 );
  5940. pPager.doNotSyncSpill--;
  5941. }
  5942. else
  5943. {
  5944. rc = pager_write( pDbPage );
  5945. }
  5946. return rc;
  5947. }
  5948. /*
  5949. ** Return TRUE if the page given in the argument was previously passed
  5950. ** to sqlite3PagerWrite(). In other words, return TRUE if it is ok
  5951. ** to change the content of the page.
  5952. */
  5953. #if !NDEBUG
  5954. static bool sqlite3PagerIswriteable( DbPage pPg )
  5955. {
  5956. return ( pPg.flags & PGHDR_DIRTY ) != 0;
  5957. }
  5958. #else
  5959. static bool sqlite3PagerIswriteable( DbPage pPg ) { return true; }
  5960. #endif
  5961. /*
  5962. ** A call to this routine tells the pager that it is not necessary to
  5963. ** write the information on page pPg back to the disk, even though
  5964. ** that page might be marked as dirty. This happens, for example, when
  5965. ** the page has been added as a leaf of the freelist and so its
  5966. ** content no longer matters.
  5967. **
  5968. ** The overlying software layer calls this routine when all of the data
  5969. ** on the given page is unused. The pager marks the page as clean so
  5970. ** that it does not get written to disk.
  5971. **
  5972. ** Tests show that this optimization can quadruple the speed of large
  5973. ** DELETE operations.
  5974. */
  5975. static void sqlite3PagerDontWrite( PgHdr pPg )
  5976. {
  5977. Pager pPager = pPg.pPager;
  5978. if ( ( pPg.flags & PGHDR_DIRTY ) != 0 && pPager.nSavepoint == 0 )
  5979. {
  5980. PAGERTRACE( "DONT_WRITE page %d of %d\n", pPg.pgno, PAGERID( pPager ) );
  5981. IOTRACE( "CLEAN %p %d\n", pPager, pPg.pgno );
  5982. pPg.flags |= PGHDR_DONT_WRITE;
  5983. pager_set_pagehash( pPg );
  5984. }
  5985. }
  5986. /*
  5987. ** This routine is called to increment the value of the database file
  5988. ** change-counter, stored as a 4-byte big-endian integer starting at
  5989. ** byte offset 24 of the pager file. The secondary change counter at
  5990. ** 92 is also updated, as is the SQLite version number at offset 96.
  5991. **
  5992. ** But this only happens if the pPager.changeCountDone flag is false.
  5993. ** To avoid excess churning of page 1, the update only happens once.
  5994. ** See also the pager_write_changecounter() routine that does an
  5995. ** unconditional update of the change counters.
  5996. **
  5997. ** If the isDirectMode flag is zero, then this is done by calling
  5998. ** sqlite3PagerWrite() on page 1, then modifying the contents of the
  5999. ** page data. In this case the file will be updated when the current
  6000. ** transaction is committed.
  6001. **
  6002. ** The isDirectMode flag may only be non-zero if the library was compiled
  6003. ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
  6004. ** if isDirect is non-zero, then the database file is updated directly
  6005. ** by writing an updated version of page 1 using a call to the
  6006. ** sqlite3OsWrite() function.
  6007. */
  6008. static int pager_incr_changecounter( Pager pPager, bool isDirectMode )
  6009. {
  6010. int rc = SQLITE_OK;
  6011. Debug.Assert( pPager.eState == PAGER_WRITER_CACHEMOD
  6012. || pPager.eState == PAGER_WRITER_DBMOD
  6013. );
  6014. Debug.Assert( assert_pager_state( pPager ) );
  6015. /* Declare and initialize constant integer 'isDirect'. If the
  6016. ** atomic-write optimization is enabled in this build, then isDirect
  6017. ** is initialized to the value passed as the isDirectMode parameter
  6018. ** to this function. Otherwise, it is always set to zero.
  6019. **
  6020. ** The idea is that if the atomic-write optimization is not
  6021. ** enabled at compile time, the compiler can omit the tests of
  6022. ** 'isDirect' below, as well as the block enclosed in the
  6023. ** "if( isDirect )" condition.
  6024. */
  6025. #if !SQLITE_ENABLE_ATOMIC_WRITE
  6026. //# define DIRECT_MODE 0
  6027. bool DIRECT_MODE = false;
  6028. Debug.Assert( isDirectMode == false );
  6029. UNUSED_PARAMETER( isDirectMode );
  6030. #else
  6031. //# define DIRECT_MODE isDirectMode
  6032. int DIRECT_MODE = isDirectMode;
  6033. #endif
  6034. if ( !pPager.changeCountDone && pPager.dbSize > 0 )
  6035. {
  6036. PgHdr pPgHdr = null; /* Reference to page 1 */
  6037. Debug.Assert( !pPager.tempFile && isOpen( pPager.fd ) );
  6038. /* Open page 1 of the file for writing. */
  6039. rc = sqlite3PagerGet( pPager, 1, ref pPgHdr );
  6040. Debug.Assert( pPgHdr == null || rc == SQLITE_OK );
  6041. /* If page one was fetched successfully, and this function is not
  6042. ** operating in direct-mode, make page 1 writable. When not in
  6043. ** direct mode, page 1 is always held in cache and hence the PagerGet()
  6044. ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
  6045. */
  6046. if ( !DIRECT_MODE && ALWAYS( rc == SQLITE_OK ) )
  6047. {
  6048. rc = sqlite3PagerWrite( pPgHdr );
  6049. }
  6050. if ( rc == SQLITE_OK )
  6051. {
  6052. /* Actually do the update of the change counter */
  6053. pager_write_changecounter( pPgHdr );
  6054. /* If running in direct mode, write the contents of page 1 to the file. */
  6055. if ( DIRECT_MODE )
  6056. {
  6057. u8[] zBuf = null;
  6058. Debug.Assert( pPager.dbFileSize > 0 );
  6059. if ( CODEC2( pPager, pPgHdr.pData, 1, SQLITE_ENCRYPT_WRITE_CTX, ref zBuf ) )
  6060. return rc = SQLITE_NOMEM;//CODEC2(pPager, pPgHdr.pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
  6061. if ( rc == SQLITE_OK )
  6062. {
  6063. rc = sqlite3OsWrite( pPager.fd, zBuf, pPager.pageSize, 0 );
  6064. }
  6065. if ( rc == SQLITE_OK )
  6066. {
  6067. pPager.changeCountDone = true;
  6068. }
  6069. }
  6070. else
  6071. {
  6072. pPager.changeCountDone = true;
  6073. }
  6074. }
  6075. /* Release the page reference. */
  6076. sqlite3PagerUnref( pPgHdr );
  6077. }
  6078. return rc;
  6079. }
  6080. /*
  6081. ** Sync the database file to disk. This is a no-op for in-memory databases
  6082. ** or pages with the Pager.noSync flag set.
  6083. **
  6084. ** If successful, or if called on a pager for which it is a no-op, this
  6085. ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
  6086. */
  6087. static int sqlite3PagerSync( Pager pPager )
  6088. {
  6089. long rc = SQLITE_OK;
  6090. if ( !pPager.noSync )
  6091. {
  6092. Debug.Assert(
  6093. #if SQLITE_OMIT_MEMORYDB
  6094. 0 == MEMDB
  6095. #else
  6096. 0 == pPager.memDb
  6097. #endif
  6098. );
  6099. rc = sqlite3OsSync( pPager.fd, pPager.syncFlags );
  6100. }
  6101. else if ( isOpen( pPager.fd ) )
  6102. {
  6103. Debug.Assert(
  6104. #if SQLITE_OMIT_MEMORYDB
  6105. 0 == MEMDB
  6106. #else
  6107. 0 == pPager.memDb
  6108. #endif
  6109. );
  6110. sqlite3OsFileControl( pPager.fd, SQLITE_FCNTL_SYNC_OMITTED, ref rc );
  6111. }
  6112. return (int)rc;
  6113. }
  6114. /*
  6115. ** This function may only be called while a write-transaction is active in
  6116. ** rollback. If the connection is in WAL mode, this call is a no-op.
  6117. ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
  6118. ** the database file, an attempt is made to obtain one.
  6119. **
  6120. ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
  6121. ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
  6122. ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
  6123. ** returned.
  6124. */
  6125. static int sqlite3PagerExclusiveLock( Pager pPager )
  6126. {
  6127. int rc = SQLITE_OK;
  6128. Debug.Assert( pPager.eState == PAGER_WRITER_CACHEMOD
  6129. || pPager.eState == PAGER_WRITER_DBMOD
  6130. || pPager.eState == PAGER_WRITER_LOCKED
  6131. );
  6132. Debug.Assert( assert_pager_state( pPager ) );
  6133. if ( false == pagerUseWal( pPager ) )
  6134. {
  6135. rc = pager_wait_on_lock( pPager, EXCLUSIVE_LOCK );
  6136. }
  6137. return rc;
  6138. }
  6139. /*
  6140. ** Sync the database file for the pager pPager. zMaster points to the name
  6141. ** of a master journal file that should be written into the individual
  6142. ** journal file. zMaster may be NULL, which is interpreted as no master
  6143. ** journal (a single database transaction).
  6144. **
  6145. ** This routine ensures that:
  6146. **
  6147. ** * The database file change-counter is updated,
  6148. ** * the journal is synced (unless the atomic-write optimization is used),
  6149. ** * all dirty pages are written to the database file,
  6150. ** * the database file is truncated (if required), and
  6151. ** * the database file synced.
  6152. **
  6153. ** The only thing that remains to commit the transaction is to finalize
  6154. ** (delete, truncate or zero the first part of) the journal file (or
  6155. ** delete the master journal file if specified).
  6156. **
  6157. ** Note that if zMaster==NULL, this does not overwrite a previous value
  6158. ** passed to an sqlite3PagerCommitPhaseOne() call.
  6159. **
  6160. ** If the final parameter - noSync - is true, then the database file itself
  6161. ** is not synced. The caller must call sqlite3PagerSync() directly to
  6162. ** sync the database file before calling CommitPhaseTwo() to delete the
  6163. ** journal file in this case.
  6164. */
  6165. static int sqlite3PagerCommitPhaseOne(
  6166. Pager pPager, /* Pager object */
  6167. string zMaster, /* If not NULL, the master journal name */
  6168. bool noSync /* True to omit the xSync on the db file */
  6169. )
  6170. {
  6171. int rc = SQLITE_OK; /* Return code */
  6172. Debug.Assert( pPager.eState == PAGER_WRITER_LOCKED
  6173. || pPager.eState == PAGER_WRITER_CACHEMOD
  6174. || pPager.eState == PAGER_WRITER_DBMOD
  6175. || pPager.eState == PAGER_ERROR
  6176. );
  6177. Debug.Assert( assert_pager_state( pPager ) );
  6178. /* If a prior error occurred, report that error again. */
  6179. if ( NEVER( pPager.errCode != 0 ) )
  6180. return pPager.errCode;
  6181. PAGERTRACE( "DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
  6182. pPager.zFilename, zMaster, pPager.dbSize );
  6183. /* If no database changes have been made, return early. */
  6184. if ( pPager.eState < PAGER_WRITER_CACHEMOD )
  6185. return SQLITE_OK;
  6186. if (
  6187. #if SQLITE_OMIT_MEMORYDB
  6188. 0 != MEMDB
  6189. #else
  6190. 0 != pPager.memDb
  6191. #endif
  6192. )
  6193. {
  6194. /* If this is an in-memory db, or no pages have been written to, or this
  6195. ** function has already been called, it is mostly a no-op. However, any
  6196. ** backup in progress needs to be restarted.
  6197. */
  6198. sqlite3BackupRestart( pPager.pBackup );
  6199. }
  6200. else
  6201. {
  6202. if ( pagerUseWal( pPager ) )
  6203. {
  6204. PgHdr pList = sqlite3PcacheDirtyList( pPager.pPCache );
  6205. PgHdr pPageOne = null;
  6206. if ( pList == null )
  6207. {
  6208. /* Must have at least one page for the WAL commit flag.
  6209. ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2null11-null5-18 */
  6210. rc = sqlite3PagerGet( pPager, 1, ref pPageOne );
  6211. pList = pPageOne;
  6212. pList.pDirty = null;
  6213. }
  6214. Debug.Assert( rc == SQLITE_OK );
  6215. if ( ALWAYS( pList ) )
  6216. {
  6217. rc = pagerWalFrames( pPager, pList, pPager.dbSize, 1,
  6218. ( pPager.fullSync ? pPager.syncFlags : (byte)0 )
  6219. );
  6220. }
  6221. sqlite3PagerUnref( pPageOne );
  6222. if ( rc == SQLITE_OK )
  6223. {
  6224. sqlite3PcacheCleanAll( pPager.pPCache );
  6225. }
  6226. }
  6227. else
  6228. {
  6229. /* The following block updates the change-counter. Exactly how it
  6230. ** does this depends on whether or not the atomic-update optimization
  6231. ** was enabled at compile time, and if this transaction meets the
  6232. ** runtime criteria to use the operation:
  6233. **
  6234. ** * The file-system supports the atomic-write property for
  6235. ** blocks of size page-size, and
  6236. ** * This commit is not part of a multi-file transaction, and
  6237. ** * Exactly one page has been modified and store in the journal file.
  6238. **
  6239. ** If the optimization was not enabled at compile time, then the
  6240. ** pager_incr_changecounter() function is called to update the change
  6241. ** counter in 'indirect-mode'. If the optimization is compiled in but
  6242. ** is not applicable to this transaction, call sqlite3JournalCreate()
  6243. ** to make sure the journal file has actually been created, then call
  6244. ** pager_incr_changecounter() to update the change-counter in indirect
  6245. ** mode.
  6246. **
  6247. ** Otherwise, if the optimization is both enabled and applicable,
  6248. ** then call pager_incr_changecounter() to update the change-counter
  6249. ** in 'direct' mode. In this case the journal file will never be
  6250. ** created for this transaction.
  6251. */
  6252. #if SQLITE_ENABLE_ATOMIC_WRITE
  6253. PgHdr *pPg;
  6254. Debug.Assert( isOpen(pPager.jfd)
  6255. || pPager.journalMode==PAGER_JOURNALMODE_OFF
  6256. || pPager.journalMode==PAGER_JOURNALMODE_WAL
  6257. );
  6258. if( !zMaster && isOpen(pPager.jfd)
  6259. && pPager.journalOff==jrnlBufferSize(pPager)
  6260. && pPager.dbSize>=pPager.dbOrigSize
  6261. && (0==(pPg = sqlite3PcacheDirtyList(pPager.pPCache)) || 0==pPg.pDirty)
  6262. ){
  6263. /* Update the db file change counter via the direct-write method. The
  6264. ** following call will modify the in-memory representation of page 1
  6265. ** to include the updated change counter and then write page 1
  6266. ** directly to the database file. Because of the atomic-write
  6267. ** property of the host file-system, this is safe.
  6268. */
  6269. rc = pager_incr_changecounter(pPager, 1);
  6270. }else{
  6271. rc = sqlite3JournalCreate(pPager.jfd);
  6272. if( rc==SQLITE_OK ){
  6273. rc = pager_incr_changecounter(pPager, 0);
  6274. }
  6275. }
  6276. #else
  6277. rc = pager_incr_changecounter( pPager, false );
  6278. #endif
  6279. if ( rc != SQLITE_OK )
  6280. goto commit_phase_one_exit;
  6281. /* If this transaction has made the database smaller, then all pages
  6282. ** being discarded by the truncation must be written to the journal
  6283. ** file. This can only happen in auto-vacuum mode.
  6284. **
  6285. ** Before reading the pages with page numbers larger than the
  6286. ** current value of Pager.dbSize, set dbSize back to the value
  6287. ** that it took at the start of the transaction. Otherwise, the
  6288. ** calls to sqlite3PagerGet() return zeroed pages instead of
  6289. ** reading data from the database file.
  6290. */
  6291. #if !SQLITE_OMIT_AUTOVACUUM
  6292. if ( pPager.dbSize < pPager.dbOrigSize
  6293. && pPager.journalMode != PAGER_JOURNALMODE_OFF
  6294. )
  6295. {
  6296. Pgno i; /* Iterator variable */
  6297. Pgno iSkip = PAGER_MJ_PGNO( pPager ); /* Pending lock page */
  6298. Pgno dbSize = pPager.dbSize; /* Database image size */
  6299. pPager.dbSize = pPager.dbOrigSize;
  6300. for ( i = dbSize + 1; i <= pPager.dbOrigSize; i++ )
  6301. {
  6302. if ( 0 == sqlite3BitvecTest( pPager.pInJournal, i ) && i != iSkip )
  6303. {
  6304. PgHdr pPage = null; /* Page to journal */
  6305. rc = sqlite3PagerGet( pPager, i, ref pPage );
  6306. if ( rc != SQLITE_OK )
  6307. goto commit_phase_one_exit;
  6308. rc = sqlite3PagerWrite( pPage );
  6309. sqlite3PagerUnref( pPage );
  6310. if ( rc != SQLITE_OK )
  6311. goto commit_phase_one_exit;
  6312. }
  6313. }
  6314. pPager.dbSize = dbSize;
  6315. }
  6316. #endif
  6317. /* Write the master journal name into the journal file. If a master
  6318. ** journal file name has already been written to the journal file,
  6319. ** or if zMaster is NULL (no master journal), then this call is a no-op.
  6320. */
  6321. rc = writeMasterJournal( pPager, zMaster );
  6322. if ( rc != SQLITE_OK )
  6323. goto commit_phase_one_exit;
  6324. /* Sync the journal file and write all dirty pages to the database.
  6325. ** If the atomic-update optimization is being used, this sync will not
  6326. ** create the journal file or perform any real IO.
  6327. **
  6328. ** Because the change-counter page was just modified, unless the
  6329. ** atomic-update optimization is used it is almost certain that the
  6330. ** journal requires a sync here. However, in locking_mode=exclusive
  6331. ** on a system under memory pressure it is just possible that this is
  6332. ** not the case. In this case it is likely enough that the redundant
  6333. ** xSync() call will be changed to a no-op by the OS anyhow.
  6334. */
  6335. rc = syncJournal( pPager, 0 );
  6336. if ( rc != SQLITE_OK )
  6337. goto commit_phase_one_exit;
  6338. rc = pager_write_pagelist( pPager, sqlite3PcacheDirtyList( pPager.pPCache ) );
  6339. if ( rc != SQLITE_OK )
  6340. {
  6341. Debug.Assert( rc != SQLITE_IOERR_BLOCKED );
  6342. goto commit_phase_one_exit;
  6343. }
  6344. sqlite3PcacheCleanAll( pPager.pPCache );
  6345. /* If the file on disk is not the same size as the database image,
  6346. ** then use pager_truncate to grow or shrink the file here.
  6347. */
  6348. if ( pPager.dbSize != pPager.dbFileSize )
  6349. {
  6350. Pgno nNew = (Pgno)( pPager.dbSize - ( pPager.dbSize == PAGER_MJ_PGNO( pPager ) ? 1 : 0 ) );
  6351. Debug.Assert( pPager.eState >= PAGER_WRITER_DBMOD );
  6352. rc = pager_truncate( pPager, nNew );
  6353. if ( rc != SQLITE_OK )
  6354. goto commit_phase_one_exit;
  6355. }
  6356. /* Finally, sync the database file. */
  6357. if ( !noSync )
  6358. {
  6359. rc = sqlite3PagerSync( pPager );
  6360. }
  6361. IOTRACE( "DBSYNC %p\n", pPager );
  6362. }
  6363. }
  6364. commit_phase_one_exit:
  6365. if ( rc == SQLITE_OK && !pagerUseWal( pPager ) )
  6366. {
  6367. pPager.eState = PAGER_WRITER_FINISHED;
  6368. }
  6369. return rc;
  6370. }
  6371. /*
  6372. ** When this function is called, the database file has been completely
  6373. ** updated to reflect the changes made by the current transaction and
  6374. ** synced to disk. The journal file still exists in the file-system
  6375. ** though, and if a failure occurs at this point it will eventually
  6376. ** be used as a hot-journal and the current transaction rolled back.
  6377. **
  6378. ** This function finalizes the journal file, either by deleting,
  6379. ** truncating or partially zeroing it, so that it cannot be used
  6380. ** for hot-journal rollback. Once this is done the transaction is
  6381. ** irrevocably committed.
  6382. **
  6383. ** If an error occurs, an IO error code is returned and the pager
  6384. ** moves into the error state. Otherwise, SQLITE_OK is returned.
  6385. */
  6386. static int sqlite3PagerCommitPhaseTwo( Pager pPager )
  6387. {
  6388. int rc = SQLITE_OK; /* Return code */
  6389. /* This routine should not be called if a prior error has occurred.
  6390. ** But if (due to a coding error elsewhere in the system) it does get
  6391. ** called, just return the same error code without doing anything. */
  6392. if ( NEVER( pPager.errCode ) != 0 )
  6393. return pPager.errCode;
  6394. Debug.Assert( pPager.eState == PAGER_WRITER_LOCKED
  6395. || pPager.eState == PAGER_WRITER_FINISHED
  6396. || ( pagerUseWal( pPager ) && pPager.eState == PAGER_WRITER_CACHEMOD )
  6397. );
  6398. Debug.Assert( assert_pager_state( pPager ) );
  6399. /* An optimization. If the database was not actually modified during
  6400. ** this transaction, the pager is running in exclusive-mode and is
  6401. ** using persistent journals, then this function is a no-op.
  6402. **
  6403. ** The start of the journal file currently contains a single journal
  6404. ** header with the nRec field set to 0. If such a journal is used as
  6405. ** a hot-journal during hot-journal rollback, 0 changes will be made
  6406. ** to the database file. So there is no need to zero the journal
  6407. ** header. Since the pager is in exclusive mode, there is no need
  6408. ** to drop any locks either.
  6409. */
  6410. if ( pPager.eState == PAGER_WRITER_LOCKED
  6411. && pPager.exclusiveMode
  6412. && pPager.journalMode == PAGER_JOURNALMODE_PERSIST
  6413. )
  6414. {
  6415. Debug.Assert( pPager.journalOff == JOURNAL_HDR_SZ( pPager ) || 0 == pPager.journalOff );
  6416. pPager.eState = PAGER_READER;
  6417. return SQLITE_OK;
  6418. }
  6419. PAGERTRACE( "COMMIT %d\n", PAGERID( pPager ) );
  6420. rc = pager_end_transaction( pPager, pPager.setMaster );
  6421. return pager_error( pPager, rc );
  6422. }
  6423. /*
  6424. ** If a write transaction is open, then all changes made within the
  6425. ** transaction are reverted and the current write-transaction is closed.
  6426. ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
  6427. ** state if an error occurs.
  6428. **
  6429. ** If the pager is already in PAGER_ERROR state when this function is called,
  6430. ** it returns Pager.errCode immediately. No work is performed in this case.
  6431. **
  6432. ** Otherwise, in rollback mode, this function performs two functions:
  6433. **
  6434. ** 1) It rolls back the journal file, restoring all database file and
  6435. ** in-memory cache pages to the state they were in when the transaction
  6436. ** was opened, and
  6437. **
  6438. ** 2) It finalizes the journal file, so that it is not used for hot
  6439. ** rollback at any point in the future.
  6440. **
  6441. ** Finalization of the journal file (task 2) is only performed if the
  6442. ** rollback is successful.
  6443. **
  6444. ** In WAL mode, all cache-entries containing data modified within the
  6445. ** current transaction are either expelled from the cache or reverted to
  6446. ** their pre-transaction state by re-reading data from the database or
  6447. ** WAL files. The WAL transaction is then closed.
  6448. */
  6449. static int sqlite3PagerRollback( Pager pPager )
  6450. {
  6451. int rc = SQLITE_OK; /* Return code */
  6452. PAGERTRACE( "ROLLBACK %d\n", PAGERID( pPager ) );
  6453. /* PagerRollback() is a no-op if called in READER or OPEN state. If
  6454. ** the pager is already in the ERROR state, the rollback is not
  6455. ** attempted here. Instead, the error code is returned to the caller.
  6456. */
  6457. Debug.Assert( assert_pager_state( pPager ) );
  6458. if ( pPager.eState == PAGER_ERROR )
  6459. return pPager.errCode;
  6460. if ( pPager.eState <= PAGER_READER )
  6461. return SQLITE_OK;
  6462. if ( pagerUseWal( pPager ) )
  6463. {
  6464. int rc2;
  6465. rc = sqlite3PagerSavepoint( pPager, SAVEPOINT_ROLLBACK, -1 );
  6466. rc2 = pager_end_transaction( pPager, pPager.setMaster );
  6467. if ( rc == SQLITE_OK )
  6468. rc = rc2;
  6469. rc = pager_error( pPager, rc );
  6470. }
  6471. else if ( !isOpen( pPager.jfd ) || pPager.eState == PAGER_WRITER_LOCKED )
  6472. {
  6473. int eState = pPager.eState;
  6474. rc = pager_end_transaction( pPager, 0 );
  6475. if (
  6476. #if SQLITE_OMIT_MEMORYDB
  6477. 0==MEMDB
  6478. #else
  6479. 0 == pPager.memDb
  6480. #endif
  6481. && eState > PAGER_WRITER_LOCKED )
  6482. {
  6483. /* This can happen using journal_mode=off. Move the pager to the error
  6484. ** state to indicate that the contents of the cache may not be trusted.
  6485. ** Any active readers will get SQLITE_ABORT.
  6486. */
  6487. pPager.errCode = SQLITE_ABORT;
  6488. pPager.eState = PAGER_ERROR;
  6489. return rc;
  6490. }
  6491. }
  6492. else
  6493. {
  6494. rc = pager_playback( pPager, 0 );
  6495. }
  6496. Debug.Assert( pPager.eState == PAGER_READER || rc != SQLITE_OK );
  6497. Debug.Assert( rc == SQLITE_OK || rc == SQLITE_FULL || ( rc & 0xFF ) == SQLITE_IOERR );
  6498. /* If an error occurs during a ROLLBACK, we can no longer trust the pager
  6499. ** cache. So call pager_error() on the way out to make any error persistent.
  6500. */
  6501. return pager_error( pPager, rc );
  6502. }
  6503. /*
  6504. ** Return TRUE if the database file is opened read-only. Return FALSE
  6505. ** if the database is (in theory) writable.
  6506. */
  6507. static bool sqlite3PagerIsreadonly( Pager pPager )
  6508. {
  6509. return pPager.readOnly;
  6510. }
  6511. /*
  6512. ** Return the number of references to the pager.
  6513. */
  6514. static int sqlite3PagerRefcount( Pager pPager )
  6515. {
  6516. return sqlite3PcacheRefCount( pPager.pPCache );
  6517. }
  6518. /*
  6519. ** Return the approximate number of bytes of memory currently
  6520. ** used by the pager and its associated cache.
  6521. */
  6522. static int sqlite3PagerMemUsed( Pager pPager )
  6523. {
  6524. int perPageSize = pPager.pageSize + pPager.nExtra + 20; //+ sizeof(PgHdr) + 5*sizeof(void*);
  6525. return perPageSize * sqlite3PcachePagecount( pPager.pPCache )
  6526. + 0// Not readily available under C#// sqlite3MallocSize(pPager);
  6527. + pPager.pageSize;
  6528. }
  6529. /*
  6530. ** Return the number of references to the specified page.
  6531. */
  6532. static int sqlite3PagerPageRefcount( DbPage pPage )
  6533. {
  6534. return sqlite3PcachePageRefcount( pPage );
  6535. }
  6536. #if SQLITE_TEST
  6537. /*
  6538. ** This routine is used for testing and analysis only.
  6539. */
  6540. static int[] sqlite3PagerStats( Pager pPager )
  6541. {
  6542. int[] a = new int[11];
  6543. a[0] = sqlite3PcacheRefCount( pPager.pPCache );
  6544. a[1] = sqlite3PcachePagecount( pPager.pPCache );
  6545. a[2] = sqlite3PcacheGetCachesize( pPager.pPCache );
  6546. a[3] = pPager.eState == PAGER_OPEN ? -1 : (int)pPager.dbSize;
  6547. a[4] = pPager.eState;
  6548. a[5] = pPager.errCode;
  6549. a[6] = pPager.nHit;
  6550. a[7] = pPager.nMiss;
  6551. a[8] = 0; /* Used to be pPager.nOvfl */
  6552. a[9] = pPager.nRead;
  6553. a[10] = pPager.nWrite;
  6554. return a;
  6555. }
  6556. #endif
  6557. /*
  6558. ** Return true if this is an in-memory pager.
  6559. */
  6560. static bool sqlite3PagerIsMemdb( Pager pPager )
  6561. {
  6562. #if SQLITE_OMIT_MEMORYDB
  6563. return MEMDB != 0;
  6564. #else
  6565. return pPager.memDb != 0;
  6566. #endif
  6567. }
  6568. /*
  6569. ** Check that there are at least nSavepoint savepoints open. If there are
  6570. ** currently less than nSavepoints open, then open one or more savepoints
  6571. ** to make up the difference. If the number of savepoints is already
  6572. ** equal to nSavepoint, then this function is a no-op.
  6573. **
  6574. ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
  6575. ** occurs while opening the sub-journal file, then an IO error code is
  6576. ** returned. Otherwise, SQLITE_OK.
  6577. */
  6578. static int sqlite3PagerOpenSavepoint( Pager pPager, int nSavepoint )
  6579. {
  6580. int rc = SQLITE_OK; /* Return code */
  6581. int nCurrent = pPager.nSavepoint; /* Current number of savepoints */
  6582. Debug.Assert( pPager.eState >= PAGER_WRITER_LOCKED );
  6583. Debug.Assert( assert_pager_state( pPager ) );
  6584. if ( nSavepoint > nCurrent && pPager.useJournal != 0 )
  6585. {
  6586. int ii; /* Iterator variable */
  6587. PagerSavepoint[] aNew; /* New Pager.aSavepoint array */
  6588. /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
  6589. ** if the allocation fails. Otherwise, zero the new portion in case a
  6590. ** malloc failure occurs while populating it in the for(...) loop below.
  6591. */
  6592. //aNew = (PagerSavepoint *)sqlite3Realloc(
  6593. // pPager.aSavepoint, sizeof(PagerSavepoint)*nSavepoint
  6594. //);
  6595. Array.Resize( ref pPager.aSavepoint, nSavepoint );
  6596. aNew = pPager.aSavepoint;
  6597. //if( null==aNew ){
  6598. // return SQLITE_NOMEM;
  6599. //}
  6600. // memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
  6601. // pPager.aSavepoint = aNew;
  6602. /* Populate the PagerSavepoint structures just allocated. */
  6603. for ( ii = nCurrent; ii < nSavepoint; ii++ )
  6604. {
  6605. aNew[ii] = new PagerSavepoint();
  6606. aNew[ii].nOrig = pPager.dbSize;
  6607. if ( isOpen( pPager.jfd ) && pPager.journalOff > 0 )
  6608. {
  6609. aNew[ii].iOffset = pPager.journalOff;
  6610. }
  6611. else
  6612. {
  6613. aNew[ii].iOffset = (int)JOURNAL_HDR_SZ( pPager );
  6614. }
  6615. aNew[ii].iSubRec = pPager.nSubRec;
  6616. aNew[ii].pInSavepoint = sqlite3BitvecCreate( pPager.dbSize );
  6617. //if ( null == aNew[ii].pInSavepoint )
  6618. //{
  6619. // return SQLITE_NOMEM;
  6620. //}
  6621. if ( pagerUseWal( pPager ) )
  6622. {
  6623. sqlite3WalSavepoint( pPager.pWal, aNew[ii].aWalData );
  6624. }
  6625. pPager.nSavepoint = ii + 1;
  6626. }
  6627. Debug.Assert( pPager.nSavepoint == nSavepoint );
  6628. assertTruncateConstraint( pPager );
  6629. }
  6630. return rc;
  6631. }
  6632. /*
  6633. ** This function is called to rollback or release (commit) a savepoint.
  6634. ** The savepoint to release or rollback need not be the most recently
  6635. ** created savepoint.
  6636. **
  6637. ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
  6638. ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
  6639. ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
  6640. ** that have occurred since the specified savepoint was created.
  6641. **
  6642. ** The savepoint to rollback or release is identified by parameter
  6643. ** iSavepoint. A value of 0 means to operate on the outermost savepoint
  6644. ** (the first created). A value of (Pager.nSavepoint-1) means operate
  6645. ** on the most recently created savepoint. If iSavepoint is greater than
  6646. ** (Pager.nSavepoint-1), then this function is a no-op.
  6647. **
  6648. ** If a negative value is passed to this function, then the current
  6649. ** transaction is rolled back. This is different to calling
  6650. ** sqlite3PagerRollback() because this function does not terminate
  6651. ** the transaction or unlock the database, it just restores the
  6652. ** contents of the database to its original state.
  6653. **
  6654. ** In any case, all savepoints with an index greater than iSavepoint
  6655. ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
  6656. ** then savepoint iSavepoint is also destroyed.
  6657. **
  6658. ** This function may return SQLITE_NOMEM if a memory allocation fails,
  6659. ** or an IO error code if an IO error occurs while rolling back a
  6660. ** savepoint. If no errors occur, SQLITE_OK is returned.
  6661. */
  6662. static int sqlite3PagerSavepoint( Pager pPager, int op, int iSavepoint )
  6663. {
  6664. int rc = pPager.errCode; /* Return code */
  6665. Debug.Assert( op == SAVEPOINT_RELEASE || op == SAVEPOINT_ROLLBACK );
  6666. Debug.Assert( iSavepoint >= 0 || op == SAVEPOINT_ROLLBACK );
  6667. if ( rc == SQLITE_OK && iSavepoint < pPager.nSavepoint )
  6668. {
  6669. int ii; /* Iterator variable */
  6670. int nNew; /* Number of remaining savepoints after this op. */
  6671. /* Figure out how many savepoints will still be active after this
  6672. ** operation. Store this value in nNew. Then free resources associated
  6673. ** with any savepoints that are destroyed by this operation.
  6674. */
  6675. nNew = iSavepoint + ( ( op == SAVEPOINT_RELEASE ) ? 0 : 1 );
  6676. for ( ii = nNew; ii < pPager.nSavepoint; ii++ )
  6677. {
  6678. sqlite3BitvecDestroy( ref pPager.aSavepoint[ii].pInSavepoint );
  6679. }
  6680. pPager.nSavepoint = nNew;
  6681. /* If this is a release of the outermost savepoint, truncate
  6682. ** the sub-journal to zero bytes in size. */
  6683. if ( op == SAVEPOINT_RELEASE )
  6684. {
  6685. if ( nNew == 0 && isOpen( pPager.sjfd ) )
  6686. {
  6687. /* Only truncate if it is an in-memory sub-journal. */
  6688. if ( sqlite3IsMemJournal( pPager.sjfd ) )
  6689. {
  6690. rc = sqlite3OsTruncate( pPager.sjfd, 0 );
  6691. Debug.Assert( rc == SQLITE_OK );
  6692. }
  6693. pPager.nSubRec = 0;
  6694. }
  6695. }
  6696. /* Else this is a rollback operation, playback the specified savepoint.
  6697. ** If this is a temp-file, it is possible that the journal file has
  6698. ** not yet been opened. In this case there have been no changes to
  6699. ** the database file, so the playback operation can be skipped.
  6700. */
  6701. else if ( pagerUseWal( pPager ) || isOpen( pPager.jfd ) )
  6702. {
  6703. PagerSavepoint pSavepoint = ( nNew == 0 ) ? null : pPager.aSavepoint[nNew - 1];
  6704. rc = pagerPlaybackSavepoint( pPager, pSavepoint );
  6705. Debug.Assert( rc != SQLITE_DONE );
  6706. }
  6707. }
  6708. return rc;
  6709. }
  6710. /*
  6711. ** Return the full pathname of the database file.
  6712. */
  6713. static string sqlite3PagerFilename( Pager pPager )
  6714. {
  6715. return pPager.zFilename;
  6716. }
  6717. /*
  6718. ** Return the VFS structure for the pager.
  6719. */
  6720. static sqlite3_vfs sqlite3PagerVfs( Pager pPager )
  6721. {
  6722. return pPager.pVfs;
  6723. }
  6724. /*
  6725. ** Return the file handle for the database file associated
  6726. ** with the pager. This might return NULL if the file has
  6727. ** not yet been opened.
  6728. */
  6729. static sqlite3_file sqlite3PagerFile( Pager pPager )
  6730. {
  6731. return pPager.fd;
  6732. }
  6733. /*
  6734. ** Return the full pathname of the journal file.
  6735. */
  6736. static string sqlite3PagerJournalname( Pager pPager )
  6737. {
  6738. return pPager.zJournal;
  6739. }
  6740. /*
  6741. ** Return true if fsync() calls are disabled for this pager. Return FALSE
  6742. ** if fsync()s are executed normally.
  6743. */
  6744. static bool sqlite3PagerNosync( Pager pPager )
  6745. {
  6746. return pPager.noSync;
  6747. }
  6748. #if SQLITE_HAS_CODEC
  6749. /*
  6750. ** Set or retrieve the codec for this pager
  6751. */
  6752. static void sqlite3PagerSetCodec(
  6753. Pager pPager,
  6754. dxCodec xCodec, //void *(*xCodec)(void*,void*,Pgno,int),
  6755. dxCodecSizeChng xCodecSizeChng, //void (*xCodecSizeChng)(void*,int,int),
  6756. dxCodecFree xCodecFree, //void (*xCodecFree)(void*),
  6757. codec_ctx pCodec
  6758. )
  6759. {
  6760. if ( pPager.xCodecFree != null )
  6761. pPager.xCodecFree( ref pPager.pCodec );
  6762. pPager.xCodec = ( pPager.memDb != 0 ) ? null : xCodec;
  6763. pPager.xCodecSizeChng = xCodecSizeChng;
  6764. pPager.xCodecFree = xCodecFree;
  6765. pPager.pCodec = pCodec;
  6766. pagerReportSize( pPager );
  6767. }
  6768. static object sqlite3PagerGetCodec( Pager pPager )
  6769. {
  6770. return pPager.pCodec;
  6771. }
  6772. #endif
  6773. #if !SQLITE_OMIT_AUTOVACUUM
  6774. /*
  6775. ** Move the page pPg to location pgno in the file.
  6776. **
  6777. ** There must be no references to the page previously located at
  6778. ** pgno (which we call pPgOld) though that page is allowed to be
  6779. ** in cache. If the page previously located at pgno is not already
  6780. ** in the rollback journal, it is not put there by by this routine.
  6781. **
  6782. ** References to the page pPg remain valid. Updating any
  6783. ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
  6784. ** allocated along with the page) is the responsibility of the caller.
  6785. **
  6786. ** A transaction must be active when this routine is called. It used to be
  6787. ** required that a statement transaction was not active, but this restriction
  6788. ** has been removed (CREATE INDEX needs to move a page when a statement
  6789. ** transaction is active).
  6790. **
  6791. ** If the fourth argument, isCommit, is non-zero, then this page is being
  6792. ** moved as part of a database reorganization just before the transaction
  6793. ** is being committed. In this case, it is guaranteed that the database page
  6794. ** pPg refers to will not be written to again within this transaction.
  6795. **
  6796. ** This function may return SQLITE_NOMEM or an IO error code if an error
  6797. ** occurs. Otherwise, it returns SQLITE_OK.
  6798. */
  6799. static int sqlite3PagerMovepage( Pager pPager, DbPage pPg, u32 pgno, int isCommit )
  6800. {
  6801. PgHdr pPgOld; /* The page being overwritten. */
  6802. u32 needSyncPgno = 0; /* Old value of pPg.pgno, if sync is required */
  6803. int rc; /* Return code */
  6804. Pgno origPgno; /* The original page number */
  6805. Debug.Assert( pPg.nRef > 0 );
  6806. Debug.Assert( pPager.eState == PAGER_WRITER_CACHEMOD
  6807. || pPager.eState == PAGER_WRITER_DBMOD
  6808. );
  6809. Debug.Assert( assert_pager_state( pPager ) );
  6810. /* In order to be able to rollback, an in-memory database must journal
  6811. ** the page we are moving from.
  6812. */
  6813. if (
  6814. #if SQLITE_OMIT_MEMORYDB
  6815. 1==MEMDB
  6816. #else
  6817. pPager.memDb != 0
  6818. #endif
  6819. )
  6820. {
  6821. rc = sqlite3PagerWrite( pPg );
  6822. if ( rc != 0 )
  6823. return rc;
  6824. }
  6825. /* If the page being moved is dirty and has not been saved by the latest
  6826. ** savepoint, then save the current contents of the page into the
  6827. ** sub-journal now. This is required to handle the following scenario:
  6828. **
  6829. ** BEGIN;
  6830. ** <journal page X, then modify it in memory>
  6831. ** SAVEPOINT one;
  6832. ** <Move page X to location Y>
  6833. ** ROLLBACK TO one;
  6834. **
  6835. ** If page X were not written to the sub-journal here, it would not
  6836. ** be possible to restore its contents when the "ROLLBACK TO one"
  6837. ** statement were is processed.
  6838. **
  6839. ** subjournalPage() may need to allocate space to store pPg.pgno into
  6840. ** one or more savepoint bitvecs. This is the reason this function
  6841. ** may return SQLITE_NOMEM.
  6842. */
  6843. if ( ( pPg.flags & PGHDR_DIRTY ) != 0
  6844. && subjRequiresPage( pPg )
  6845. && SQLITE_OK != ( rc = subjournalPage( pPg ) )
  6846. )
  6847. {
  6848. return rc;
  6849. }
  6850. PAGERTRACE( "MOVE %d page %d (needSync=%d) moves to %d\n",
  6851. PAGERID( pPager ), pPg.pgno, ( pPg.flags & PGHDR_NEED_SYNC ) != 0 ? 1 : 0, pgno );
  6852. IOTRACE( "MOVE %p %d %d\n", pPager, pPg.pgno, pgno );
  6853. /* If the journal needs to be sync()ed before page pPg.pgno can
  6854. ** be written to, store pPg.pgno in local variable needSyncPgno.
  6855. **
  6856. ** If the isCommit flag is set, there is no need to remember that
  6857. ** the journal needs to be sync()ed before database page pPg.pgno
  6858. ** can be written to. The caller has already promised not to write to it.
  6859. */
  6860. if ( ( ( pPg.flags & PGHDR_NEED_SYNC ) != 0 ) && 0 == isCommit )
  6861. {
  6862. needSyncPgno = pPg.pgno;
  6863. Debug.Assert( pageInJournal( pPg ) || pPg.pgno > pPager.dbOrigSize );
  6864. Debug.Assert( ( pPg.flags & PGHDR_DIRTY ) != 0 );
  6865. }
  6866. /* If the cache contains a page with page-number pgno, remove it
  6867. ** from its hash chain. Also, if the PGHDR_NEED_SYNC was set for
  6868. ** page pgno before the 'move' operation, it needs to be retained
  6869. ** for the page moved there.
  6870. */
  6871. pPg.flags &= ~PGHDR_NEED_SYNC;
  6872. pPgOld = pager_lookup( pPager, pgno );
  6873. Debug.Assert( null == pPgOld || pPgOld.nRef == 1 );
  6874. if ( pPgOld != null )
  6875. {
  6876. pPg.flags |= ( pPgOld.flags & PGHDR_NEED_SYNC );
  6877. if (
  6878. #if SQLITE_OMIT_MEMORYDB
  6879. 1==MEMDB
  6880. #else
  6881. pPager.memDb != 0
  6882. #endif
  6883. )
  6884. {
  6885. /* Do not discard pages from an in-memory database since we might
  6886. ** need to rollback later. Just move the page out of the way. */
  6887. sqlite3PcacheMove( pPgOld, pPager.dbSize + 1 );
  6888. }
  6889. else
  6890. {
  6891. sqlite3PcacheDrop( pPgOld );
  6892. }
  6893. }
  6894. origPgno = pPg.pgno;
  6895. sqlite3PcacheMove( pPg, pgno );
  6896. sqlite3PcacheMakeDirty( pPg );
  6897. /* For an in-memory database, make sure the original page continues
  6898. ** to exist, in case the transaction needs to roll back. Use pPgOld
  6899. ** as the original page since it has already been allocated.
  6900. */
  6901. if (
  6902. #if SQLITE_OMIT_MEMORYDB
  6903. 0!=MEMDB
  6904. #else
  6905. 0 != pPager.memDb
  6906. #endif
  6907. )
  6908. {
  6909. Debug.Assert( pPgOld );
  6910. sqlite3PcacheMove( pPgOld, origPgno );
  6911. sqlite3PagerUnref( pPgOld );
  6912. }
  6913. if ( needSyncPgno != 0 )
  6914. {
  6915. /* If needSyncPgno is non-zero, then the journal file needs to be
  6916. ** sync()ed before any data is written to database file page needSyncPgno.
  6917. ** Currently, no such page exists in the page-cache and the
  6918. ** "is journaled" bitvec flag has been set. This needs to be remedied by
  6919. ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
  6920. ** flag.
  6921. **
  6922. ** If the attempt to load the page into the page-cache fails, (due
  6923. ** to a malloc() or IO failure), clear the bit in the pInJournal[]
  6924. ** array. Otherwise, if the page is loaded and written again in
  6925. ** this transaction, it may be written to the database file before
  6926. ** it is synced into the journal file. This way, it may end up in
  6927. ** the journal file twice, but that is not a problem.
  6928. */
  6929. PgHdr pPgHdr = null;
  6930. rc = sqlite3PagerGet( pPager, needSyncPgno, ref pPgHdr );
  6931. if ( rc != SQLITE_OK )
  6932. {
  6933. if ( needSyncPgno <= pPager.dbOrigSize )
  6934. {
  6935. Debug.Assert( pPager.pTmpSpace != null );
  6936. u32[] pTemp = new u32[pPager.pTmpSpace.Length];
  6937. sqlite3BitvecClear( pPager.pInJournal, needSyncPgno, pTemp );//pPager.pTmpSpace );
  6938. }
  6939. return rc;
  6940. }
  6941. pPgHdr.flags |= PGHDR_NEED_SYNC;
  6942. sqlite3PcacheMakeDirty( pPgHdr );
  6943. sqlite3PagerUnref( pPgHdr );
  6944. }
  6945. return SQLITE_OK;
  6946. }
  6947. #endif
  6948. /*
  6949. ** Return a pointer to the data for the specified page.
  6950. */
  6951. static byte[] sqlite3PagerGetData( DbPage pPg )
  6952. {
  6953. Debug.Assert( pPg.nRef > 0 || pPg.pPager.memDb != 0 );
  6954. return pPg.pData;
  6955. }
  6956. /*
  6957. ** Return a pointer to the Pager.nExtra bytes of "extra" space
  6958. ** allocated along with the specified page.
  6959. */
  6960. static MemPage sqlite3PagerGetExtra( DbPage pPg )
  6961. {
  6962. return pPg.pExtra;
  6963. }
  6964. /*
  6965. ** Get/set the locking-mode for this pager. Parameter eMode must be one
  6966. ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
  6967. ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
  6968. ** the locking-mode is set to the value specified.
  6969. **
  6970. ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
  6971. ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
  6972. ** locking-mode.
  6973. */
  6974. static bool sqlite3PagerLockingMode( Pager pPager, int eMode )
  6975. {
  6976. Debug.Assert( eMode == PAGER_LOCKINGMODE_QUERY
  6977. || eMode == PAGER_LOCKINGMODE_NORMAL
  6978. || eMode == PAGER_LOCKINGMODE_EXCLUSIVE );
  6979. Debug.Assert( PAGER_LOCKINGMODE_QUERY < 0 );
  6980. Debug.Assert( PAGER_LOCKINGMODE_NORMAL >= 0 && PAGER_LOCKINGMODE_EXCLUSIVE >= 0 );
  6981. Debug.Assert( pPager.exclusiveMode || false == sqlite3WalHeapMemory( pPager.pWal ) );
  6982. if ( eMode >= 0 && !pPager.tempFile && !sqlite3WalHeapMemory( pPager.pWal ) )
  6983. {
  6984. pPager.exclusiveMode = eMode != 0;
  6985. }
  6986. return pPager.exclusiveMode;
  6987. }
  6988. /*
  6989. ** Set the journal-mode for this pager. Parameter eMode must be one of:
  6990. **
  6991. ** PAGER_JOURNALMODE_DELETE
  6992. ** PAGER_JOURNALMODE_TRUNCATE
  6993. ** PAGER_JOURNALMODE_PERSIST
  6994. ** PAGER_JOURNALMODE_OFF
  6995. ** PAGER_JOURNALMODE_MEMORY
  6996. ** PAGER_JOURNALMODE_WAL
  6997. **
  6998. ** The journalmode is set to the value specified if the change is allowed.
  6999. ** The change may be disallowed for the following reasons:
  7000. **
  7001. ** * An in-memory database can only have its journal_mode set to _OFF
  7002. ** or _MEMORY.
  7003. **
  7004. ** * Temporary databases cannot have _WAL journalmode.
  7005. **
  7006. ** The returned indicate the current (possibly updated) journal-mode.
  7007. */
  7008. static int sqlite3PagerSetJournalMode( Pager pPager, int eMode )
  7009. {
  7010. u8 eOld = pPager.journalMode; /* Prior journalmode */
  7011. #if SQLITE_DEBUG
  7012. /* The print_pager_state() routine is intended to be used by the debugger
  7013. ** only. We invoke it once here to suppress a compiler warning. */
  7014. print_pager_state( pPager );
  7015. #endif
  7016. /* The eMode parameter is always valid */
  7017. Debug.Assert( eMode == PAGER_JOURNALMODE_DELETE
  7018. || eMode == PAGER_JOURNALMODE_TRUNCATE
  7019. || eMode == PAGER_JOURNALMODE_PERSIST
  7020. || eMode == PAGER_JOURNALMODE_OFF
  7021. || eMode == PAGER_JOURNALMODE_WAL
  7022. || eMode == PAGER_JOURNALMODE_MEMORY );
  7023. /* This routine is only called from the OP_JournalMode opcode, and
  7024. ** the logic there will never allow a temporary file to be changed
  7025. ** to WAL mode.
  7026. */
  7027. Debug.Assert( pPager.tempFile == false || eMode != PAGER_JOURNALMODE_WAL );
  7028. /* Do allow the journalmode of an in-memory database to be set to
  7029. ** anything other than MEMORY or OFF
  7030. */
  7031. if (
  7032. #if SQLITE_OMIT_MEMORYDB
  7033. 1==MEMDB
  7034. #else
  7035. 1 == pPager.memDb
  7036. #endif
  7037. )
  7038. {
  7039. Debug.Assert( eOld == PAGER_JOURNALMODE_MEMORY || eOld == PAGER_JOURNALMODE_OFF );
  7040. if ( eMode != PAGER_JOURNALMODE_MEMORY && eMode != PAGER_JOURNALMODE_OFF )
  7041. {
  7042. eMode = eOld;
  7043. }
  7044. }
  7045. if ( eMode != eOld )
  7046. {
  7047. /* Change the journal mode. */
  7048. Debug.Assert( pPager.eState != PAGER_ERROR );
  7049. pPager.journalMode = (u8)eMode;
  7050. /* When transistioning from TRUNCATE or PERSIST to any other journal
  7051. ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
  7052. ** delete the journal file.
  7053. */
  7054. Debug.Assert( ( PAGER_JOURNALMODE_TRUNCATE & 5 ) == 1 );
  7055. Debug.Assert( ( PAGER_JOURNALMODE_PERSIST & 5 ) == 1 );
  7056. Debug.Assert( ( PAGER_JOURNALMODE_DELETE & 5 ) == 0 );
  7057. Debug.Assert( ( PAGER_JOURNALMODE_MEMORY & 5 ) == 4 );
  7058. Debug.Assert( ( PAGER_JOURNALMODE_OFF & 5 ) == 0 );
  7059. Debug.Assert( ( PAGER_JOURNALMODE_WAL & 5 ) == 5 );
  7060. Debug.Assert( isOpen( pPager.fd ) || pPager.exclusiveMode );
  7061. if ( !pPager.exclusiveMode && ( eOld & 5 ) == 1 && ( eMode & 1 ) == 0 )
  7062. {
  7063. /* In this case we would like to delete the journal file. If it is
  7064. ** not possible, then that is not a problem. Deleting the journal file
  7065. ** here is an optimization only.
  7066. **
  7067. ** Before deleting the journal file, obtain a RESERVED lock on the
  7068. ** database file. This ensures that the journal file is not deleted
  7069. ** while it is in use by some other client.
  7070. */
  7071. sqlite3OsClose( pPager.jfd );
  7072. if ( pPager.eLock >= RESERVED_LOCK )
  7073. {
  7074. sqlite3OsDelete( pPager.pVfs, pPager.zJournal, 0 );
  7075. }
  7076. else
  7077. {
  7078. int rc = SQLITE_OK;
  7079. int state = pPager.eState;
  7080. Debug.Assert( state == PAGER_OPEN || state == PAGER_READER );
  7081. if ( state == PAGER_OPEN )
  7082. {
  7083. rc = sqlite3PagerSharedLock( pPager );
  7084. }
  7085. if ( pPager.eState == PAGER_READER )
  7086. {
  7087. Debug.Assert( rc == SQLITE_OK );
  7088. rc = pagerLockDb( pPager, RESERVED_LOCK );
  7089. }
  7090. if ( rc == SQLITE_OK )
  7091. {
  7092. sqlite3OsDelete( pPager.pVfs, pPager.zJournal, 0 );
  7093. }
  7094. if ( rc == SQLITE_OK && state == PAGER_READER )
  7095. {
  7096. pagerUnlockDb( pPager, SHARED_LOCK );
  7097. }
  7098. else if ( state == PAGER_OPEN )
  7099. {
  7100. pager_unlock( pPager );
  7101. }
  7102. Debug.Assert( state == pPager.eState );
  7103. }
  7104. }
  7105. }
  7106. /* Return the new journal mode */
  7107. return (int)pPager.journalMode;
  7108. }
  7109. /*
  7110. ** Return the current journal mode.
  7111. */
  7112. static int sqlite3PagerGetJournalMode( Pager pPager )
  7113. {
  7114. return (int)pPager.journalMode;
  7115. }
  7116. /*
  7117. ** Return TRUE if the pager is in a state where it is OK to change the
  7118. ** journalmode. Journalmode changes can only happen when the database
  7119. ** is unmodified.
  7120. */
  7121. static int sqlite3PagerOkToChangeJournalMode( Pager pPager )
  7122. {
  7123. Debug.Assert( assert_pager_state( pPager ) );
  7124. if ( pPager.eState >= PAGER_WRITER_CACHEMOD )
  7125. return 0;
  7126. if ( NEVER( isOpen( pPager.jfd ) && pPager.journalOff > 0 ) )
  7127. return 0;
  7128. return 1;
  7129. }
  7130. /*
  7131. ** Get/set the size-limit used for persistent journal files.
  7132. **
  7133. ** Setting the size limit to -1 means no limit is enforced.
  7134. ** An attempt to set a limit smaller than -1 is a no-op.
  7135. */
  7136. static i64 sqlite3PagerJournalSizeLimit( Pager pPager, i64 iLimit )
  7137. {
  7138. if ( iLimit >= -1 )
  7139. {
  7140. pPager.journalSizeLimit = iLimit;
  7141. sqlite3WalLimit( pPager.pWal, iLimit );
  7142. }
  7143. return pPager.journalSizeLimit;
  7144. }
  7145. /*
  7146. ** Return a pointer to the pPager.pBackup variable. The backup module
  7147. ** in backup.c maintains the content of this variable. This module
  7148. ** uses it opaquely as an argument to sqlite3BackupRestart() and
  7149. ** sqlite3BackupUpdate() only.
  7150. */
  7151. static sqlite3_backup sqlite3PagerBackupPtr( Pager pPager )
  7152. {
  7153. return pPager.pBackup;
  7154. }
  7155. #if !SQLITE_OMIT_WAL
  7156. /*
  7157. ** This function is called when the user invokes "PRAGMA wal_checkpoint",
  7158. ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
  7159. ** or wal_blocking_checkpoint() API functions.
  7160. **
  7161. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  7162. */
  7163. int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
  7164. int rc = SQLITE_OK;
  7165. if( pPager.pWal ){
  7166. rc = sqlite3WalCheckpoint(pPager.pWal, eMode,
  7167. pPager.xBusyHandler, pPager.pBusyHandlerArg,
  7168. pPager.ckptSyncFlags, pPager.pageSize, (u8 *)pPager.pTmpSpace,
  7169. pnLog, pnCkpt
  7170. );
  7171. }
  7172. return rc;
  7173. }
  7174. int sqlite3PagerWalCallback(Pager *pPager){
  7175. return sqlite3WalCallback(pPager.pWal);
  7176. }
  7177. /*
  7178. ** Return true if the underlying VFS for the given pager supports the
  7179. ** primitives necessary for write-ahead logging.
  7180. */
  7181. int sqlite3PagerWalSupported(Pager *pPager){
  7182. const sqlite3_io_methods *pMethods = pPager.fd->pMethods;
  7183. return pPager.exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
  7184. }
  7185. /*
  7186. ** Attempt to take an exclusive lock on the database file. If a PENDING lock
  7187. ** is obtained instead, immediately release it.
  7188. */
  7189. static int pagerExclusiveLock(Pager *pPager){
  7190. int rc; /* Return code */
  7191. assert( pPager.eLock==SHARED_LOCK || pPager.eLock==EXCLUSIVE_LOCK );
  7192. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  7193. if( rc!=SQLITE_OK ){
  7194. /* If the attempt to grab the exclusive lock failed, release the
  7195. ** pending lock that may have been obtained instead. */
  7196. pagerUnlockDb(pPager, SHARED_LOCK);
  7197. }
  7198. return rc;
  7199. }
  7200. /*
  7201. ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
  7202. ** exclusive-locking mode when this function is called, take an EXCLUSIVE
  7203. ** lock on the database file and use heap-memory to store the wal-index
  7204. ** in. Otherwise, use the normal shared-memory.
  7205. */
  7206. static int pagerOpenWal(Pager *pPager){
  7207. int rc = SQLITE_OK;
  7208. assert( pPager.pWal==0 && pPager.tempFile==0 );
  7209. assert( pPager.eLock==SHARED_LOCK || pPager.eLock==EXCLUSIVE_LOCK || pPager.noReadlock);
  7210. /* If the pager is already in exclusive-mode, the WAL module will use
  7211. ** heap-memory for the wal-index instead of the VFS shared-memory
  7212. ** implementation. Take the exclusive lock now, before opening the WAL
  7213. ** file, to make sure this is safe.
  7214. */
  7215. if( pPager.exclusiveMode ){
  7216. rc = pagerExclusiveLock(pPager);
  7217. }
  7218. /* Open the connection to the log file. If this operation fails,
  7219. ** (e.g. due to malloc() failure), return an error code.
  7220. */
  7221. if( rc==SQLITE_OK ){
  7222. rc = sqlite3WalOpen(pPager.pVfs,
  7223. pPager.fd, pPager.zWal, pPager.exclusiveMode, &pPager.pWal
  7224. pPager.journalSizeLimit, &pPager.pWal
  7225. );
  7226. }
  7227. return rc;
  7228. }
  7229. /*
  7230. ** The caller must be holding a SHARED lock on the database file to call
  7231. ** this function.
  7232. **
  7233. ** If the pager passed as the first argument is open on a real database
  7234. ** file (not a temp file or an in-memory database), and the WAL file
  7235. ** is not already open, make an attempt to open it now. If successful,
  7236. ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
  7237. ** not support the xShmXXX() methods, return an error code. *pbOpen is
  7238. ** not modified in either case.
  7239. **
  7240. ** If the pager is open on a temp-file (or in-memory database), or if
  7241. ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
  7242. ** without doing anything.
  7243. */
  7244. int sqlite3PagerOpenWal(
  7245. Pager *pPager, /* Pager object */
  7246. int *pbOpen /* OUT: Set to true if call is a no-op */
  7247. ){
  7248. int rc = SQLITE_OK; /* Return code */
  7249. assert( assert_pager_state(pPager) );
  7250. assert( pPager.eState==PAGER_OPEN || pbOpen );
  7251. assert( pPager.eState==PAGER_READER || !pbOpen );
  7252. assert( pbOpen==0 || *pbOpen==0 );
  7253. assert( pbOpen!=0 || (!pPager.tempFile && !pPager.pWal) );
  7254. if( !pPager.tempFile && !pPager.pWal ){
  7255. if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
  7256. /* Close any rollback journal previously open */
  7257. sqlite3OsClose(pPager.jfd);
  7258. rc = pagerOpenWal(pPager);
  7259. if( rc==SQLITE_OK ){
  7260. pPager.journalMode = PAGER_JOURNALMODE_WAL;
  7261. pPager.eState = PAGER_OPEN;
  7262. }
  7263. }else{
  7264. *pbOpen = 1;
  7265. }
  7266. return rc;
  7267. }
  7268. /*
  7269. ** This function is called to close the connection to the log file prior
  7270. ** to switching from WAL to rollback mode.
  7271. **
  7272. ** Before closing the log file, this function attempts to take an
  7273. ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
  7274. ** error (SQLITE_BUSY) is returned and the log connection is not closed.
  7275. ** If successful, the EXCLUSIVE lock is not released before returning.
  7276. */
  7277. int sqlite3PagerCloseWal(Pager *pPager){
  7278. int rc = SQLITE_OK;
  7279. assert( pPager.journalMode==PAGER_JOURNALMODE_WAL );
  7280. /* If the log file is not already open, but does exist in the file-system,
  7281. ** it may need to be checkpointed before the connection can switch to
  7282. ** rollback mode. Open it now so this can happen.
  7283. */
  7284. if( !pPager.pWal ){
  7285. int logexists = 0;
  7286. rc = pagerLockDb(pPager, SHARED_LOCK);
  7287. if( rc==SQLITE_OK ){
  7288. rc = sqlite3OsAccess(
  7289. pPager.pVfs, pPager.zWal, SQLITE_ACCESS_EXISTS, &logexists
  7290. );
  7291. }
  7292. if( rc==SQLITE_OK && logexists ){
  7293. rc = pagerOpenWal(pPager);
  7294. }
  7295. }
  7296. /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
  7297. ** the database file, the log and log-summary files will be deleted.
  7298. */
  7299. if( rc==SQLITE_OK && pPager.pWal ){
  7300. rc = pagerExclusiveLock(pPager);
  7301. if( rc==SQLITE_OK ){
  7302. rc = sqlite3WalClose(pPager.pWal, pPager.ckptSyncFlags,
  7303. pPager.pageSize, (u8*)pPager.pTmpSpace);
  7304. pPager.pWal = 0;
  7305. }
  7306. }
  7307. return rc;
  7308. }
  7309. #if SQLITE_HAS_CODEC
  7310. /*
  7311. ** This function is called by the wal module when writing page content
  7312. ** into the log file.
  7313. **
  7314. ** This function returns a pointer to a buffer containing the encrypted
  7315. ** page content. If a malloc fails, this function may return NULL.
  7316. */
  7317. void sqlite3PagerCodec(PgHdr *pPg){
  7318. voidaData = 0;
  7319. CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
  7320. return aData;
  7321. }
  7322. #endif //* SQLITE_HAS_CODEC */
  7323. #endif //* !SQLITE_OMIT_WAL */
  7324. #endif // * SQLITE_OMIT_DISKIO */
  7325. }
  7326. }