Something went wrong. Try again.
My own corner of monopam
Something went wrong. Try again.
2.6 kB · 62 lines
OCaml
at main
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263open Cmdliner
(* The named file, or stdin when none was named. A refused script is raised as the [Failure] [Common.user_error] reports, which names the script rather than the database: this is the one subcommand holding two paths. *)let load_script env = function | None -> Eio.Flow.read_all (Eio.Stdenv.stdin env) | Some f -> ( try Eio.Path.load (Common.cli_path env f) with Eio.Io ((Eio.Fs.E _ as e), _) -> failwith (Common.unable_to_open ~noun:"script" f e))
let run () db journal_mode file = Common.user_error ~db @@ fun () -> Eio_main.run @@ fun env -> (* Read before the database is opened, so a refused script leaves no database behind it. *) let sql = load_script env file in Eio.Switch.run @@ fun sw -> (* Stop at the first failing statement, as sqlite3 -bail does, but still close so the committed statements reach the file. Syncing first would make durable a transaction the script left open, which closing discards. *) Sqlite.with_open ~sw ~create:true ?journal_mode ~clock:(Common.clock env) (Common.db_path env db) @@ fun t -> Sqlite.Raw.run t sql ~params:[] ~on_row:List_mode.print
let cmd = let file_arg = Arg.( value & pos 1 (some string) None & info [] ~docv:"FILE" ~doc:"SQL script file to run; reads stdin when omitted.") in let info = Cmd.info "script" ~doc:"Run a SQL script, like sqlite3 db < file." ~man: [ `S Manpage.s_description; `P "Execute a $(b,;)-separated script of statements against a \ database (created if absent). Each $(b,SELECT)'s rows are printed \ as pipe-separated values, matching the sqlite3 CLI's list mode; \ the other statements are run for their effect."; `P "A failing statement stops the script and exits 1, as $(b,sqlite3 \ -bail) does; the statements before it stay committed."; `P "Use $(b,--journal-mode) to say how the commit reaches the file. \ It decides the mode a database being created is created in, and \ moves one that is already there; $(b,PRAGMA journal_mode) in the \ script itself moves it again."; `S Manpage.s_examples; `P "$(iname) mydb.db schema.sql"; `P "echo 'SELECT count(*) FROM t;' | $(iname) mydb.db"; `P "$(iname) --journal-mode=delete mydb.db schema.sql"; ] in Cmd.v info Term.( const run $ Common.logging $ Common.db_arg $ Common.journal_mode $ file_arg)