(*--------------------------------------------------------------------------- Copyright (c) 2025 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*) (* Opening, closing, syncing and recovering a {!Handle.t}, and the transaction and savepoint boundaries its durability points hang from. It reads and writes every field of the record directly: the record is the shared state the rest of the engine mutates, not an abstraction over it. *) open Model open Handle open Durability open Page1 include Session_state let snapshot_txn t = { pager_snap = Btree.Pager.snapshot t.pager; schema_snap = Handle.snapshot t } let restore_txn t snap = Btree.Pager.rollback t.pager snap.pager_snap; restore_schema t snap.schema_snap (* Write the savepoint at slot [i] of [tx] over what the handle holds now. *) let save_at t tx i = tx.savepoints.(i).schema_at <- Handle.snapshot t (* Open a savepoint over [tx]'s open ones, in the slot of its depth; the slots grow only past the deepest a transaction of the handle has reached. *) let push_savepoint t tx = let n = Array.length tx.savepoints in if tx.depth = n then begin let slots = tx.savepoints in let schema_at = tx.began.schema_snap in tx.savepoints <- Array.init (max 4 (2 * n)) (fun i -> if i < n then slots.(i) else { schema_at }) end; save_at t tx tx.depth; tx.depth <- tx.depth + 1 (* What the file and its log looked like, read as SQLite's pager reads the file's version before it trusts its cache (pager.c, dbFileVers): the 16 bytes at offset 24 of the database header and the file's size; and the log's {!Durability.wal_stamp}. Any commit or checkpoint another handle made moves one of them. [None] for a handle with no file, and for a log it cannot read. *) let physical_stamp t = match (t.db_path, t.file) with | Some path, Some file -> let db_size = Optint.Int63.to_int (Eio.File.stat file).size in let db_version = if db_size < 40 then "" else begin let buf = Cstruct.create 16 in Eio.File.pread_exact file ~file_offset:(Optint.Int63.of_int 24) [ buf ]; Cstruct.to_string buf end in Option.map (Fmt.str "%d:%s:%s" db_size db_version) (Durability.wal_stamp (wal_path path)) | _ -> None (* Whether the connection has a transaction open, by [BEGIN] or [SAVEPOINT], which a statement of its own does not count: what sqlite3 asks of db->autoCommit before a statement it refuses inside one. *) let in_transaction t = not (Sql.Private.Connection.autocommit (Handle.connection t)) (* A logical writable handle attaches an exclusive physical session before touching its file. The cache it kept across the unlocked interval stands only if the file and its log are as its last session left them ({!physical_stamp}); otherwise the pager and schema are rebuilt from the file, with whatever a crash of another process left put back. *) (* The pager and schema of a writable handle rebuilt from the commit its WAL-index session names. *) let rebuild_from_index t file ~page_size ?wal () = let pager = Btree_eio.Pager.v ~page_size ?wal file in install_pager t pager; t.journal_mode <- `Wal; load_schema t; t.wal_seen <- no_wal; t.file_change_seen <- file_change_counter file; t.alone_seen <- None; Handle.Plans.clear t.plan_cache (* The pager and schema of a writable handle read again from a rollback-journal file it holds SHARED on, which no commit moves and no hot journal stands beside: nothing is put back, since a read session writes nothing. *) let reload_journal t file = let ro = (file :> Eio.File.ro_ty Eio.Resource.t) in let page_size = Option.value ~default:default_page_size (header_page_size ro) in install_pager t (Btree_eio.Pager.v ~page_size file); t.journal_mode <- `Journal; load_schema t; t.wal_seen <- no_wal; t.file_change_seen <- file_change_counter ro; t.alone_seen <- None; Handle.Plans.clear t.plan_cache (* The end of a writable handle's read session: what the file and its log looked like goes into [detached_stamp], so the next session keeps the cache where neither moved, and the read mark and SHARED go back. *) let end_read_session t = match t.shared with | Some shared when (not t.read_only) && Option.is_none t.claim -> t.txn_read <- false; Fun.protect ~finally:(fun () -> Option.iter Wal_index.close t.wal; t.wal <- None; t.shared <- None; Writer_lock.release shared) (fun () -> t.detached_stamp <- (match (t.wal, t.file) with | Some index, Some file -> index_stamp ~file index | _ -> physical_stamp t)) | Some _ | None -> () (* The end of a read session that failed part way. It wrote no page, so its failure ends the session, not the physical session (session_state.mli, sync_journal), and the handle reads and writes again: its [detached_stamp] is [None], so the next session reads the file again over the cache the failure left half rebuilt. *) let abandon_read t = Fun.protect ~finally:(fun () -> Option.iter Writer_lock.release t.shared; t.shared <- None) (fun () -> Option.iter Wal_index.close t.wal; t.wal <- None) (* A read session of a writable handle on a rollback-journal file, as a sqlite3 connection reads one (lockingv3.html, section 3): SHARED, under which no other connection commits, and the cache kept where the file is as the last session left it ({!physical_stamp}), read again otherwise. [false], holding nothing, where the file needs a write session: a hot journal to roll back, or a log beside it to fold in. *) let read_journal t path file lock = let ro = (file :> Eio.File.ro_ty Eio.Resource.t) in let shared = take_shared ~busy:t.busy path lock in match file_journal_mode ro = Some `Journal && (not (Eio.Path.is_file (wal_path path))) && not (journal_is_hot ~db:ro (journal_path path) && Option.is_some (Writer_lock.idle lock) && not (Writer_lock.reserved_elsewhere lock)) with | exception e -> Writer_lock.release shared; raise e | false -> Writer_lock.release shared; false | true -> ( t.shared <- Some shared; let stamp = t.detached_stamp in t.detached_stamp <- None; match if Option.is_none stamp || stamp <> physical_stamp t then reload_journal t file with | () -> true | exception e -> abandon_read t; raise e) (* A read session of a writable handle on a WAL database under its WAL-index, as a sqlite3 connection reads one (wal.c, walTryBeginRead): SHARED on the file and a read mark at the last commit, which keeps every checkpoint from copying past it and no writer out. The cache stands while the index names the commit the handle's last session left; otherwise the pager is rebuilt from the file and the frames the snapshot names. [false], holding nothing, where the index cannot be written. *) let read_indexed t path file lock sw = let shared = take_shared ~busy:t.busy path lock in match index_session ?held:t.index_hold ~sw ~busy:t.busy path file Wal_index.begin_read with | exception e -> Writer_lock.release shared; raise e | `Unwritable -> Writer_lock.release shared; t.index_read_only <- true; false | `Busy reason -> Writer_lock.release shared; Model.fail_busy "database is locked: %a: %s" Eio.Path.pp path reason | `Held index -> ( t.shared <- Some shared; t.wal <- Some index; hold_index ~sw t index; let stamp = t.detached_stamp in t.detached_stamp <- None; match let page_size, wal = index_source ~file:(file :> Eio.File.ro_ty Eio.Resource.t) index in if stamp <> index_stamp ~file index then rebuild_from_index t file ~page_size ?wal () else ignore (bind_index_source t wal : bool) with | () -> true | exception e -> abandon_read t; raise e) (* A write session of a WAL database under its WAL-index, as a sqlite3 connection writes one (walformat.html, section 2.3.2): SHARED on the file, which readers hold too, and the index's WRITE lock, which keeps out every other writer and no reader. The cache stands while the index names the commit the handle's last session left; otherwise the pager is rebuilt from the file and the frames the index names. [false] where the index cannot be written, and the session is the EXCLUSIVE one of {!attach}. *) let attach_indexed t path file lock sw = let claim = match Writer_lock.take_wal_session ~busy:t.busy lock with | Some claim -> claim | None -> Model.fail_busy "database is locked: %a has an active session" Eio.Path.pp path in (* A session that fails once it holds the WRITE lock keeps it and its claim, and refuses every later access, as a failure past {!attach}'s claim does: what the failure left is not known. *) let failed index = t.claim <- Some claim; t.wal <- Some index; t.physical_failed <- true in match index_session ~on_failure:failed ?held:t.index_hold ~sw ~busy:t.busy path file Wal_index.begin_write with | exception e when not t.physical_failed -> Writer_lock.release claim; raise e | `Unwritable -> Writer_lock.release claim; t.index_read_only <- true; false | `Busy reason -> Writer_lock.release claim; Model.fail_busy "database is locked: %a: %s" Eio.Path.pp path reason | `Held index -> ( t.claim <- Some claim; t.wal <- Some index; hold_index ~sw t index; let stamp = t.detached_stamp in t.detached_stamp <- None; match (* The log is checked where the handle opens it, once for the life of its descriptor, as sqlite3 reads a log's header only when it recovers the index from it (walIndexRecover); a WAL session reads no rollback journal, which {!indexed} keeps out. *) let page_size, wal = index_source ~file:(file :> Eio.File.ro_ty Eio.Resource.t) index in if stamp <> index_stamp ~file index then rebuild_from_index t file ~page_size ?wal () else ignore (bind_index_source t wal : bool) with | () -> true | exception e -> t.physical_failed <- true; raise e) (* A write session. A WAL handle reads the file's mode and takes the WAL-index's write session ({!attach_indexed}); a rollback-journal handle asks for EXCLUSIVE before it reads anything of the file, so a session that has to wait is waiting from its first step, and the file's mode read under EXCLUSIVE moves the handle to WAL for its next session where another connection changed it. A read session the handle holds ends first: what it read is read again where the file moved. *) let attach ?sw t = if t.physical_failed then Catalog.Error.fail_runtime "Sqlite: physical session failed; close and reopen the handle"; end_read_session t; let sw = match sw with Some _ -> sw | None -> t.sw in match (t.read_only, t.claim, t.db_path, t.writable_file, t.lock_file, sw) with | false, None, Some path, Some file, Some lock, Some sw when t.journal_mode = `Wal && indexed (file :> Eio.File.ro_ty Eio.Resource.t) path && attach_indexed t path file lock sw -> () | false, None, Some path, Some file, Some lock, _ -> ( let claim = match Writer_lock.take_session ~busy:t.busy lock with | Some claim -> claim | None -> Model.fail_busy "database is locked: %a has an active session" Eio.Path.pp path in t.claim <- Some claim; let stamp = t.detached_stamp in t.detached_stamp <- None; match if Option.is_none stamp || stamp <> physical_stamp t then begin let pager = recovered_pager ~file ~path in install_pager t pager; (* A file of no pages states no mode, and the handle's stands. *) t.journal_mode <- Option.value (file_journal_mode file) ~default:t.journal_mode; load_schema t; t.wal_seen <- wal_mark (wal_path path); t.file_change_seen <- file_change_counter file; t.alone_seen <- None; Handle.Plans.clear t.plan_cache end with | () -> () | exception e -> t.physical_failed <- true; raise e) | _ -> () (* A transaction that holds no session has written nothing, since a write takes the write session and keeps it until the transaction ends; its rollback points are taken again over the pager and schema its first session reads, which may have been read again from a file another connection moved. *) let resnapshot t = match t.transaction with | Some tx when not (Btree.Pager.has_dirty t.pager) -> tx.began <- snapshot_txn t; for i = 0 to tx.depth - 1 do save_at t tx i done | Some _ | None -> () let in_session t = Option.is_some t.claim || Option.is_some t.shared (* A session for a writable handle that holds none, taken as a door reads: a read session on a file of the host in either mode ({!read_journal}, {!read_indexed}), and the write session where the file needs one or has no host name, whose claims count in this process alone. An open transaction takes its rollback points over what the new session reads ({!resnapshot}). *) let attach_read t = if t.physical_failed then Catalog.Error.fail_runtime "Sqlite: physical session failed; close and reopen the handle"; match (t.read_only, in_session t, t.db_path, t.writable_file, t.lock_file) with | true, _, _, _, _ | false, true, _, _, _ -> () | false, false, Some path, Some file, Some lock when Option.is_some (Eio.Path.native path) -> let ro = (file :> Eio.File.ro_ty Eio.Resource.t) in let read = match (file_journal_mode ro, t.sw) with | Some `Wal, Some sw -> indexed ro path && read_indexed t path file lock sw | Some `Journal, _ -> read_journal t path file lock | (Some `Wal | None), _ -> false in if not read then attach t; resnapshot t | false, false, _, _, _ -> attach t; if in_session t then resnapshot t (* sqlite3 calls no busy handler for a transaction that holds a read already (btree.c, sqlite3BtreeBeginTrans): in a rollback journal the writer it would wait for waits for this SHARED, and under a WAL-index that writer's commit would make the snapshot stale. *) let no_wait = Writer_lock.busy 0. (* The write session of a transaction that has read, on the snapshot it read: in a rollback journal the claim, taken while SHARED keeps the file as it was read; under a WAL-index the WRITE lock, refused as SQLITE_BUSY_SNAPSHOT where another connection committed since ({!Wal_index.begin_write}). A refusal leaves the read session as it was. *) let upgrade t = match (t.shared, t.db_path, t.lock_file) with | Some shared, Some path, Some lock -> ( let refused reason = Model.fail_busy "database is locked: %a: %s" Eio.Path.pp path reason in let take claim = t.claim <- Some claim; t.shared <- None; t.observed <- false; Writer_lock.release shared in match t.wal with | Some index -> ( match Writer_lock.take_wal_session ~busy:no_wait lock with | None -> refused "another handle of this process is writing it" | Some claim -> ( match Wal_index.begin_write index with | Ok () -> take claim | Error reason -> Writer_lock.release claim; refused reason | exception e -> Writer_lock.release claim; raise e)) | None -> ( match Writer_lock.take_session ~busy:no_wait lock with | None -> refused "another connection holds it" | Some claim -> take claim)) | _ -> attach t (* The write session a write needs, before it reads a page it will change. A transaction that has read writes on the snapshot it read ({!upgrade}); anything else takes the write session afresh, waiting as [busy] waits, and a transaction that held no session takes its rollback points again over what that session reads ({!resnapshot}). A read-only handle, refused by its write doors ({!check_writable}), takes nothing here. *) let writing t = if (not t.read_only) && Option.is_some t.db_path && Option.is_none t.claim then if t.txn_read && Option.is_some t.shared then upgrade t else begin attach t; (* The session that found the index unwritable is the one a read takes without it; it writes nothing, and ends here. *) if t.index_read_only then begin Option.iter Writer_lock.release t.claim; t.claim <- None; t.detached_stamp <- None; refuse_write () end; if Option.is_some t.claim then resnapshot t end (* The end of a write transaction: every commit the handle made is written to the log or the file, and EXCLUSIVE goes back (lockingv3.html, section 7: an idle connection holds no lock). The log stays, as it does between sqlite3's transactions (wal.html, section 3.1); the next session of any handle, in this process or another, reads it back. A failed write retains the claim and refuses further access until the handle is closed. *) let detach t = match t.claim with | Some claim when t.read_depth = 0 && at_boundary t -> ( protecting t @@ fun () -> match sync_committed t; t.alone_seen <- None; t.detached_stamp <- (match (t.wal, t.file) with | Some index, Some file -> index_stamp ~file index | _ -> physical_stamp t); Option.iter Wal_index.close t.wal; t.wal <- None; t.claim <- None; Writer_lock.release claim with | () -> () | exception e -> t.physical_failed <- true; raise e) | _ -> () (* Read a WAL database again for a read-only handle at the commit its WAL-index session names, where that is not the one it last read. *) let reread_index t index = match t.file with | None -> () | Some file -> let stamp = index_stamp ~file index in let page_size, wal = index_source ~file index in if stamp <> t.detached_stamp then begin install_pager t (Btree_eio.Pager.Read_only.v ~page_size ?wal file); t.journal_mode <- opening_journal_mode ~asked:None file; load_schema t; t.file_change_seen <- file_change_counter file; t.detached_stamp <- stamp; Handle.Plans.clear t.plan_cache end else ignore (bind_index_source t wal : bool) (* Read a WAL file and its log again for a read-only handle that reaches no WAL-index, where either moved since it last read them ({!physical_stamp}). *) let reread_wal t path = let now = physical_stamp t in if Option.is_none now || now <> t.detached_stamp then match (t.file, t.readers) with | Some file, Some readers -> let pager, stamp = read_only_pager ~file ~readers ~path in install_pager t pager; t.journal_mode <- opening_journal_mode ~asked:None file; load_schema t; t.file_change_seen <- stamp; t.wal_seen <- wal_mark (wal_path path); t.detached_stamp <- now; Handle.Plans.clear t.plan_cache | _ -> () (* Say that this handle is reading its database file, so a checkpoint of it defers rather than folding the log underneath the read ({!Durability.Readers}). A handle that may write does not say it -- the one writer's checkpoint is its own -- and neither does a rollback-journal handle, where there is no log to fold. Kept for as long as the handle holds a state a checkpoint would move under it: the reads, and any transaction or savepoint they leave open. A read-only handle on a named file takes SHARED first, for the same span: a checkpoint of another process is one this count never reaches, and SHARED keeps that process from writing the file at all ({!take_shared}). A writable handle that holds no session takes a read session ({!attach_read}). *) let hold_read t = if not t.read_only then attach_read t; (match (t.read_only, t.shared, t.db_path, t.lock_file) with | true, None, Some path, Some lock -> ( let shared = take_shared ~busy:t.busy path lock in t.shared <- Some shared; match (* A rollback-journal file is read under {!steady_read}, which drops the cache whenever the file's version moved. A WAL file is read at the commit a read mark of its WAL-index holds (walTryBeginRead). Where the index cannot supply a snapshot, read again under WAL_READ_LOCK(0) ({!hold_unreliable}) if the physical stamp changed. *) match (t.file, t.sw) with | Some file, _ when file_journal_mode file <> Some `Wal -> () | None, _ -> () | Some _, None -> if at_boundary t then reread_wal t path | Some file, Some sw -> ( match index_session ?held:t.index_hold ~read_only:true ~sw ~busy:t.busy path file Wal_index.begin_read with | `Held index -> t.wal <- Some index; hold_index ~sw t index; if at_boundary t then reread_index t index | `Unwritable -> t.unreliable <- hold_unreliable ~busy:t.busy path; share_for_life t; if at_boundary t then reread_wal t path | `Busy reason -> Model.fail_busy "database is locked: %a: %s" Eio.Path.pp path reason) with | () -> () | exception e -> Option.iter Wal_index.close t.wal; t.wal <- None; Option.iter Wal_index.end_unreliable t.unreliable; t.unreliable <- None; t.shared <- None; t.observed <- false; Writer_lock.release shared; raise e) | _ -> ()); t.read_depth <- t.read_depth + 1; match t.readers with | Some readers when t.read_only && t.journal_mode = `Wal && not t.live_read -> Readers.enter readers; t.live_read <- true | _ -> () (* Give the count back, whatever the handle was in the middle of. Reached from {!close}: a handle that has said it is reading and is then dropped without this holds a checkpoint off for the life of the process. *) let drop_read t = if t.read_only then begin Option.iter Wal_index.close t.wal; t.wal <- None; Option.iter Wal_index.end_unreliable t.unreliable; t.unreliable <- None end else end_read_session t; if t.live_read then begin (match t.readers with Some readers -> Readers.leave readers | None -> ()); t.live_read <- false end; match t.shared with | Some lock -> t.shared <- None; t.observed <- false; Writer_lock.release lock | None -> () (* Give the count back once there is nothing left holding a state: no read in flight and no transaction or savepoint open. Every door that ends one of those asks. A transaction that has neither read nor written holds no session between its statements, as sqlite3's deferred transaction holds no lock until its first read (lang_transaction.html). *) let settle_read t = if t.read_depth = 0 then if at_boundary t then begin t.txn_read <- false; drop_read t; detach t end else if not t.txn_read then end_read_session t (* Leave a read. The count outlives it where the read opened a transaction, and the transaction's own end is then what gives it back. *) let release_read t = t.read_depth <- t.read_depth - 1; settle_read t (* Read through a public door. The rule the interface states -- a handle absorbs other handles' commits at its next transaction boundary -- is a rule about every door, and a read is a boundary as much as a write: a row answered from a page another handle has replaced is stale, and the handle that then writes from that page commits it back over the replacement. So the read verbs take the write verbs' guard ({!autocommit_op}), and inside an explicit transaction it is a no-op, which holds that transaction's snapshot. A read-only handle on a rollback-journal database is the one door that does more, because the file itself moves under the read: {!steady_read} takes the read between two observations of the file's version and retakes it where they disagree, at every read and not only at a boundary. The read is bracketed by the count a checkpoint defers to ({!hold_read}), the refresh included, and the count is given back however the read ends. *) (* The boundary every read takes, and the whole of what a read is on a handle whose file no other handle rewrites under it: absorb what the others committed, run the body, and give back the count a checkpoint of this file defers to -- however the body ended. *) let bounded_read t f = hold_read t; match maybe_refresh t; f () with | v -> release_read t; v | exception exn -> release_read t; raise exn (* A read of an open transaction: the transaction keeps the session it reads under, and so the snapshot, until it ends. *) let pin_read t = if not (at_boundary t) then t.txn_read <- true let read_op t f = (* A read is one of the two things a scan's callback may not do, and every read door is this one, so this is where it is refused ({!Handle.check_not_scanning}). A script comes in through {!script_op} and is refused a statement at a time instead. *) check_not_scanning t "read"; entered t "Sqlite read" @@ fun () -> match (reads_a_moving_file t, t.db_path, t.file, t.lock_file) with | true, Some path, Some file, Some lock -> bounded_read t (fun () -> pin_read t; journal_read t ~reload:false path file lock f) | _ -> bounded_read t (fun () -> pin_read t; f ()) (* Read through a public door whose body cannot be run a second time. Taking a read again costs nothing where the body left nothing behind, and a script leaves two things: rows already handed to its caller, and the transaction a transaction verb opened. Neither is undone by dropping the page cache, so a second run hands the same rows over twice and meets its own [BEGIN]. What is taken again here is the observation and not the body: the file's version is settled first with an empty body, then the body runs once inside the ordinary boundary. *) let once t f = bounded_read t @@ fun () -> (match (reads_a_moving_file t, t.db_path, t.file, t.lock_file) with | true, Some path, Some file, Some lock -> journal_read t ~reload:false path file lock (fun () -> ()) | _ -> ()); f () let read_op_once t f = entered t "Sqlite script" @@ fun () -> once t (fun () -> pin_read t; f ()) (* A script runs once, as {!read_op_once}, and its statements say what they read ({!pin_read}) and write ({!writing}) one at a time: a transaction verb reads nothing. [write] takes the write session before the session a read would take, for a script whose first statement writes. *) let script_op ?(write = false) t f = entered t "Sqlite script" @@ fun () -> if write then writing t; once t f (* Re-lay the database at [page_size]. Reached only on an unwritten one, so re-laying it builds the empty structure again at the new width: the file is truncated, a pager of that width takes over, and page 1 is created afresh. The reserved space belongs to the file, so it carries over. The log of the discarded layout goes into the file first, through {!checkpoint}: a database states its width in page 1 while a log is read at the width its own header names, and a file and a log that disagree is not a state this engine reads back at all. The page 1 written below is written from this handle's own fields, which the fold has brought up to date. [Btree.Pager.sync] cannot be used here: it folds the dirty set into the clean cache, which the statement journal open over this pager records pre-images against, so ocaml-btree refuses it while one is open. The pages go out through the file the pager was built on instead. *) let relay_at_page_size t page_size = check_writable t; (* Between the truncation and the last page written the file holds no page 1 at all, which is not a database anything opens. A cancellation stops a fiber at its next Eio call, so the re-lay is run where one cannot reach it. *) protecting t @@ fun () -> if not (fold_and_remove t) then Model.fail_busy "database is locked: another connection reads the log the new page size \ would discard"; let reserved = Btree.Pager.reserved t.pager in let pager = match t.writable_file with | Some file -> Eio.File.truncate file Optint.Int63.zero; Btree_eio.Pager.v ~page_size file | None -> Btree.Pager.mem ~page_size () in Btree.Pager.set_reserved pager reserved; Btree.Pager.set_encoding pager (Btree.Pager.encoding t.pager); init_pages pager; (* The open savepoints' journals were on the pager being discarded, so the replacement opens as many ({!install_pager}): an unmatched close is an error, and a statement that raises after this must still find a journal to roll back. *) install_pager t pager; t.all_tables <- []; t.named_tables <- []; t.insert_rowids <- Ident.Tbl.create 8; t.wal_seen <- no_wal; t.file_change_seen <- t.change_counter; rebuild_page1 t; match t.writable_file with | Some file -> let width = Btree.Pager.page_size pager in for p = 1 to Btree.Pager.page_count pager do Eio.File.pwrite_all file ~file_offset:(Optint.Int63.of_int ((p - 1) * width)) [ Cstruct.of_string (Btree.Pager.read pager p) ] done; Eio.File.sync file | None -> () (* Whether a handle is inside a read of this database file at this moment, in which case a checkpoint of it would fold the log into the file the read is answering off ({!Durability.Readers}). *) let read_in_flight t = match t.readers with | Some readers when t.journal_mode = `Wal -> Readers.busy readers | Some _ | None -> false (* The threshold crossing, deferred while another handle is reading this file: the condition holds until a fold clears it, so a later commit asks again. The cost of deferring is the log growing to hold what the reader is reading. A read-only handle passes the threshold but may not act on it, so the test is here rather than in {!checkpoint}, which refuses such a handle by raising. Reached only once a commit is in the log ({!commit_durably}), so the log the threshold reads holds it, as sqlite3 counts a commit's frames once it wrote them (sqlite3WalDefaultHook). *) let maybe_autocheckpoint t = let frames = match t.wal with Some index -> Wal_index.max_frame index | None -> 0 in if (not t.read_only) && Option.is_none t.shared && t.wal_autocheckpoint > 0 && (Btree.Pager.pinned_count t.pager >= t.wal_autocheckpoint || frames >= t.wal_autocheckpoint) && not (read_in_flight t) then copy_back t (* A commit's pages go to the log or the file when it ends, in every mode: [`Off] skips only the fsync (SQLite synchronous=OFF, pager.c noSync), every other mode makes the commit durable now (SQLite synchronous=FULL). Reached at a commit boundary, which is what lets it write every dirty page. *) let sync_on_commit t = match synchronous t with | `Off -> sync_committed ~sync:false t | `Normal | `Full | `Extra -> sync_committed t (* Durability is a property of committed work, so an open transaction gets a no-op: its pages belong to a commit that has not happened, and writing them under a commit marker would be that commit; its savepoints hold journals whose pre-images say which pages were clean when each opened, and a commit erases them. *) let sync t = entered t "Sqlite.sync" @@ fun () -> if at_boundary t then begin attach t; sync_committed t; detach t end (* A copy-back that waits for no reader: one attempt. *) let no_wait = Writer_lock.busy 0. (* sqlite3_wal_checkpoint_v2, PASSIVE or TRUNCATE, as a door of its own, waiting for no reader: the committed frames copied into the file up to the least read mark, and with [`Truncate] the log then started over and cut to no bytes where no mark keeps it; else the next commit starts it over once every frame is in the file. Deferred while a handle of this process reads the file, as {!maybe_autocheckpoint} defers. *) let checkpoint_log ?(mode = `Passive) t = entered t "Sqlite.checkpoint" @@ fun () -> check_writable t; if at_boundary t && not (read_in_flight t) then begin attach t; sync_committed t; (match mode with | `Passive -> checkpoint t | `Truncate -> copy_back ~wait:no_wait t); detach t end (* PRAGMA wal_checkpoint[(MODE)], the row OP_Checkpoint answers (vdbe.c): whether the checkpoint was kept from finishing, the log's last frame and the frame up to which the file holds the log; [(false, -1, -1)] with no log in use. Run inside the pragma's own statement, so only an explicit transaction or savepoint refuses it, in sqlite3's words. FULL and RESTART copy what PASSIVE copies, waiting for no reader, and answer busy where a read mark kept a frame out; TRUNCATE is {!copy_back}, which waits as the busy timeout does and leaves an empty log. *) let wal_checkpoint t mode = if t.journal_mode <> `Wal then (false, -1, -1) else if in_transaction t then Catalog.Error.fail_runtime "database table is locked" else begin (match mode with | `Noop -> () | `Truncate -> check_writable t; sync_committed t; copy_back t | `Passive | `Full | `Restart -> check_writable t; sync_committed t; if not (read_in_flight t) then checkpoint t); match t.wal with | None -> (false, 0, 0) | Some index -> let log = Wal_index.max_frame index in let copied = Wal_index.min_frame index - 1 in let busy = match mode with | `Noop | `Passive -> false | `Full | `Restart -> copied < log | `Truncate -> log > 0 in (busy, log, copied) end (* Change how this handle's commits are made durable. The mode is not only the handle's: page 1 records it, and a reader meeting the rollback-journal version never looks at a [-wal] beside the file. So the change is a write. Leaving [`Wal] folds the log into the file and removes it first, since a log left behind is committed transactions nothing looks at again. Refused inside a transaction or savepoint, in sqlite3's own words (vdbe.c, OP_JournalMode): the mode decides where that transaction's pages are going, and it has already started putting them there. The pragma's own statement is not counted. *) let set_journal_mode t mode = let changed = match (mode, t.journal_mode) with | `Wal, `Journal | `Journal, `Wal -> true | `Wal, `Wal | `Journal, `Journal -> false in if changed then begin (* Only a change is refused. The mode a handle is in is a thing to ask a read-only handle, and asking for the one it is already in changes nothing; moving it rewrites page 1 and folds the log away. *) check_writable t; if in_transaction t then Catalog.Error.fail_runtime "cannot change %s wal mode from within a transaction" (match mode with `Wal -> "into" | `Journal -> "out of"); if t.journal_mode = `Wal then begin if not (fold_and_remove t) then Model.fail_busy "database is locked: another connection reads the log, so the \ database stays in wal mode"; (* The log closed, page 1 is read from the file again. *) t.vers_read <- t.change_counter end; t.journal_mode <- mode; rebuild_page1 t; (* Header bytes 18 and 19 go in by a rollback-journal transaction of their own, whatever the mode, and only where they changed (vdbe.c, OP_JournalMode; btree.c, sqlite3BtreeSetVersion): the commit that ends this statement. *) t.commit_in_place <- Btree.Pager.is_dirty t.pager 1 end (* Closing a handle that may only read. It owes the file nothing, so it drops what it held and leaves every byte where it is. Each step a writable close takes would take something from the handle still writing: the checkpoint would put this reader's older pages into the file, removing the log would discard later commits, and two readers closing at once would race to remove the same log. *) let close_read_only t = (* Whatever this handle was in the middle of, it is reading nothing from here: a count it kept would hold a checkpoint of this file off for the life of the process. *) drop_read t; Btree.Pager.checkpointed t.pager; t.sw <- None (* Whether this handle's path no longer names the file it has open (os_unix.c, fileHasMoved). *) let moved t = match (t.db_path, t.file) with | Some path, Some file -> (not (Handle.is_closed t)) && has_moved ~file path | _ -> false (* A rollback-journal handle outside a write session made its commits durable when that session ended ({!detach}), and has no log to fold: it closes taking no lock, as sqlite3PagerClose does in rollback mode. *) let owes_the_file_nothing t = match t.db_path with | Some path -> Option.is_none t.claim && t.journal_mode = `Journal && not (Eio.Path.is_file (wal_path path)) | None -> false (* The close of a handle that may owe the file its commits or its log, in a write session of its own. *) let close_in_session ?sw t = match if t.claim = None && at_boundary t && not (Btree.Pager.has_dirty t.pager) then attach ?sw t with | exception Catalog.Error (Busy _) -> (* Another handle is in a transaction on the file: this handle owes it nothing, and the log stays for whichever handle closes last. *) t.sw <- None | () -> attach ?sw t; refresh t; sync_committed t; (* A handle is reading this file, so the checkpoint would fold the log underneath that read; or the path names another file, or none, so the log and index there are no longer this file's to fold and remove, as sqlite3PagerClose checkpoints only where databaseIsUnmoved. Leave the log: it is the committed state, a later handle folds it in. *) if not (read_in_flight t || moved t) then ignore (fold_and_remove t : bool); detach t; t.sw <- None (* Closing a handle that may write, at a boundary ({!close}). Pick up other handles' commits, make the commits still in the cache durable as every commit is made, and checkpoint the committed pages and remove the log. A checkpoint that cannot complete is replayed on the next open. A rollback-journal handle outside a write session owes none of that, and closes taking no lock ({!owes_the_file_nothing}). Those last commits go to the log (or the journal), not straight into the file. The log still holds older frames of some of their pages, and until the fold removes it, the next open lays those frames over the file: a process that ended in between would reopen on a mixture of the two, a row pointing at pages that hold another commit's bytes. *) let close_writable t = (* The close has its own session switch. A still-held log descriptor remains authoritative even after unlink; a descriptor released by the caller's switch has already cleared its owner, so this session opens it anew. *) let with_switch f = match t.db_path with | Some _ -> Eio.Switch.run (fun sw -> f (Some sw)) | None -> f None in with_switch @@ fun sw -> (* A handle with no write session ends its read session. *) if Option.is_none t.claim && Option.is_some t.db_path then end_read_session t; if owes_the_file_nothing t then t.sw <- None else close_in_session ?sw t (* Clean shutdown that opens no new switch-scoped resource: it writes through the already-open file, the in-memory cache and path operations only, so it is safe to call from [Switch.on_release] while that switch is finishing. Run where a cancellation cannot reach it, because what it writes is the run's last state: the log folded into the file. Then the descriptor the open took goes back. A handle closed under a switch that lives on would otherwise keep a descriptor until the process reached its limit; Eio's own close removes the switch's release hook, so the later release is a no-op. One close is the whole of it: a writable handle's [file] and [writable_file] are one open read two ways, and closing both would close a descriptor twice, which the in-memory filesystem refuses. A second close is asked to do nothing ({!Handle.is_closed}). *) let close t = if not (is_closed t) then begin protecting t @@ fun () -> if t.physical_failed then begin (* End the failed physical session as a crash would: recovery sidecars remain authority for the next attachment, and no cached page is written out of an uncertain outcome. *) t.transaction <- None; t.sw <- None end else begin (* What the connection has open never committed: it is undone, as sqlite3_close rolls it back, so the store closes at a boundary. *) if Lazy.is_val t.connection then Sql.close (Lazy.force t.connection); if t.read_only || t.index_read_only then close_read_only t else close_writable t end; (* Closing any descriptor on the file releases every record lock this process holds on it, whichever descriptor took them, so the descriptor goes through {!Writer_lock.close_later}: while a claim of this process stands, it stays open until that claim's last release. This handle's claim is then given back, and whatever claim survives it is taken again for a close that came under no claim. *) Option.iter Writer_lock.close_later t.lock_file; Option.iter Wal_index.close t.wal; t.wal <- None; drop_index_hold t; Option.iter Writer_lock.release t.claim; t.claim <- None; Option.iter Writer_lock.release t.shared; t.shared <- None; Option.iter Writer_lock.reassert t.lock_file end let open_ ~sw ?create ?read_only ?busy_timeout ?synchronous ?journal_mode ?clock ?zone path = let t = open_attached ~sw ?create ?read_only ?busy_timeout ?synchronous ?journal_mode ?clock ?zone path in (* A writable handle on a WAL database builds its pager in its first session; one refused gives its descriptor back, as {!opening} does. A rollback-journal one builds it in the first session a door takes, as sqlite3 reads its schema at the first statement. *) (if (not t.read_only) && Option.is_none t.claim && t.journal_mode = `Wal then match attach t with | () -> () | exception e -> Option.iter Writer_lock.close_later t.lock_file; Option.iter Wal_index.close t.wal; t.wal <- None; drop_index_hold t; Option.iter Writer_lock.release t.claim; t.claim <- None; t.sw <- None; raise e); detach t; t (* The file an overlay's pager reads ({!overlay}): each page written, held in memory, and every other page of the first [base] answered by [read], the pages of the transaction the overlay reads; past [base], zeros. *) module Overlay_file = struct type t = { page_size : int; read : int -> string; mutable base : int; mutable size : int; pages : (int, bytes) Hashtbl.t; } let v ~page_size ~pages read = { page_size; read; base = pages; size = pages * page_size; pages = Hashtbl.create 64; } (* The bytes of page [n], numbered from 1, without a copy: written, read, or zeros. *) let page t n = match Hashtbl.find_opt t.pages n with | Some b -> Bytes.unsafe_to_string b | None when n <= t.base -> t.read n | None -> String.make t.page_size '\000' let writable t n = match Hashtbl.find_opt t.pages n with | Some b -> b | None -> let b = Bytes.of_string (page t n) in Hashtbl.replace t.pages n b; b let pread t ~off buf ~pos ~len = if off < 0 || off + len > t.size then raise End_of_file; let rec go off pos len = if len > 0 then begin let n = (off / t.page_size) + 1 and o = off mod t.page_size in let k = min len (t.page_size - o) in Bytes.blit_string (page t n) o buf pos k; go (off + k) (pos + k) (len - k) end in go off pos len let pwrite t ~off bufs = let rec go off s i = if i < String.length s then begin let n = (off / t.page_size) + 1 and o = off mod t.page_size in let k = min (String.length s - i) (t.page_size - o) in Bytes.blit_string s i (writable t n) o k; go (off + k) s (i + k) end else off in let stop = List.fold_left (fun off s -> go off s 0) off bufs in t.size <- max t.size stop let size t = t.size (* The pages past [n] go, and the bytes past [n] of the page it cuts read as zeros once it grows again. *) let truncate t n = let whole = n / t.page_size in if n mod t.page_size <> 0 then begin let b = writable t (whole + 1) in Bytes.fill b (n mod t.page_size) (t.page_size - (n mod t.page_size)) '\000' end; let last = (n + t.page_size - 1) / t.page_size in Hashtbl.filter_map_inplace (fun p b -> if p > last then None else Some b) t.pages; t.base <- min t.base whole; t.size <- n let sync_data _ = () let sync_file _ = () end module Overlay_pager = Btree.Pager.Make (struct module File = Overlay_file let caps _ = Block.Sim.default_caps end) (* The pages of [src] are read through its pager while its transaction holds the commit it began on: the read mark keeps every checkpoint from copying past it, so a page [src] reads from the file is that commit's. The pages read are cached by [src]'s pager, so the overlay's keeps the floor of ten pages, and the pages it writes are held by its file. *) let overlay src = if at_boundary src then invalid_arg "Sqlite.overlay: no transaction is open on the database"; read_op src @@ fun () -> let page_size = Btree.Pager.page_size src.pager in let locking = Btree.Pager.locking_page src.pager in let read n = if n = locking then String.make page_size '\000' else Btree.Pager.read src.pager n in let file = Overlay_file.v ~page_size ~pages:(Btree.Pager.page_count src.pager) read in let t = handle ~busy:src.busy ~pager:(Overlay_pager.v ~page_size ~cache_bytes:page_size file) ~file:None ~writable_file:None ~read_only:false ~readers:None ~claim:None ~sw:None ~db_path:None ~synchronous:`Full ~journal_mode:src.journal_mode ~clock:src.clock ~zone:src.zone ~file_change_seen:src.file_change_seen ~wal_seen:no_wal () in t.usable <- (fun () -> if at_boundary src then invalid_arg "Sqlite.overlay: the transaction of the database it reads has ended"); load_committed_schema t; t (* The pages are written at their offsets and the file cut to the count read, so a read that {!read_op} runs again over a file that moved leaves the copy of the second run alone. The locking page holds no data and is written as zeros, as sqlite3 leaves it. *) let write_pages t out = let pager = t.pager in let page_size = Btree.Pager.page_size pager in let pages = Btree.Pager.page_count pager in let locking = Btree.Pager.locking_page pager in for page = 1 to pages do let bytes = if page = locking then String.make page_size '\x00' else Btree.Pager.read pager page in Eio.File.pwrite_all out ~file_offset:(Optint.Int63.of_int ((page - 1) * page_size)) [ Cstruct.of_string bytes ] done; Eio.File.truncate out (Optint.Int63.of_int (pages * page_size)) let backup t dst = if not (at_boundary t) then invalid_arg "Sqlite.backup: inside a transaction or savepoint"; (* A copy that did not complete is removed: a part of a database is not one. The refusal of an existing [dst] is the open's, so it removes nothing. *) Eio.Switch.run (fun sw -> let out = Eio.Path.open_out ~sw ~create:(`Exclusive 0o644) dst in match read_op t (fun () -> write_pages t out); Eio_fs_sync.sync_file out with | () -> () | exception exn -> let bt = Printexc.get_raw_backtrace () in (try Eio.Path.unlink dst with Eio.Io _ -> ()); Printexc.raise_with_backtrace exn bt); Eio_fs_sync.sync_parent dst (* The order of each index b-tree of the schema, by its root page: the comparison this handle reads it with, or why it has none. *) let index_orders t = let orders = Hashtbl.create 16 in let known idx = Hashtbl.replace orders (Btree.Index.root_page idx) (Ok (Btree.Index.comparison idx)) in List.iter (fun (gt : generic_table) -> (match gt.store with | Pk_index_rows p -> known p.index | Rowid_rows _ -> ()); List.iter (fun (i : index) -> known i.btree) gt.indexes; List.iter (fun (u : unusable_index) -> Hashtbl.replace orders u.root_page (Error u.reason)) gt.unusable) t.all_tables; Hashtbl.find_opt orders (* sqlite3RunVacuum refuses an open transaction before it reads its argument (sqlite/src/vacuum.c), so the two refusals come in that order. *) let check_vacuum t = if in_transaction t then Catalog.Error.fail_runtime "cannot VACUUM from within a transaction" (* The copy, from its first page: a read that is taken again ({!read_op}) writes it again over what the first attempt left. *) let compact_copy t out = Eio.File.truncate out Optint.Int63.zero; let pager = Btree_eio.Pager.v ~page_size:(Btree.Pager.page_size t.pager) (out :> Eio.File.rw_ty Eio.Resource.t) in Vacuum.copy ~flush_bytes:(cache_bytes t) ~src:t.pager ~dst:pager ~order:(index_orders t); Btree.Pager.sync pager (* As {!backup}, a copy that did not complete is removed, and an existing [dst] is refused by the open, so it removes nothing. [read] runs the copy under a read of [t]. *) let into_file t dst ~read = check_vacuum t; Eio.Switch.run (fun sw -> let out = match Eio.Path.open_out ~sw ~create:(`Exclusive 0o644) dst with | out -> out | exception Eio.Io (Eio.Fs.E (Eio.Fs.Already_exists _), _) -> Catalog.Error.fail_runtime "output file already exists" in match read (fun () -> compact_copy t out) with | () -> () | exception exn -> let bt = Printexc.get_raw_backtrace () in (try Eio.Path.unlink dst with Eio.Io _ -> ()); Printexc.raise_with_backtrace exn bt); Eio_fs_sync.sync_parent dst let vacuum_into t dst = into_file t dst ~read:(read_op t) let vacuum_into_read t dst = into_file t dst ~read:(fun f -> f ()) (* The compact image is built in a file of its own beside the database, unlinked as soon as it is open so that nothing is left of it after a crash, or in memory for a database with no file. *) let with_scratch t f = let page_size = Btree.Pager.page_size t.pager in match t.db_path with | None -> f (Btree.Pager.mem ~page_size ()) | Some (dir, name) -> Eio.Switch.run @@ fun sw -> let path = (dir, name ^ "-vacuum") in let file = Eio.Path.open_out ~sw ~create:(`Or_truncate 0o600) path in Eio.Path.unlink path; f (Btree_eio.Pager.v ~page_size (file :> Eio.File.rw_ty Eio.Resource.t)) (* sqlite3RunVacuum's copy back (sqlite3BtreeCopyFile) where the commit goes to a log no WAL-index names or to no file: the compact image's pages over pages 1..N of the database, dirty in the write transaction the caller commits, whose log frame states N. The schema is then the image's, and so are its sqlite_master rows, which the commit's {!rebuild_page1} leaves where they are. The change counter goes on from the database's, so the commit tells every reader of the file that it moved. The whole image is held until that commit: a log with no index is read back from the cache alone, and a database with no file is its cache. *) let copy_into_cache t image = let counter = t.change_counter in let n = Btree.Pager.page_count image in let locking = Btree.Pager.locking_page t.pager in for page = 1 to n do if page <> locking then Btree.Pager.write t.pager page (Btree.Pager.read image page) done; Btree.Pager.set_page_count t.pager n; load_schema t; t.change_counter <- counter; t.master_written <- Some (t.pager, master_records t) (* The image's pages [first .. last] but the locking page, written into [file] in runs of at most {!fold_run_pages}, so one buffer of a run is all a copy holds. *) let write_image_pages ~image ~file ~locking first last = let page_size = Btree.Pager.page_size image in let write first count = let buf = Cstruct.create (count * page_size) in for i = 0 to count - 1 do Cstruct.blit_from_string (Btree.Pager.read image (first + i)) 0 buf (i * page_size) page_size done; Eio.File.pwrite_all file ~file_offset:(Optint.Int63.of_int ((first - 1) * page_size)) [ buf ] in let rec runs p = if p <= last then ( if p = locking then runs (p + 1) else let rec span count = if count < fold_run_pages && p + count <= last && p + count <> locking then span (count + 1) else count in let count = span 1 in write p count; runs (p + count)) in runs first (* A rollback-journal VACUUM commits the image straight from its scratch file, as sqlite3's pager spills a transaction too large for its cache (pager.c, pagerStress): the journal takes the pre-image of every page of the file, read from the file in runs, and is synced; then the image's pages go into the file in runs, page 1 last with the change counter moved on, the file is cut to the image's size and synced, and the journal is removed. No page of the image is held dirty, so the copy costs a run's buffer whatever the size of the database, where holding the image in the cache until the commit costs the whole of it. The handle then reads the file afresh. *) let commit_image t path file image = let page_size = Btree.Pager.page_size t.pager in let n = Btree.Pager.page_count image in let orig_pages = Btree.Pager.file_pages ~page_size (Optint.Int63.to_int (Eio.File.stat file).size) in let counter = Page1.next_change_counter t.vers_read in let page1 = Bytes.of_string (Btree.Pager.read image 1) in Btree.Page.set_u32_be page1 Page1.change_counter_offset counter; Btree.Page.set_u32_be page1 92 counter; escalate_claim t; check_unmoved path file; let jp = journal_path path in Eio.Path.with_open_out ~create:(`Or_truncate 0o644) jp (fun j -> write_journal j ~file ~page_size ~orig_pages (List.init orig_pages (fun i -> i + 1)); Eio.File.sync j; sync_dir_of jp); (* As {!sync_journal}: from the first page written to the barrier over the journal's removal, the commit runs to its end whatever happens to the fiber, and a failure in it ends the physical session, the hot journal being the only copy of what it overwrote. *) Eio.Cancel.protect (fun () -> match write_image_pages ~image ~file ~locking:(Btree.Pager.locking_page t.pager) 2 n; Eio.File.pwrite_all file ~file_offset:Optint.Int63.zero [ Cstruct.of_bytes page1 ]; if n < orig_pages then Eio.File.truncate file (Optint.Int63.of_int (n * page_size)); Eio.File.sync file; Eio.Path.unlink jp; sync_dir_of jp with | () -> () | exception exn -> t.physical_failed <- true; raise exn); Btree.Pager.refresh_from_file t.pager; load_schema t; t.file_change_seen <- t.change_counter; t.pages_written <- t.pages_written + n (* A WAL VACUUM under the WAL-index commits the image straight from its scratch file, as sqlite3WalFrames appends the frames pagerStress spills: the image's pages 1..N but the locking page, page 1 in WAL format with the change counter moved on, go into the log as one commit stating N, read from the image a run at a time ({!Wal_index.commit}). No page of the image is held dirty or pinned: the handle then reads the database afresh through the index, as a session does that finds the log moved. *) let commit_image_wal t index file image = let page_size = Btree.Pager.page_size t.pager in let n = Btree.Pager.page_count image in let locking = Btree.Pager.locking_page t.pager in let counter = Page1.next_change_counter t.vers_read in let page1 = Bytes.of_string (Btree.Pager.read image 1) in Btree.Page.set_u32_be page1 Page1.change_counter_offset counter; Btree.Page.set_u32_be page1 92 counter; Bytes.set_uint8 page1 18 Page1.wal_file_format; Bytes.set_uint8 page1 19 Page1.wal_file_format; let rest = Seq.filter_map (fun page -> if page = locking then None else Some (page, Btree.Pager.read image page)) (Seq.init (n - 1) (fun i -> i + 2)) in Wal_index.commit index ~page_size ~page_count:n (Seq.cons (1, Bytes.to_string page1) rest); rebuild_from_index t file ~page_size ?wal:(Wal_index.snapshot index) (); t.pages_written <- t.pages_written + n let vacuum t = check_vacuum t; check_writable t; if Btree.Pager.page_count t.pager > 0 then with_scratch t (fun image -> (* The image is spilled to its scratch file whenever it has grown by the handle's cache budget, as sqlite3 spills a full cache. *) Vacuum.copy ~flush_bytes:(cache_bytes t) ~src:t.pager ~dst:image ~order:(index_orders t); match (t.sw, t.db_path, t.writable_file, t.journal_mode, t.wal) with | Some _, Some path, Some file, `Journal, _ -> commit_image t path file image | Some _, Some _, Some file, `Wal, Some index -> commit_image_wal t index file image | _ -> copy_into_cache t image) let write_op t f = entered t "Sqlite write" @@ fun () -> writing t; bounded_read t f let with_open ~sw ?create ?read_only ?busy_timeout ?synchronous ?journal_mode ?clock ?zone path f = let db = open_ ~sw ?create ?read_only ?busy_timeout ?synchronous ?journal_mode ?clock ?zone path in Fun.protect ~finally:(fun () -> close db) (fun () -> f db) (* Make the transaction that has just ended durable, or leave the handle as if it had never run. [snap] is its rollback snapshot, still in hand: a durability step that raises is a transaction that did not happen, and the pages and schema go back to [snap] before the failure is re-raised. Every transaction boundary comes through here. What a failure leaves on disk is the journal mode's to say. Under [`Journal] the commit writes and fsyncs the journal before touching a page, so a failure at or before that barrier leaves the file as it was, and one after leaves a half-rewritten file the next open rolls back, with this handle refusing every access until it is closed ({!sync_journal}). Under [`Wal] the frames are cut back off, leaving the log ending on the last durable commit. In memory both modes leave the state held before the transaction ran. *) let commit_durably t snap = (match escalate t; sync_on_commit t with | () -> () | exception exn -> restore_txn t snap; raise exn); maybe_autocheckpoint t (* {1 The transaction door} {!Catalog.Spi}'s transaction stack over the file, which the connection drives and names ({!Sql.Private.Connection}). At the bottom the transaction's rollback point, a snapshot taken at a boundary, where no page is dirty, so it copies none. Over it each savepoint, a statement's own among them, is a pager statement journal: it records the pre-image of a page the first time its span touches it, so it costs what the span changed rather than what the transaction has (sqlite3's pager keeps one sub-journal for both, pager.c, sqlite3PagerOpenSavepoint). The engine opens and closes them in order: a step out of that order is its error. *) let open_transaction t what = match t.transaction with | Some tx -> tx | None -> Fmt.invalid_arg "Sqlite.%s: no transaction is open" what (* The lock [BEGIN] names (btree.c, sqlite3BtreeBeginTrans): IMMEDIATE takes the write session at once, and EXCLUSIVE in a rollback journal also keeps every reader of this process out, being IMMEDIATE in WAL mode; DEFERRED takes nothing until the transaction reads or writes. Its view is current: other handles' commits are folded in first. *) let begin_transaction t (lock : Catalog.Spi.lock) = if Option.is_some t.transaction then invalid_arg "Sqlite.begin_transaction: a transaction is open"; (match lock with | `Deferred -> () | `Immediate -> writing t | `Exclusive -> writing t; escalate_claim t); refresh t; t.transaction <- Some { began = snapshot_txn t; journals_on = t.pager; savepoints = [||]; depth = 0; } (* A commit is refused before anything ends where EXCLUSIVE is not taken (vdbe.c, OP_AutoCommit on SQLITE_BUSY): the transaction stays open for a later one. Otherwise its savepoints close keeping their pages, the handle is back at a boundary, so a checkpoint of the file may fold under its snapshot again, and the pages are made durable or put back. The deferred foreign keys are judged before, by the connection ({!Connection.commit}). *) let commit t = let tx = open_transaction t "commit" in escalate t; for _ = 1 to tx.depth do Btree.Pager.commit_statement t.pager done; t.transaction <- None; settle_read t; commit_durably t tx.began let rollback t = let tx = open_transaction t "rollback" in for _ = 1 to tx.depth do Btree.Pager.rollback_statement t.pager done; t.transaction <- None; restore_txn t tx.began; settle_read t let savepoint t = let tx = open_transaction t "savepoint" in Btree.Pager.begin_statement t.pager; push_savepoint t tx let release t = let tx = open_transaction t "release" in if tx.depth = 0 then invalid_arg "Sqlite.release: no savepoint is open"; Btree.Pager.commit_statement t.pager; tx.depth <- tx.depth - 1 (* The savepoint stays open: its journal starts again from here. *) let rollback_to t = let tx = open_transaction t "rollback_to" in if tx.depth = 0 then invalid_arg "Sqlite.rollback_to: no savepoint is open"; let sp = tx.savepoints.(tx.depth - 1) in Btree.Pager.rollback_statement t.pager; Btree.Pager.begin_statement t.pager; restore_schema t sp.schema_at (* {1 Stored definitions} Every row of the schema table is a definition: a table and its indexes as their b-trees were made, and a view or a trigger as a row with its text and no root page, the schema state a transaction's rollback restores with the rest ({!Handle.snapshot}). *) let master_type : Catalog.Spi.Definition.kind -> string = function | `Table -> "table" | `Index -> "index" | `View -> "view" | `Trigger -> "trigger" let definition_kind = function | "table" -> Some `Table | "index" -> Some `Index | "view" -> Some `View | "trigger" -> Some `Trigger | _ -> None let definitions t = List.filter_map (fun (rowid, name, tbl_name, _, sql, type_) -> Option.map (fun kind -> let sql = match sql with Sql.Ast.Text s -> Some s | _ -> None in (rowid, Catalog.Spi.Definition.v kind ~name ~table:tbl_name sql)) (definition_kind type_)) (master_entries t) let define t (d : Catalog.Spi.Definition.t) = let sql = match (d.kind, d.sql) with | (`View | `Trigger), Some sql -> sql | _ -> Fmt.invalid_arg "Sqlite.define: %s is no view or trigger" d.name in t.extra_master <- t.extra_master @ [ Ddl.master_entry ~rowid:(next_master_rowid t) ~type_:(master_type d.kind) ~name:d.name ~tbl_name:d.table ~sql; ]; rebuild_page1 t let undefine t kind name = (match kind with | `View | `Trigger -> () | `Table | `Index -> Fmt.invalid_arg "Sqlite.undefine: %s is no view or trigger" name); let type_ = master_type kind in let is (rm : raw_master_entry) = String.equal rm.type_ type_ && Ident.equal rm.name name in if not (List.exists is t.extra_master) then Fmt.invalid_arg "Sqlite.undefine: no %s %s" type_ name; t.extra_master <- List.filter (fun rm -> not (is rm)) t.extra_master; rebuild_page1 t let redefine t (d : Catalog.Spi.Definition.t) = let sql = match (d.kind, d.sql) with | (`View | `Trigger), Some sql -> sql | _ -> Fmt.invalid_arg "Sqlite.redefine: %s is no view or trigger" d.name in let type_ = master_type d.kind in let is (rm : raw_master_entry) = String.equal rm.type_ type_ && Ident.equal rm.name d.name in if not (List.exists is t.extra_master) then Fmt.invalid_arg "Sqlite.redefine: no %s %s" type_ d.name; t.extra_master <- List.map (fun rm -> if is rm then { rm with sql = Sql.Ast.Text sql } else rm) t.extra_master; rebuild_page1 t module Connection = Sql.Private.Connection (* The transaction's end, or its undo where the store refused the commit and left it open. *) let commit_or_undo conn = match Connection.commit conn with | () -> () | exception e -> let bt = Printexc.get_raw_backtrace () in if not (Connection.autocommit conn) then Connection.rollback conn; Printexc.raise_with_backtrace e bt (* A direct write outside a transaction is one of its own, made durable when it returns or undone where it raises. Inside one it is [f ()], whose end commits it. It takes the write session first, so [f] writes in it. *) let autocommit t f = writing t; let conn = Handle.connection t in if not (Connection.autocommit conn) then f () else begin Connection.begin_ conn Immediate; match f () with | r -> commit_or_undo conn; r | exception e -> let bt = Printexc.get_raw_backtrace () in if not (Connection.autocommit conn) then Connection.rollback conn; Printexc.raise_with_backtrace e bt end (* An outermost transaction of the API is [BEGIN IMMEDIATE] ... [COMMIT], and a nested one a savepoint with no name. Its commit is refused while violations of foreign keys are counted, and with no statement of the caller left to resolve them the transaction is undone (vdbeaux.c, sqlite3VdbeCheckFkDeferred). [f] may end the transaction itself. *) let transaction t f = let exception Own of Catalog.Error.t in let own operation = match operation () with | value -> value | exception Catalog.Error e -> raise (Own e) in let conn = Handle.connection t in let callback_failure = ref None in let failed exn = callback_failure := Some (exn, Printexc.get_raw_backtrace ()) in let outermost () = own (fun () -> Connection.begin_ conn Immediate); match f () with | result -> if not (Connection.autocommit conn) then begin if Connection.deferred_violated conn then begin Connection.rollback conn; Catalog.Error.fail (Constraint Foreign_key) end; own (fun () -> commit_or_undo conn) end; result | exception exn -> failed exn; if not (Connection.autocommit conn) then Connection.rollback conn; raise exn in let body () = if Connection.autocommit conn then outermost () else Fun.protect ~finally:(fun () -> settle_read t) (fun () -> try Connection.nested conn f with exn -> failed exn; raise exn) in (* The read is given back however the body ended, as {!bounded_read} gives it back: giving it back can write the log, and a write that fails there is the caller's error, as any failed write is. *) match own (fun () -> writing t; hold_read t); match body () with | result -> release_read t; result | exception exn -> let trace = Printexc.get_raw_backtrace () in release_read t; Printexc.raise_with_backtrace exn trace with | result -> Ok result | exception exn when Option.is_some !callback_failure -> ( let trace = Printexc.get_raw_backtrace () in match !callback_failure with | Some (callback, original_trace) -> Printexc.raise_with_backtrace callback original_trace | None -> Printexc.raise_with_backtrace exn trace) | exception Own e -> Error e (* The transaction's whole span, its commit included, is owned by the calling domain ({!Handle.owned}): between its statements no entry point runs, and another domain's would run beside its snapshot and its commit. *) let with_transaction_result t f = owned t "Sqlite.with_transaction" (fun () -> transaction t f) let with_transaction t f = match with_transaction_result t f with | Ok value -> value | Error e -> Catalog.Error.fail e