Something went wrong. Try again.
SQLite file format and SQL engine in pure OCaml
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124(* [sql script DB [FILE]] and [sql query DB SQL], as the sqlite-cli [sql] answers them, run by the [sql] engine over a [Catalog.Spi.Mem] store instead of a sqlite3 file. A page runs [sql] several times over one name and reads what the earlier runs left, but the store has no file format to save: DB holds, after [header], the statements the earlier runs ran, each as its text exactly, which a statement that keeps its text keeps, and each run's closed by [run_end]; the next run rebuilds the store by running them again, each run's on a connection of its own, as each sqlite-cli run is. A statement that failed part way is logged too, and its run again fails at the same row, so the store comes back as it was left; one that reads the clock or random() reads another value. *)
module Store = Catalog.Spi.Make (Catalog.Spi.Mem)
let header = "-- the statements of a catalog.mem store\n"let run_end = "-- the end of a run\n"let memory = ":memory:"
(* A statement's entry: its length on a line of its own, then its text. *)let entry text = Fmt.str "-- %d\n%s\n" (String.length text) text
(* The runs of a log, each the texts of its statements in order. A page may cut the file short or write past its end, as it does to a sqlite3 file: the log ends at the first entry that is not whole. *)let runs log = let n = String.length log in let line_end i = Option.value ~default:n (String.index_from_opt log i '\n') in let rec go i run acc = let finish () = List.rev (if run = [] then acc else List.rev run :: acc) in if i >= n then finish () else if String.starts_with ~prefix:run_end (String.sub log i (n - i)) then go (i + String.length run_end) [] (List.rev run :: acc) else let e = line_end i in match if String.starts_with ~prefix:"-- " (String.sub log i (e - i)) then int_of_string_opt (String.sub log (i + 3) (e - i - 3)) else None with | Some len when e + 1 + len < n -> go (e + 1 + len + 1) (String.sub log (e + 1) len :: run) acc | Some _ | None -> finish () in go (String.length header) [] []
let load path = match Eio.Path.load path with | exception Eio.Io (Eio.Fs.E (Eio.Fs.Not_found _), _) -> None | s -> if String.starts_with ~prefix:header s then Some s else Catalog.Error.fail (Not_a_database "file is not a database")
let print row = Fmt.pr "%s@." (String.concat "|" (List.map Sqlite.Value.to_shell row))
(* The sqlite-cli's words for a failure: a statement that does not prepare is a "Parse error", every other refusal an "Error". *)let fail = function | Script.Refused ((Prepare _ | Not_a_database _) as e) -> Fmt.epr "Parse error: %a@." Catalog.Error.pp e; exit 1 | f -> Fmt.epr "Error: %a@." Script.pp_failure f; exit 1
let run ~create ~write db sql = Eio_main.run @@ fun env -> let path = Eio.Path.(Eio.Stdenv.fs env / db) in let stored = if String.equal db memory then None else match load path with | log -> log | exception Catalog.Error e -> fail (Refused e) in let cat = Store.v (Catalog.Spi.Mem.v []) in let log = match stored with | Some log -> (* each run that wrote the log closed its connection, which rolled back a transaction it left open *) List.iter (fun ran -> let replayed = Sql.v cat in Script.replay replayed ran; Sql.close replayed) (runs log); log | None when create || String.equal db memory -> header | None -> Fmt.epr "Error: unable to open database %S: no such file or directory@." db; exit 1 in let ran = Buffer.create 256 in let on_statement text = Buffer.add_string ran (entry text) in (* each run is a connection of its own, as each sqlite-cli run is, so its counts start from none whatever the replay counted *) let conn = Sql.v cat in let result = Script.run conn (sql env) ~on_statement ~on_row:print in Sql.close conn; if write && not (String.equal db memory) then Eio.Path.save ~create:(`Or_truncate 0o644) path (log ^ Buffer.contents ran ^ run_end); Result.iter_error fail result
let () = let args = List.filter (fun a -> not (String.starts_with ~prefix:"--journal-mode" a)) (List.tl (Array.to_list Sys.argv)) in match args with | [ "script"; db ] -> run ~create:true ~write:true db (fun env -> Eio.Flow.read_all (Eio.Stdenv.stdin env)) | [ "script"; db; file ] -> run ~create:true ~write:true db (fun env -> Eio.Path.load Eio.Path.(Eio.Stdenv.fs env / file)) | [ "query"; db; sql ] -> run ~create:false ~write:false db (fun _ -> sql) | _ -> Fmt.epr "sql: over the in-memory store only script and query run@."; exit 2