|
| 1 | +open Postgresql |
| 2 | + |
| 3 | +let _ = |
| 4 | + if Array.length Sys.argv <> 2 then ( |
| 5 | + Printf.printf "\ |
| 6 | + Usage: async conninfo\n\ |
| 7 | + Connect to PostgreSQL with [conninfo] (e.g. \"host=localhost\"),\n\ |
| 8 | + and run async tests on a temporary table\n"; |
| 9 | + exit 1) |
| 10 | + |
| 11 | +let wait_for_result c = |
| 12 | + c#consume_input; |
| 13 | + while c#is_busy do |
| 14 | + ignore (Unix.select [Obj.magic c#socket] [] [] (-.1.0)); |
| 15 | + c#consume_input |
| 16 | + done |
| 17 | + |
| 18 | +let fetch_result c = wait_for_result c; c#get_result |
| 19 | + |
| 20 | +let fetch_single_result c = |
| 21 | + match fetch_result c with |
| 22 | + | None -> assert false |
| 23 | + | Some r -> assert (fetch_result c = None); r |
| 24 | + |
| 25 | +let main () = |
| 26 | + let c = new connection ~conninfo:Sys.argv.(1) () in |
| 27 | + c#set_nonblocking true; |
| 28 | + c#send_query "\ |
| 29 | + CREATE TEMPORARY TABLE postgresql_ocaml_async \ |
| 30 | + (id SERIAL PRIMARY KEY, a INTEGER NOT NULL, b TEXT NOT NULL)"; |
| 31 | + assert ((fetch_single_result c)#status = Command_ok); |
| 32 | + c#send_prepare "test_ins" |
| 33 | + "INSERT INTO postgresql_ocaml_async (a, b) VALUES ($1, $2)"; |
| 34 | + assert ((fetch_single_result c)#status = Command_ok); |
| 35 | + c#send_query_prepared ~params:[|"2"; "two"|] "test_ins"; |
| 36 | + assert ((fetch_single_result c)#status = Command_ok); |
| 37 | + c#send_query_prepared ~params:[|"3"; "three"|] "test_ins"; |
| 38 | + assert ((fetch_single_result c)#status = Command_ok); |
| 39 | + c#send_prepare "test_sel" "SELECT * FROM postgresql_ocaml_async"; |
| 40 | + assert ((fetch_single_result c)#status = Command_ok); |
| 41 | + c#send_describe_prepared "test_sel"; |
| 42 | + let r = fetch_single_result c in |
| 43 | + assert (r#status = Command_ok); |
| 44 | + assert (r#nfields = 3); |
| 45 | + assert (r#fname 0 = "id"); |
| 46 | + assert (r#fname 1 = "a"); |
| 47 | + assert (r#fname 2 = "b"); |
| 48 | + c#send_query_prepared "test_sel"; |
| 49 | + let r = fetch_single_result c in |
| 50 | + assert (r#status = Tuples_ok); |
| 51 | + assert (r#ntuples = 2); |
| 52 | + assert (r#nfields = 3); |
| 53 | + for i = 0 to r#ntuples - 1 do |
| 54 | + Printf.printf "%s %s %s\n" |
| 55 | + (r#getvalue i 0) (r#getvalue i 1) (r#getvalue i 2) |
| 56 | + done |
| 57 | + |
| 58 | +let _ = |
| 59 | + try main () with |
| 60 | + | Error e -> prerr_endline (string_of_error e) |
| 61 | + | e -> prerr_endline (Printexc.to_string e) |
0 commit comments