Something went wrong. Try again.
SQL frontend over the catalog engine
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061(* SQLite's JSONB (jsonb.html): its detection and its verbs. Every expected value is the answer of the reference sqlite3, 3.54.1 as Homebrew builds it, to the same call: the BLOBs as its hex() prints them, so a header of the wrong width or an element of the wrong type shows. *)
module J = Sql.Jsonb
let hex s = String.uppercase_ascii (Hex.encode s)let unhex = Hex.decode
(* A short BLOB could be JSON text cast to a BLOB, so it is JSONB only when every element is well formed; a longer one only needs its outer size. *)let test_sniff () = let c what expected b = Alcotest.(check bool) what expected (J.sniff b) in c "an empty array" true "\x0b"; c "a null" true "\x00"; c "the text [1]" false "[1]"; c "the text 1" false "1"; c "nothing" false ""; c "a size past the end" false "\xcb\x09\x13"; c "a short array whose first byte is not a JSON one" true "\x2b\x13\x41"; c "a short array spelt '['" true "\x5b\x13\x31\x13\x32\x00"; c "a short array spelt '[' cut in an element" false "\x5b\x13\x31\x13\x31\x13"
(* The verbs read and write the bytes sqlite3 writes: jsonb('[1,"a",{"b": null}]'), a short payload under a one-byte header. *)let doc1 = unhex "8B133117613C176200"let jvalue = Alcotest.testable J.Value.pp J.Value.equal
let test_verbs () = let v = J.Value.Array [ Int "1"; Text "a"; Object [ (Text "b", Null) ] ] in Alcotest.check jvalue "of_string" v (J.of_string_exn J.Codec.Value.t doc1); Alcotest.(check string) "to_string" (hex doc1) (hex (J.to_string J.Codec.Value.t v)); let b = Buffer.create 16 in Buffer.add_string b "x"; J.to_writer J.Codec.Value.t v b; Alcotest.(check string) "to_writer adds" ("78" ^ hex doc1) (hex (Buffer.contents b)); Alcotest.check jvalue "encode then decode" v (J.decode_exn J.Codec.Value.t (J.encode J.Codec.Value.t v)); Alcotest.(check bool) "a truncated document is refused" true (Result.is_error (J.of_string J.Codec.ignore (unhex "CB0513"))); Alcotest.(check bool) "trailing bytes are refused" true (Result.is_error (J.of_string J.Codec.ignore (doc1 ^ "\000"))); Alcotest.(check bool) "a bool codec on an int" true (Result.is_error (J.of_string J.Codec.bool (unhex "1331")))
let suite = ( "jsonb", [ Alcotest.test_case "sniff" `Quick test_sniff; Alcotest.test_case "verbs" `Quick test_verbs; ] )