summaryrefslogtreecommitdiff
path: root/lib/value/value.ml
blob: 1b1112d6ed740982e1ad1515e6df74d55afabd1f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
type value = Model.target Model.Data.any
(** A resolved field data: the data of a field of a content or a list, whatever
    the type of the data held *)

let none : value = Model.Data.any Model.Data.none

let single : ('db, 'ocaml, Model.target) Model.Types.t * 'ocaml -> value =
 fun data -> Model.Data.any (Model.Data.v data)

module Property = Property

(** The key of the fields dictionary: an existential pack over the property of a
    field, hiding its ['db] and ['ocaml] parameters *)
type key = Named : ('db, 'ocaml, Model.target) Model.Types.t Property.t -> key

module Key = struct
  type t = key

  let equal : t -> t -> bool = fun (Named a) (Named b) -> Property.same a b
  let hash : t -> int = fun (Named n) -> Hashtbl.hash (Property.name n)
end

module Properties = Hashtbl.Make (Key)

type t = {
  target : Model.target;  (** The content or list whose table holds the row *)
  id : int64;  (** The primary key of the row *)
  fields : value Properties.t;
      (** Cache of the other fields and their values, keyed by their named type
          — empty by default, populating it requires reading the database *)
}
(** A value: one row of a content or list table in the database, identified by
    its {!Model.target} and its [id] *)

let v : Model.target -> int64 -> t =
 fun target id -> { target; id; fields = Properties.create 0 }

let target : t -> Model.target = fun t -> t.target
let id : t -> int64 = fun t -> t.id

let add_property : type ocaml.
    t -> ('db, ocaml, Model.target) Model.Types.t Property.t -> ocaml -> unit =
 fun t ref data ->
  let typ = Property.typ ref in
  Properties.replace t.fields (Named ref)
    (Model.Data.any (Model.Data.v (typ, data)))

let id_ref : Model.target Model.Types.monoreference Property.t =
  Property.named ~name:Model.Identifier.id ~typ:Model.Types.Integer

(** Cast a stored field data to the ['ocaml] representation of [ref_typ], when
    the stored type matches the requested one. The existential parameters of the
    stored data are packed behind the locally abstract types of this function,
    so that the pair equality of {!Model.Types.eq} can be decomposed inside *)
let cast : type db ocaml db' ocaml'.
    (db, ocaml, Model.target) Model.Types.t ->
    (db', ocaml', Model.target) Model.Types.t ->
    ocaml' ->
    ocaml option =
 fun ref_typ typ payload ->
  match Model.Types.eq ref_typ typ with
  | Some Type.Equal -> Some payload
  | None -> None

let get : type ocaml.
    t -> ('db, ocaml, Model.target) Model.Types.t Property.t -> ocaml =
 fun t ref ->
  match Property.provably_equal id_ref ref with
  | Some Type.Equal -> Some t.id
  | None -> (
      match Properties.find_opt t.fields (Named ref) with
      | Some (Model.Data.Any (Model.Data.V (typ, payload))) -> (
          match cast (Property.typ ref) typ payload with
          | Some data -> data
          | None -> raise Not_found)
      | _ -> raise Not_found)

(** Read the row of [t] from the database and store each field in [t]'s
    dictionary — the value is modified in place. With [~multivalued:false], the
    multivalued reference fields are not read *)
let load' : Caqti_lwt.connection -> ?multivalued:bool -> t -> unit Lwt.t =
 fun db ?(multivalued = true) t ->
  let ( let* ) = Lwt.bind in
  let* () =
    match t.target with
    | Model.Reference.Content ref ->
        Query.select db ~multivalued (id t) (Model.Reference.get ref)
          {
            f =
              (fun ((name, typ), data) ->
                add_property t (Property.named ~name ~typ) data);
          }
    | Model.Reference.List list ->
        Query.select_list db ~multivalued (id t) list
          {
            f =
              (fun ((name, typ), data) ->
                add_property t (Property.named ~name ~typ) data);
          }
  in
  Lwt.return_unit

let load :
    Caqti_lwt.connection ->
    ?multivalued:bool ->
    Model.target ->
    Int64.t ->
    t Lwt.t =
 fun db ?(multivalued = true) target id ->
  let ( let* ) = Lwt.bind in
  let v = v target id in
  let* () = load' db ~multivalued v in
  Lwt.return v

(** Pretty-print the data of a field, whatever its type *)
let pp_data : type db ocaml.
    Format.formatter -> (db, ocaml, Model.target) Model.Types.t -> ocaml -> unit
    =
 fun fmt typ data ->
  let pp_option pp fmt data =
    match data with
    | Some v -> pp fmt v
    | None -> Format.pp_print_string fmt "NULL"
  in
  match typ with
  | Model.Types.Text ->
      pp_option (fun fmt s -> Format.fprintf fmt "%S" s) fmt data
  | Model.Types.Integer ->
      pp_option (fun fmt i -> Format.fprintf fmt "%Ld" i) fmt data
  | Model.Types.MonoReference _ ->
      pp_option (fun fmt i -> Format.fprintf fmt "%Ld" i) fmt data
  | Model.Types.MultiReference _ ->
      Format.fprintf fmt "[%a]"
        (Format.pp_print_list
           ~pp_sep:(fun fmt () -> Format.pp_print_string fmt ", ")
           (fun fmt i -> Format.fprintf fmt "%Ld" i))
        (List.of_seq data)

let pp : Format.formatter -> t -> unit =
 fun fmt t ->
  let fields =
    Properties.fold
      (fun (Named named) data acc -> (Property.name named, data) :: acc)
      t.fields []
    |> List.sort (fun (n1, _) (n2, _) -> Model.Identifier.compare n1 n2)
  in
  let pp_field fmt (name, data) =
    let (Model.Data.Any d) = data in
    match d with
    | Model.Data.None ->
        Format.fprintf fmt "%s = NULL" (Model.Identifier.to_string name)
    | Model.Data.V (typ, payload) ->
        Format.fprintf fmt "%s = " (Model.Identifier.to_string name);
        pp_data fmt typ payload
  in
  Format.fprintf fmt "{@[id = %Ld;@ %a@]}" t.id
    (Format.pp_print_list
       ~pp_sep:(fun fmt () -> Format.pp_print_string fmt "; ")
       pp_field)
    fields