(*--------------------------------------------------------------------------- Copyright (c) 2026 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*) (* The json1 functions of sqlite/src/json.c at version-3.54.1, over {!Jsonb}: each reads its JSON argument as JSONB, a BLOB that {!Jsonb.sniff}s as JSONB as it is and anything else parsed from its text, and answers JSON text or, for a [jsonb_] function, JSONB. Text is read and written by {!Json_text}, json.c's own parser and renderer. *) module Value = Catalog.Value module Error = Catalog.Error type answer = Value.t * bool type extract = Extract | Extract_blob | Arrow_json | Arrow_sql type edit = Insert | Replace | Set | Array_insert module C = Jsonb_codec module Cursor = Jsonb_cursor module T = Json_text let malformed () = Jsonb_error.fail_malformed () let fail_path = Jsonb_error.fail_path (* sqlite3DecOrHexToI64 over the digits of a hexadecimal integer *) let hex_int s len = let rec zeros i = if i < len && s.[i] = '0' then zeros (i + 1) else i in let i = zeros 2 in let rec digits k u = if k < len && Jsonb_core.is_xdigit (Char.code s.[k]) then digits (k + 1) (Int64.add (Int64.mul u 16L) (Int64.of_int (Jsonb_core.hex_value (Char.code s.[k])))) else (k, u) in let k, u = digits i 0L in if k - i > 16 then `Overflow else if k < len then `Bad else `Hex u (* sqlite3DecOrHexToI64 over a JSONB integer's digits *) let dec_or_hex s = let len = String.length s in if len >= 2 && s.[0] = '0' && (s.[1] = 'x' || s.[1] = 'X') then hex_int s len else if len = 0 || not (String.for_all (fun c -> c >= '0' && c <= '9') s) then `Bad else match Int64.of_string_opt s with | Some v -> `Int v | None -> let rec zeros i = if i < len - 1 && s.[i] = '0' then zeros (i + 1) else i in let i = zeros 0 in if String.sub s i (len - i) = "9223372036854775808" then `Min else `Overflow (* sqlite3AtoF over the whole text, which must be a number *) let double_of_text s = match Value_ops.whole_number s with | Some (Int i) -> Value.Float (Int64.to_float i) | Some (Float f) -> Value.Float f | _ -> malformed () (* the unsigned [u] as a double, rounded once: halved keeping the low bit sticky, converted, doubled *) let unsigned_float u = let half = Int64.logor (Int64.shift_right_logical u 1) (Int64.logand u 1L) in Int64.to_float half *. 2. (* an INT or INT5 payload as an SQL value *) let int_value text = let neg = String.length text > 0 && text.[0] = '-' in if neg && String.length text < 2 then malformed () else let digits = if neg then String.sub text 1 (String.length text - 1) else text in let sign v = if neg then Int64.neg v else v in match dec_or_hex digits with | `Int v -> Value.Int (sign v) | `Hex u when Int64.compare u 0L < 0 -> let r = unsigned_float u in Value.Float (if neg then -.r else r) | `Hex u -> Value.Int (sign u) | `Min -> if neg then Value.Int Int64.min_int else double_of_text text | `Bad -> malformed () | `Overflow -> double_of_text text (* jsonReturnFromBlob: an element as an SQL value, an array or an object as [container] reads it *) let sql_value container = C.any ~kind:"SQL value" ~null:(C.null Value.Null) ~bool:(C.map ~dec:(fun b -> Value.Int (if b then 1L else 0L)) C.bool) ~int:(C.map ~dec:int_value C.int) ~float:(C.map ~dec:double_of_text C.float) ~text:(C.map ~dec:(fun s -> Value.Text s) C.text) ~array:container ~object':container () let sql_text = sql_value (C.map ~dec:(fun sub -> Value.Text (T.text_at (Cursor.of_string sub) 0)) C.element) let sql_blob = sql_value (C.map ~dec:(fun sub -> Value.Blob sub) C.element) let no_blob () = Error.fail_runtime "JSON cannot hold BLOB values" (* jsonFunctionArgToBlob: an SQL value to store in JSONB, text as a string *) let arg = let null = C.null Value.Null in let blob = C.map ~enc:(function | Value.Blob s when Jsonb_core.is_jsonb s -> s | _ -> no_blob ()) C.element in let text = C.map ~enc:Value_ops.text_of_value C.text in let int = C.map ~enc:Value_ops.text_of_value C.int in let real = C.map ~enc:(fun v -> match Value_ops.text_of_value v with | "Inf" -> "9e999" | "-Inf" -> "-9e999" | z -> z) C.float in C.any ~kind:"SQL value" ~enc:(function | Value.Null -> null | Blob _ -> blob | Text _ -> text | Float f when Float.is_nan f -> null | Float _ -> real | Int _ -> int) () (* jsonAppendSqlValue *) let add_sql_value (o : T.out) (v : Value.t) = match v with | Null -> Buffer.add_string o.b "null" | Float f -> if Float.is_finite f then Buffer.add_string o.b (Value_ops.text_of_float f) else if f > 0. then Buffer.add_string o.b "9.0e+999" else Buffer.add_string o.b "-9.0e+999" | Int i -> Buffer.add_string o.b (Int64.to_string i) | Text s -> T.add_string o.b s 0 (String.length s) | Blob s -> if Jsonb_core.is_jsonb s then begin ignore (T.render (Cursor.of_string s) 0 o : int); if o.deep then Jsonb_error.fail_too_deep () end else no_blob () (* jsonParseFuncArg: [None] for NULL *) let parse_arg (v : Value.t) = match v with | Null -> None | Blob s when Jsonb_core.is_jsonb s -> Some (Cursor.of_string s) | v -> ( let z = Value_ops.text_of_value v in if z = "" then malformed () else match T.of_string z with Ok t -> Some t | Error _ -> malformed ()) (* jsonReturnParse *) let result c ~blob : answer = if blob then (Value.Blob (Cursor.to_string c), false) else (Value.Text (T.text_at c 0), true) (* jsonReturnString *) let text_result (o : T.out) ~blob : answer = if o.deep then Jsonb_error.fail_too_deep () else if o.bad then malformed () else let s = Buffer.contents o.b in if blob then (Value.Blob (T.blob_of_text s), false) else (Value.Text s, true) let null : answer = (Value.Null, false) let json ~blob v = match parse_arg v with None -> null | Some c -> result c ~blob let quote v = let o = T.out () in add_sql_value o v; text_result o ~blob:false let array ~blob args = let o = T.out () in Buffer.add_char o.b '['; List.iteri (fun i v -> if i > 0 then Buffer.add_char o.b ','; add_sql_value o v) args; Buffer.add_char o.b ']'; text_result o ~blob let rec add_members o first = function | (Value.Text s : Value.t) :: v :: rest -> if not first then Buffer.add_char o.T.b ','; T.add_string o.T.b s 0 (String.length s); Buffer.add_char o.T.b ':'; add_sql_value o v; add_members o false rest | _ :: _ :: _ -> Error.fail_runtime "json_object() labels must be TEXT" | [] | [ _ ] -> () let object_ ~blob args = if List.length args land 1 = 1 then Error.fail_runtime "json_object() requires an even number of arguments"; let o = T.out () in Buffer.add_char o.b '{'; add_members o true args; Buffer.add_char o.b '}'; text_result o ~blob (* the cursor focused on what a path argument names: [false] for a NULL path or nothing at the path *) let at_path c (p : Value.t) = match p with | Null -> false | p -> ( let path = Value_ops.text_of_value p in match Cursor.seek path c with | Ok found -> found | Error e -> fail_path e path) let array_length v path = match parse_arg v with | None -> null | Some c -> let found = match path with None -> true | Some p -> at_path c p in if found then (Value.Int (Int64.of_int (Cursor.length c)), false) else null let type_name : Jsonb_sort.t option -> string = function | Some Null -> "null" | Some True -> "true" | Some False -> "false" | Some (Int | Int5) -> "integer" | Some (Float | Float5) -> "real" | Some (Text | Textj | Text5 | Textraw) -> "text" | Some Array -> "array" | Some Object -> "object" | None -> "" let type_ v path = match parse_arg v with | None -> null | Some c -> let found = match path with None -> true | Some p -> at_path c p in if found then (Value.Text (type_name (Cursor.sort c)), false) else null (* jsonAllAlphanum *) let all_alnum s = String.for_all (fun c -> Jsonb_core.is_alnum (Char.code c) || c = '_') s (* the full path an abbreviated [->] path stands for *) let abbreviated (p : Value.t) path = let np = String.length path in match p with | Int _ -> if path.[0] = '-' then "$[#" ^ path ^ "]" else "$[" ^ path ^ "]" | _ -> if all_alnum path then "$." ^ path else if np >= 3 && path.[0] = '[' && path.[np - 1] = ']' then "$" ^ path else "$.\"" ^ path ^ "\"" (* whether [p] lands in [c], focusing it there *) let extract_at mode c (p : Value.t) = let path = Value_ops.text_of_value p in let r = if String.length path > 0 && path.[0] = '$' then Cursor.seek path c else if mode = Arrow_json || mode = Arrow_sql then Cursor.seek (abbreviated p path) c else fail_path Bad_path path in match r with Ok found -> found | Error e -> fail_path e path (* the answer for the one path that landed at the focus *) let extracted mode c : answer = match mode with | Arrow_json -> (Value.Text (T.text_at c c.Jsonb_core.at), true) | Arrow_sql -> (Cursor.get sql_text c, false) | Extract -> let tagged = match Cursor.sort c with Some (Array | Object) -> true | _ -> false in (Cursor.get sql_text c, tagged) | Extract_blob -> (Cursor.get sql_blob c, false) let extract mode v paths = match (parse_arg v, paths) with | None, _ | Some _, [ Value.Null ] -> null | Some c, [ p ] -> if extract_at mode c p then extracted mode c else null | Some c, paths -> let o = T.out () in let rec go i = function | [] -> Buffer.add_char o.b ']'; text_result o ~blob:(mode = Extract_blob) | Value.Null :: _ -> null | p :: rest -> let found = extract_at mode c p in Buffer.add_char o.b (if i = 0 then '[' else ','); if found then ignore (T.render c c.Jsonb_core.at o : int) else Buffer.add_string o.b "null"; go (i + 1) rest in go 0 paths let remove ~blob v paths = match parse_arg v with | None -> null | Some c -> let rec go = function | [] -> result c ~blob | (Value.Null : Value.t) :: _ -> null | p :: rest -> ( let path = Value_ops.text_of_value p in if path = "$" then null else match Cursor.remove path c with | Ok () -> go rest | Error e -> fail_path e path) in go paths (* jsonInsertIntoBlob *) let edit e ~blob args = let name, edit = match e with | Insert -> ("insert", Cursor.insert) | Replace -> ("replace", Cursor.replace) | Set -> ("set", Cursor.set) | Array_insert -> ("array_insert", Cursor.array_insert) in if List.length args land 1 = 0 && args <> [] then Error.fail_runtime "json_%s() needs an odd number of arguments" name; match args with | [] -> null | v :: pairs -> ( match parse_arg v with | None -> null | Some c -> let rec go = function | (p : Value.t) :: x :: rest -> ( match p with | Null -> go rest | _ -> ( let path = Value_ops.text_of_value p in match edit path arg x c with | Ok () -> go rest | Error e -> fail_path e path)) | _ -> () in go pairs; result c ~blob) (* the FLAGS of json_valid, 1 by default *) let valid_flags = function | None -> 1 | Some (f : Value.t) -> let f = match Value_ops.leading_number (Value_ops.text_of_value f) with | Int i -> i | Float x -> Int64.of_float x | _ -> 0L in let f = match f with _ when f < 1L || f > 15L -> 0 | f -> Int64.to_int f in if f = 0 then Error.fail_runtime "FLAGS parameter to json_valid() must be between 1 and 15"; f let valid v flags = let flags = valid_flags flags in let text () = flags land 0x3 <> 0 && let z = Value_ops.text_of_value v in z <> "" && match T.of_string z with | Error _ -> false | Ok t -> flags land 0x02 <> 0 || not t.Jsonb_core.has_nonstd in let ok = match (v : Value.t) with | Null -> None | Blob s when Jsonb_core.is_jsonb s -> Some (flags land 0x04 <> 0 || flags land 0x08 <> 0 && Result.is_ok (Jsonb.of_string Jsonb.Codec.ignore s)) | _ -> Some (text ()) in match ok with | None -> null | Some ok -> (Value.Int (if ok then 1L else 0L), false) (* jsonPrettyFunc: the indent ends at its first NUL, as strlen reads it *) let pretty v indent = match parse_arg v with | None -> null | Some c -> let indent = match indent with | None | Some Value.Null -> " " | Some i -> ( let s = Value_ops.text_of_value i in match String.index_opt s '\000' with | Some n -> String.sub s 0 n | None -> s) in (Value.Text (T.pretty c ~indent), false) (* jsonErrorFunc: the validity check's offset in JSONB, and in text the count of characters before where the parser stopped, plus one *) let error_position (v : Value.t) = match v with | Null -> null | Blob s when Jsonb_core.is_jsonb s -> let t = Jsonb_core.of_blob s in let pos = Jsonb_core.validity t 0 (String.length s) 1 in (Value.Int (Int64.of_int pos), false) | v -> ( let z = Value_ops.text_of_value v in match T.of_string z with | Ok _ -> (Value.Int 0L, false) | Error err -> let rec chars k n = if k >= err || k >= String.length z || z.[k] = '\000' then n else chars (k + 1) (if Char.code z.[k] land 0xc0 <> 0x80 then n + 1 else n) in (Value.Int (Int64.of_int (chars 0 0 + 1)), false)) (* jsonArrayStep / jsonArrayCompute *) let group_array ~blob = let o = T.out () in let any = ref false in let step v = Buffer.add_char o.b (if !any then ',' else '['); any := true; add_sql_value o v in let finish () = let s = if !any then Buffer.contents o.b ^ "]" else "[]" in if blob then Value.Blob (T.blob_of_text s) else Value.Text s in (step, finish) (* jsonObjectStep / jsonObjectCompute: a NULL label adds no member, and a label ends at its first NUL *) let group_object ~blob = let o = T.out () in let any = ref false in let step (k : Value.t) v = if k <> Null then begin Buffer.add_char o.b (if !any then ',' else '{'); any := true; let s = Value_ops.text_of_value k in let len = match String.index_opt s '\000' with | Some i -> i | None -> String.length s in T.add_string o.b s 0 len; Buffer.add_char o.b ':'; add_sql_value o v end in let finish () = let s = if !any then Buffer.contents o.b ^ "}" else "{}" in if blob then Value.Blob (T.blob_of_text s) else Value.Text s in (step, finish) let embed ((v, json) : answer) = match v with | Value.Text s when json -> Value.Blob (T.blob_of_text s) | v -> v (* The JSON aggregates, as {!Value_ops.agg_acc} folds *) let aggregate name ~nargs ~coll : Value_ops.agg_acc = match name with | ("json_group_array" | "jsonb_group_array") when nargs > 0 -> let step, finish = group_array ~blob:(name.[4] = 'b') in Value_ops.of_values ~nargs ~finish ~step:(fun row base -> step row.(base)) | ("json_group_object" | "jsonb_group_object") when nargs > 0 -> let step, finish = group_object ~blob:(name.[4] = 'b') in Value_ops.of_values ~nargs ~finish ~step:(fun row base -> step row.(base) row.(base + 1)) | _ -> Value_ops.agg_acc name ~nargs ~coll