PageRenderTime 101ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 1ms

/drivers/sqlite-wp7/sqlite/pager_c.cs

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