summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--lib/common/dune3
-rw-r--r--lib/common/format.ml10
-rw-r--r--lib/model/typ.ml4
-rw-r--r--lib/query/common.ml0
-rw-r--r--lib/query/dune1
-rw-r--r--lib/query/encoder.ml3
-rw-r--r--lib/query/insert.ml45
-rw-r--r--lib/query/insert.mli11
-rw-r--r--lib/query/query.ml1
-rw-r--r--lib/query/query.mli7
-rw-r--r--lib/query/tests/update.t99
-rw-r--r--lib/query/update.ml182
-rw-r--r--lib/splay/splay.ml44
-rw-r--r--lib/splay/tests/splay.t24
-rw-r--r--test/common.ml86
-rw-r--r--test/configuration_.ml2
-rw-r--r--test/dune1
-rw-r--r--test/hash.ml2
-rw-r--r--test/insert.ml93
-rw-r--r--test/intf.ml6
-rw-r--r--test/parent.ml2
-rw-r--r--test/schema.ml2
-rw-r--r--test/splay_tree.ml2
-rw-r--r--test/tests.ml3
-rw-r--r--test/update.ml207
25 files changed, 698 insertions, 142 deletions
diff --git a/lib/common/dune b/lib/common/dune
new file mode 100644
index 0000000..d070694
--- /dev/null
+++ b/lib/common/dune
@@ -0,0 +1,3 @@
+(library
+ (name croquette_common)
+ (libraries))
diff --git a/lib/common/format.ml b/lib/common/format.ml
new file mode 100644
index 0000000..5245dd0
--- /dev/null
+++ b/lib/common/format.ml
@@ -0,0 +1,10 @@
+(** [format_string f] call the function [f] with a fresh formatter and return
+ the content as a string *)
+let format_string : (Stdlib.Format.formatter -> unit) -> string =
+ fun f ->
+ let buff = Buffer.create 16 in
+ let format = Stdlib.Format.formatter_of_buffer buff in
+ let () = f format in
+
+ Stdlib.Format.pp_print_flush format ();
+ Buffer.contents buff
diff --git a/lib/model/typ.ml b/lib/model/typ.ml
index d736be0..98429d6 100644
--- a/lib/model/typ.ml
+++ b/lib/model/typ.ml
@@ -47,8 +47,8 @@ Example for inserting data
(* Function providing a value for each field to insert in the database *)
let f : string -> Model.Reference.t Model.Field.value = function
- | "siret" -> V (Model.Field.Text, Some "siret")
- | "name" -> V (Model.Field.Text, Some "name")
+ | "siret" -> V (Model.Typ.Text, Some "siret")
+ | "name" -> V (Model.Typ.Text, Some "name")
| _ -> None
let* id = Query.insert db entity_content f in
diff --git a/lib/query/common.ml b/lib/query/common.ml
deleted file mode 100644
index e69de29..0000000
--- a/lib/query/common.ml
+++ /dev/null
diff --git a/lib/query/dune b/lib/query/dune
index b9a862a..307319a 100644
--- a/lib/query/dune
+++ b/lib/query/dune
@@ -7,5 +7,6 @@
lwt.unix
lwt
uri
+ croquette_common
model
configuration))
diff --git a/lib/query/encoder.ml b/lib/query/encoder.ml
index c9314cb..ae34c3e 100644
--- a/lib/query/encoder.ml
+++ b/lib/query/encoder.ml
@@ -261,8 +261,7 @@ module EncodeParameter = Map (struct
| { content_type = Text; _ } -> "?"
| { content_type = Integer; _ } -> "?"
| { content_type = MonoReference _; _ } -> "?"
- | { content_type = MultiReference _; _ } ->
- failwith "Cannot encode multireference field"
+ | { content_type = MultiReference _; _ } -> "?"
include ConcatParam
end)
diff --git a/lib/query/insert.ml b/lib/query/insert.ml
index 1ee1549..ecb0efb 100644
--- a/lib/query/insert.ml
+++ b/lib/query/insert.ml
@@ -21,15 +21,6 @@ let collect_fields :
let (Model.Field.T content_type) = Model.Field.type_ field in
TT { name; content_type })
-let format_string : (Format.formatter -> unit) -> string =
- fun f ->
- let buff = Buffer.create 16 in
- let format = Format.formatter_of_buffer buff in
- let () = f format in
-
- Format.pp_print_flush format ();
- Buffer.contents buff
-
module MultiReferencesInsert = struct
type 'a t = {
db : Caqti_lwt.connection;
@@ -80,7 +71,7 @@ module MultiReferencesInsert = struct
| None -> raise Encoder.TypeMismatch
| Some Equal ->
let q =
- format_string (fun format ->
+ Croquette_common.Format.format_string (fun format ->
Format.fprintf format
"INSERT INTO \"%s.%s\" (\"parent\", \"target\") VALUES \
(?, ?)"
@@ -96,7 +87,9 @@ module MultiReferencesInsert = struct
let* res =
Seq.fold_left (accumulate db request parent_id) k values
in
- let* _ = Db.deallocate request in
+ let* () = Caqti_lwt.or_fail res in
+ let* res = Db.deallocate request in
+ let* () = Caqti_lwt.or_fail res in
Lwt.return res
in
@@ -141,7 +134,7 @@ let insert_returning :
in
let q =
- format_string (fun format ->
+ Croquette_common.Format.format_string (fun format ->
Format.fprintf format "INSERT INTO \"%s\" %s VALUES %s RETURNING ID"
(Model.Content.id content) columns insert_template)
in
@@ -169,9 +162,9 @@ let insert_returning :
MultiReferencesInsert.
{ db; provider; k = Lwt.return_ok (); parent_id = content_id; content }
in
- let ret = Fold.f acc multi_valuated_fields in
- let* k = ret.k in
- let* () = Caqti_lwt.or_fail k in
+ let MultiReferencesInsert.{ k; _ } = Fold.f acc multi_valuated_fields in
+ let* res = k in
+ let* () = Caqti_lwt.or_fail res in
Lwt.return content_id
(** Insert an entry for a specific content *)
@@ -199,3 +192,25 @@ let insert :
match Caqti_driver_info.dialect_tag Db.driver_info with
| `Sqlite | `Pgsql -> insert_returning db content provider
| _ -> raise Not_found
+
+let insert_references :
+ Caqti_lwt.connection ->
+ Model.Reference.t Model.Content.t ->
+ Int64.t ->
+ string ->
+ Model.Reference.t Model.Typ.value ->
+ Int64.t Intf.data ->
+ unit Lwt.t =
+ fun db content content_id field_name value data ->
+ let provider : string -> Model.Reference.t Model.Typ.value = function
+ | n when String.equal n field_name -> value
+ | _ -> Model.Typ.None
+ in
+ let acc =
+ MultiReferencesInsert.
+ { db; provider; k = Lwt.return_ok (); parent_id = content_id; content }
+ in
+ let ( let* ) = Lwt.bind in
+ let MultiReferencesInsert.{ k; _ } = MultiReferencesInsert.f acc data in
+ let* res = k in
+ Caqti_lwt.or_fail res
diff --git a/lib/query/insert.mli b/lib/query/insert.mli
index f19ff11..798c37b 100644
--- a/lib/query/insert.mli
+++ b/lib/query/insert.mli
@@ -7,3 +7,14 @@ val insert :
(string -> Model.Reference.t Model.Typ.value) ->
int64 Lwt.t
(** See [Query.insert] *)
+
+val insert_references :
+ Caqti_lwt.connection ->
+ Model.Reference.t Model.Content.t ->
+ Int64.t ->
+ string ->
+ Model.Reference.t Model.Typ.value ->
+ Int64.t Intf.data ->
+ unit Lwt.t
+(** Insert a list of references for a content. This function is used during the
+ update but is not exposed outside of the module *)
diff --git a/lib/query/query.ml b/lib/query/query.ml
index 4aaf467..13a646a 100644
--- a/lib/query/query.ml
+++ b/lib/query/query.ml
@@ -7,3 +7,4 @@
let insert = Insert.insert
let create = Create.create
+let update = Update.q
diff --git a/lib/query/query.mli b/lib/query/query.mli
index 9dcef17..24e0591 100644
--- a/lib/query/query.mli
+++ b/lib/query/query.mli
@@ -20,3 +20,10 @@ val insert :
itself, and no functionnals controls are realized. *)
val create : Caqti_lwt.connection -> Configuration.Ast.setting -> unit Lwt.t
+
+val update :
+ Caqti_lwt.connection ->
+ Int64.t ->
+ Model.Reference.t Model.Content.t ->
+ (string -> Model.Reference.t Model.Typ.value) ->
+ unit Lwt.t
diff --git a/lib/query/tests/update.t b/lib/query/tests/update.t
new file mode 100644
index 0000000..32c04bb
--- /dev/null
+++ b/lib/query/tests/update.t
@@ -0,0 +1,99 @@
+Test the update method of a content.
+
+The test create a content with four features:
+- text
+- integer
+- mono reference
+- multi references
+and each test start with a new content empty.
+
+ $ tests --update --help
+ Start the tests
+ --text <v> Set field with the value <v>
+ --integer <n> Set field with the value <n>
+ --reference <id> Set field with the id
+ --references <id,..> Set this list of values
+ --commit Commit this group of update
+ --clear <f> Clear the field <f>
+ -help Display this list of options
+ --help Display this list of options
+
+After each invocation (or after a commit), the test displays the values for the
+content. By default it is empty:
+
+ $ tests --update \
+ > --commit
+ {"reference":null,"integer":null,"text":null}
+
+The multivaluated field references is not displayed when there is no values.
+
+Any feature can be set using an argument with the same name:
+
+ $ tests --update \
+ > --integer 123
+ {"reference":null,"integer":123,"text":null}
+
+ $ tests --update \
+ > --text abc
+ {"reference":null,"integer":null,"text":"abc"}
+
+ $ tests --update \
+ > --reference 1
+ {"reference":1,"integer":null,"text":null}
+
+The multireferences values are displayed only when they are set.
+
+ $ tests --update \
+ > --references 1,2,3 \
+ {"reference":null,"integer":null,"text":null}
+ {"references":1}
+ {"references":2}
+ {"references":3}
+
+The "commit" argument can be used to update the content at a given state
+
+ $ tests --update \
+ > --integer 123 \
+ > --text abc \
+ > --references 1 \
+ > --commit \
+ > --reference 1
+ {"reference":null,"integer":123,"text":"abc"}
+ {"references":1}
+ {"reference":1,"integer":123,"text":"abc"}
+ {"references":1}
+
+A field can be explicitally set empty. There is a difference between not
+updating a field (changing nothing) and setting the field to empty:
+
+ $ tests --update \
+ > --integer 123 \
+ > --text abc \
+ > --commit \
+ > --clear integer
+ {"reference":null,"integer":123,"text":"abc"}
+ {"reference":null,"integer":null,"text":"abc"}
+
+ $ tests --update \
+ > --references 1,2,3 \
+ > --commit \
+ > --clear references
+ {"reference":null,"integer":null,"text":null}
+ {"references":1}
+ {"references":2}
+ {"references":3}
+ {"reference":null,"integer":null,"text":null}
+
+There is no duplicates values in the external references, a new update replace
+the existing values.
+
+ $ tests --update \
+ > --references 1,2 \
+ > --commit \
+ > --references 1,3
+ {"reference":null,"integer":null,"text":null}
+ {"references":1}
+ {"references":2}
+ {"reference":null,"integer":null,"text":null}
+ {"references":1}
+ {"references":3}
diff --git a/lib/query/update.ml b/lib/query/update.ml
new file mode 100644
index 0000000..4b8adfb
--- /dev/null
+++ b/lib/query/update.ml
@@ -0,0 +1,182 @@
+(** Generate the update queries for a content *)
+
+type provider = string -> Model.Reference.t Model.Typ.value
+
+module UpdateTemplate = Encoder.Map (struct
+ type 'a t = string
+ type env = unit
+
+ let f : type a. unit -> a Intf.data -> a t =
+ fun () -> function
+ | { name = column; content_type = Text; _ } -> column ^ "=?"
+ | { name = column; content_type = Integer; _ } -> column ^ "=?"
+ | { name = column; content_type = MonoReference _; _ } -> column ^ "=?"
+ | { name = _; content_type = MultiReference _; _ } -> raise Not_found
+
+ include Encoder.ConcatParam
+end)
+
+let update_fields :
+ Caqti_lwt.connection ->
+ 'a Model.Content.t ->
+ (Intf.t_type * (string * Model.Reference.t Model.Typ.value)) list ->
+ int64 ->
+ unit Lwt.t =
+ fun db content fields id ->
+ let module Db = (val db) in
+ let fields_list, value_list = List.split fields in
+ (* Update all the fields stored in the content table *)
+ let (T query_fields) =
+ Encoder.list_to_tup fields_list ~f:(fun field -> field)
+ in
+ let format_param = (UpdateTemplate.f ()) query_fields in
+ let types_param =
+ Caqti_type.(t2 ((Encoder.CaqtiRequest.f ()) query_fields) int64)
+ in
+ let q =
+ Croquette_common.Format.format_string (fun format ->
+ Format.fprintf format "UPDATE \"%s\" SET %s WHERE ID = ?"
+ (Model.Content.id content) format_param)
+ in
+ let request =
+ Caqti_request.Infix.((types_param ->. Caqti_type.unit) ~oneshot:true) q
+ in
+ let query_param =
+ Encoder.DataToCaqtiValues.f
+ (fun name -> List.assoc name value_list)
+ query_fields
+ in
+
+ let ( let* ) = Lwt.bind in
+ let* result = Db.exec request (query_param, id) in
+ Caqti_lwt.or_fail result
+
+(** Encode a sequence of references into a type usable in Caqti request *)
+module ReferenceListEncoder = Encoder.Map (struct
+ include Encoder.DefaultEncoder
+
+ type 'a t = 'a
+ type env = (int64, Model.Reference.t) Model.Typ.t * Int64.t Seq.t ref
+
+ let f : type a. env -> a Intf.data -> a t =
+ fun (t, env) d ->
+ match !env () with
+ | Seq.Nil -> raise Not_found
+ | Cons (value, tl) -> (
+ env := tl;
+ match Model.Typ.eq t d.Intf.content_type with
+ | Some Type.Equal -> value
+ | None -> raise Encoder.TypeMismatch)
+end)
+
+module ReferencesSet = Set.Make (Int64)
+
+let update_mulivaluated_field :
+ Caqti_lwt.connection ->
+ Model.Reference.t Model.Content.t ->
+ (string * (int64, Model.Reference.t) Model.Typ.t * int64 Seq.t) list ->
+ int64 ->
+ unit Lwt.t =
+ fun db content fields id ->
+ let module Db = (val db) in
+ let ( let* ) = Lwt.bind in
+ List.fold_left
+ (fun acc (field_name, t, values) ->
+ let* () = acc in
+
+ let values = ReferencesSet.of_seq values in
+ let lvalues = ReferencesSet.to_list values in
+
+ let data_type = Intf.{ name = field_name; content_type = t } in
+
+ (* First delete all the values not belonging to the new set *)
+ let (T existing_references_t) =
+ Encoder.list_to_tup lvalues ~f:(fun ref ->
+ ignore ref;
+ Intf.(TT data_type))
+ in
+ let q_delete =
+ Croquette_common.Format.format_string (fun f ->
+ Format.fprintf f
+ "DELETE FROM \"%s.%s\" where parent=? and target not in (%s)"
+ (Model.Content.id content) field_name
+ (Encoder.EncodeParameter.f () existing_references_t))
+ in
+ let caqti_param = Encoder.CaqtiRequest.f () existing_references_t in
+ let request_delete =
+ Caqti_request.Infix.(
+ (Caqti_type.(t2 int64 caqti_param) ->. Caqti_type.unit) ~oneshot:true)
+ q_delete
+ in
+ let seq = ref (ReferencesSet.to_seq values) in
+ let* result =
+ Db.exec request_delete
+ (id, ReferenceListEncoder.f (t, seq) existing_references_t)
+ in
+ let* () = Caqti_lwt.or_fail result in
+
+ (* Then collect all the existing remaining values *)
+ let q_select =
+ Croquette_common.Format.format_string (fun f ->
+ Format.fprintf f "SELECT id FROM \"%s.%s\" WHERE parent=?"
+ (Model.Content.id content) field_name)
+ in
+ let request_select =
+ Caqti_request.Infix.(
+ (Caqti_type.int64 ->* Caqti_type.int64) ~oneshot:true)
+ q_select
+ in
+ let* request_result = Db.collect_list request_select id in
+ let* remaining' = Caqti_lwt.or_fail request_result in
+
+ (* Finaly insert the missing values.
+
+ At this step, we can just use the code from the insert module. *)
+ let remaining = ReferencesSet.(diff values (of_list remaining')) in
+ let v = Model.Typ.Seq (t, ReferencesSet.to_seq remaining) in
+ Insert.insert_references db content id field_name v data_type)
+ Lwt.return_unit fields
+
+let q :
+ Caqti_lwt.connection ->
+ Int64.t ->
+ Model.Reference.t Model.Content.t ->
+ (string -> Model.Reference.t Model.Typ.value) ->
+ unit Lwt.t =
+ fun db id content provider ->
+ let module Db = (val db) in
+ (* Get all the single fields to update in the content *)
+
+ (* There is a difference between
+
+ - Typ.None
+ - Typ.V None
+
+ The former will be ignored in the update, and the value will remains as is
+ The later will set the content to NULL in the database. *)
+ let fields, references =
+ Seq.fold_left
+ (fun ((fields, references) as acc) field ->
+ let name = Model.Field.name field in
+ let (Model.Field.T content_type) = Model.Field.type_ field in
+ let tt = Intf.TT { name; content_type } in
+ let value = provider name in
+ match value with
+ | Model.Typ.None -> acc
+ | Model.Typ.V _ as value -> ((tt, (name, value)) :: fields, references)
+ | Model.Typ.Seq (t, seq) -> (fields, (name, t, seq) :: references))
+ ([], [])
+ (Model.Content.fields content)
+ in
+ let ( let* ) = Lwt.bind in
+ let* () =
+ match fields with
+ | [] -> Lwt.return_unit
+ | _ -> update_fields db content fields id
+ in
+ let* () =
+ match references with
+ | [] -> Lwt.return_unit
+ | _ -> update_mulivaluated_field db content references id
+ in
+ Lwt.return_unit
diff --git a/lib/splay/splay.ml b/lib/splay/splay.ml
index bf0a2ac..979d017 100644
--- a/lib/splay/splay.ml
+++ b/lib/splay/splay.ml
@@ -28,40 +28,40 @@ module Make (El : KEY) = struct
let (Node (l, y, r)) = t in
begin match El.compare x (fst y) with
| 0 -> t
- | v when v < 0 -> begin
- match l with
+ | v when v < 0 ->
+ begin match l with
| Leaf -> t
- | Node (ll, z, rr) -> begin
- match El.compare x (fst z) with
+ | Node (ll, z, rr) ->
+ begin match El.compare x (fst z) with
| 0 -> Node (ll, z, Node (rr, y, r))
- | v when v < 0 -> begin
- match ll with
+ | v when v < 0 ->
+ begin match ll with
| Leaf -> Node (ll, z, Node (rr, y, r))
| Node _ as ll ->
let (Node (newL, newV, newR)) = splay x ll in
Node (newL, newV, Node (newR, z, Node (rr, y, r)))
- end
+ end
| _ -> (
match rr with
| Leaf -> Node (ll, z, Node (rr, y, r))
| Node _ as rr ->
let (Node (newL, newV, newR)) = splay x rr in
Node (Node (ll, z, newL), newV, Node (newR, y, r)))
- end
- end
+ end
+ end
| _ -> (
match r with
| Leaf -> t
| Node (ll, z, rr) -> (
match El.compare x (fst z) with
| 0 -> Node (Node (l, y, ll), z, rr)
- | v when v < 0 -> begin
- match ll with
+ | v when v < 0 ->
+ begin match ll with
| Leaf -> Node (Node (l, y, ll), z, rr)
| Node _ as ll ->
let (Node (newL, newV, newR)) = splay x ll in
Node (Node (l, y, newL), newV, Node (newR, z, rr))
- end
+ end
| _ -> (
match rr with
| Leaf -> Node (Node (l, y, ll), z, rr)
@@ -128,8 +128,8 @@ module Make (El : KEY) = struct
let root' = splay key root in
let (Node (l, c', r)) = root' in
begin match El.compare (fst c') key with
- | 0 -> begin
- match _subtree_maximum l with
+ | 0 ->
+ begin match _subtree_maximum l with
| Node (l, c, Leaf) -> T (ref (Node (l, c, r)))
| Node (_, _, _) -> raise Not_found
| Leaf -> (
@@ -137,7 +137,7 @@ module Make (El : KEY) = struct
| Leaf -> empty ()
| Node (Leaf, c, r) -> T (ref (Node (l, c, r)))
| Node (_, _, _) -> raise Not_found)
- end
+ end
(* The key is not present, return the splayed tree *)
| _ -> T (ref root')
end
@@ -155,11 +155,11 @@ module Make (El : KEY) = struct
let c = (key, value) in
(_fold [@tailcall]) ((c, Branch right) :: acc) v left
(* We have nothing left, we process the values delayed *)
- | Leaf -> begin
- match acc with
+ | Leaf ->
+ begin match acc with
| [] -> v
| (c, Branch right) :: tl -> (_fold [@tailcall]) tl (f v c) right
- end
+ end
in
_fold [] init !t
@@ -174,14 +174,14 @@ module Make (El : KEY) = struct
let pp formatter (T t) =
let leaf_id = ref 0 in
let repr_edge from formatter dest =
- Format.fprintf formatter "\"%a\" -> \"%a\"@;" El.pp from El.pp dest
+ Format.fprintf formatter "@,\"%a\" -> \"%a\"" El.pp from El.pp dest
in
let rec repr' : type b. El.t -> Format.formatter -> (b, _) branch -> unit =
fun parent formatter -> function
| Leaf ->
- Format.fprintf formatter "leaf_%d [shape=point]@;" !leaf_id;
- Format.fprintf formatter "\"%a\" -> leaf_%d@;" El.pp parent !leaf_id;
+ Format.fprintf formatter "@,leaf_%d [shape=point]" !leaf_id;
+ Format.fprintf formatter "@,\"%a\" -> leaf_%d" El.pp parent !leaf_id;
incr leaf_id
| Node (l, c, r) ->
let key = fst c in
@@ -193,6 +193,6 @@ module Make (El : KEY) = struct
| Leaf -> Format.fprintf formatter "digraph G {}"
| Node (l, c, r) ->
let key = fst c in
- Format.fprintf formatter "@[<v 2>digraph G {@;%a%a@]}" (repr' key) l
+ Format.fprintf formatter "@[<v 2>digraph G {%a%a@]@,}" (repr' key) l
(repr' key) r
end
diff --git a/lib/splay/tests/splay.t b/lib/splay/tests/splay.t
index 64f77a6..7b49803 100644
--- a/lib/splay/tests/splay.t
+++ b/lib/splay/tests/splay.t
@@ -1,8 +1,18 @@
-Tests for the splay tree. The tree representation used in the tests follow the
-dot syntax
+Tests for the splay tree.
See https://en.wikipedia.org/wiki/Splay_tree
+The test build a splay tree with the node given as argument, then display the
+representation using the dot syntax.
+
+ $ tests --splay_tree \
+ > --help
+ Start the tests
+ --add Add an element in the tree
+ --del Remove an element from the tree
+ --get Get an element from the tree
+ -help Display this list of options
+ --help Display this list of options
The root is the latest inserted node:
@@ -17,7 +27,7 @@ The root is the latest inserted node:
"5" -> leaf_1
leaf_2 [shape=point]
"5" -> leaf_2
- }
+ }
$ tests --splay_tree \
> --add 3 \
@@ -30,7 +40,7 @@ The root is the latest inserted node:
"3" -> leaf_1
leaf_2 [shape=point]
"5" -> leaf_2
- }
+ }
Collecting an element in the tree will push this node at the root:
@@ -50,7 +60,7 @@ Collecting an element in the tree will push this node at the root:
"3" -> leaf_2
leaf_3 [shape=point]
"3" -> leaf_3
- }
+ }
$ tests --splay_tree \
> --add 1 \
@@ -72,7 +82,7 @@ Collecting an element in the tree will push this node at the root:
"4" -> leaf_3
leaf_4 [shape=point]
"4" -> leaf_4
- }
+ }
Removing an element from the tree modify the structure
@@ -89,5 +99,5 @@ Removing an element from the tree modify the structure
"3" -> leaf_1
leaf_2 [shape=point]
"3" -> leaf_2
- }
+ }
diff --git a/test/common.ml b/test/common.ml
index 807289a..f06d431 100644
--- a/test/common.ml
+++ b/test/common.ml
@@ -11,3 +11,89 @@ let connect : Configuration.Ast.setting -> Caqti_lwt.connection Lwt.t =
let module Db = (val db) in
let* () = Query.create db conf in
Lwt.return db
+
+(** Load the given content and return the values as a json *)
+let content_as_json :
+ 'a Model.Content.t -> (int64, string, [ `One ]) Caqti_request.t =
+ fun content ->
+ let fields =
+ Model.Content.fields content
+ (* Remove the multivaluated fields from the query *)
+ |> Seq.filter (fun t ->
+ let (Model.Field.T ty) = Model.Field.type_ t in
+ match ty with Model.Typ.MultiReference _ -> false | _ -> true)
+ in
+ let buff = Buffer.create 64 in
+ let () =
+ Seq.iter
+ (fun field ->
+ Buffer.add_char buff '\'';
+ Buffer.add_string buff (Model.Field.name field);
+
+ Buffer.add_string buff "',";
+ Buffer.add_string buff (Model.Field.name field);
+ Buffer.add_string buff ",")
+ fields
+ in
+
+ let () =
+ match Model.Content.parent content with
+ | None ->
+ let length = Buffer.length buff in
+ if length > 1 then Buffer.truncate buff (length - 1);
+ ()
+ | Some _ -> Buffer.add_string buff "'parent',parent"
+ in
+
+ let q = Buffer.contents buff in
+ Caqti_request.Infix.(Caqti_type.(int64) ->! Caqti_type.string)
+ ~oneshot:true
+ ("SELECT json_object(" ^ q ^ ") from " ^ Model.Content.id content
+ ^ " where id=?")
+
+let query_values (table : Model.Reference.t Model.Content.t) (feature : string)
+ =
+ Caqti_request.Infix.(Caqti_type.(int64) ->* Caqti_type.string)
+ ~oneshot:true
+ ("SELECT json_object('" ^ feature ^ "', target) from \""
+ ^ Model.Content.id table ^ "." ^ feature ^ "\" where parent=?")
+
+(** Query all the multireferences tables for the given content and the given id.
+ Collect all the values and return them in the same json format as the same
+ content. *)
+let collect_references :
+ Caqti_lwt.connection ->
+ Model.Reference.t Model.Content.t ->
+ int64 ->
+ (string * int64 * string) list Lwt.t =
+ fun db content id ->
+ let module Db = (val db) in
+ let ( let* ) = Lwt.bind in
+ let content_id = Model.Content.id content in
+
+ (* Only keep the multivaluated fields *)
+ let fields =
+ Seq.filter
+ (fun field ->
+ let (T ty) = Model.Field.type_ field in
+ match ty with Model.Typ.MultiReference _ -> true | _ -> false)
+ (Model.Content.fields content)
+ |> List.of_seq
+ in
+ let results =
+ Lwt_list.fold_left_s
+ (fun acc field ->
+ let field_name = Model.Field.name field in
+ let* json_result =
+ Db.collect_list (query_values content field_name) id
+ in
+ let* json = Caqti_lwt.or_fail json_result in
+ let line =
+ ListLabels.fold_left ~init:acc json ~f:(fun acc json ->
+ (content_id, id, json) :: acc)
+ in
+ Lwt.return line)
+ [] fields
+ in
+
+ results
diff --git a/test/configuration_.ml b/test/configuration_.ml
index 0cc01da..a5079c3 100644
--- a/test/configuration_.ml
+++ b/test/configuration_.ml
@@ -2,7 +2,7 @@ let name = "configuration"
let description = "Load the configuration file and report errors"
let printer = ref (fun formatter _ -> Format.pp_print_nothing formatter ())
-let speclist =
+let speclist () =
[
( "--tree",
Arg.Unit
diff --git a/test/dune b/test/dune
index 51fa57a..cead409 100644
--- a/test/dune
+++ b/test/dune
@@ -13,6 +13,7 @@
caqti-driver-sqlite3
decoders
uri
+ croquette_common
splay
configuration
model
diff --git a/test/hash.ml b/test/hash.ml
index 83f7d5c..c91280b 100644
--- a/test/hash.ml
+++ b/test/hash.ml
@@ -4,7 +4,7 @@
let name = __FILE__
let description = "Print the hash of the configuration"
-let speclist = []
+let speclist () = []
type t = (int, Configuration.Read_conf.error) result
diff --git a/test/insert.ml b/test/insert.ml
index 70b98d6..bc65422 100644
--- a/test/insert.ml
+++ b/test/insert.ml
@@ -2,7 +2,7 @@ open StdLabels
let name = __FILE__
let description = "Insert data and check the result"
-let speclist = []
+let speclist () = []
type t =
((string * Int64.t * string) list, Configuration.Read_conf.error) result
@@ -14,53 +14,7 @@ let pp : Format.formatter -> t -> unit =
(fun formatter (content_id, id, content) ->
Format.fprintf formatter "@[<v 2>%s:%Ld@;%s@]" content_id id content))
-let query_columns : 'a Model.Content.t -> string =
- fun content ->
- let fields =
- Model.Content.fields content
- (* Remove the multivaluated fields from the query *)
- |> Seq.filter (fun t ->
- let (Model.Field.T ty) = Model.Field.type_ t in
- match ty with Model.Typ.MultiReference _ -> false | _ -> true)
- in
- let buff = Buffer.create 64 in
- let () =
- Seq.iter
- (fun field ->
- Buffer.add_char buff '\'';
- Buffer.add_string buff (Model.Field.name field);
-
- Buffer.add_string buff "',";
- Buffer.add_string buff (Model.Field.name field);
- Buffer.add_string buff ",")
- fields
- in
-
- let () =
- match Model.Content.parent content with
- | None ->
- let length = Buffer.length buff in
- if length > 1 then Buffer.truncate buff (length - 1);
- ()
- | Some _ -> Buffer.add_string buff "'parent',parent"
- in
-
- Buffer.contents buff
-
type content = Model.Reference.t Model.Content.t
-
-let query (table : content) =
- Caqti_request.Infix.(Caqti_type.(int64) ->! Caqti_type.string)
- ~oneshot:true
- ("SELECT json_object(" ^ query_columns table ^ ") from "
- ^ Model.Content.id table ^ " where id=?")
-
-let query_values (table : content) (feature : string) =
- Caqti_request.Infix.(Caqti_type.(int64) ->* Caqti_type.string)
- ~oneshot:true
- ("SELECT json_object('" ^ feature ^ "', target) from \""
- ^ Model.Content.id table ^ "." ^ feature ^ "\" where parent=?")
-
type value = Model.Reference.t Model.Typ.value
type properties = (string * value) list
@@ -83,7 +37,7 @@ let insert_and_get_result :
in
let content_id = Model.Content.id content in
let module Db = (val db) in
- let* json_result = Db.find (query content) id in
+ let* json_result = Db.find (Common.content_as_json content) id in
let* json = Caqti_lwt.or_fail json_result in
Lwt.return (content_id, id, json)
@@ -258,43 +212,6 @@ end
module D = Make (Configuration.Json5.Decode)
-(** Query all the multireferences tables for the given content and the given id.
- Collect all the values and return them in the same json format as the same
- content. *)
-let collect_references :
- Caqti_lwt.connection -> content -> int64 -> 'a list Lwt.t =
- fun db content id ->
- let module Db = (val db) in
- let ( let* ) = Lwt.bind in
- let content_id = Model.Content.id content in
-
- (* Only keep the multivaluated fields *)
- let fields =
- Seq.filter
- (fun field ->
- let (T ty) = Model.Field.type_ field in
- match ty with Model.Typ.MultiReference _ -> true | _ -> false)
- (Model.Content.fields content)
- |> List.of_seq
- in
- let results =
- Lwt_list.fold_left_s
- (fun acc field ->
- let field_name = Model.Field.name field in
- let* json_result =
- Db.collect_list (query_values content field_name) id
- in
- let* json = Caqti_lwt.or_fail json_result in
- let line =
- List.fold_left ~init:acc json ~f:(fun acc json ->
- (content_id, id, json) :: acc)
- in
- Lwt.return line)
- [] fields
- in
-
- results
-
let exec : string list -> t =
fun _ ->
let stdin = In_channel.input_all stdin in
@@ -324,7 +241,7 @@ let exec : string list -> t =
let acc = (content_id, id, json) :: acc in
(* Also query the multivaluated references *)
- let* ext = collect_references db content id in
+ let* ext = Common.collect_references db content id in
let acc = List.append ext acc in
(* Insert the subcontent associated *)
Lwt_list.fold_left_s
@@ -339,7 +256,9 @@ let exec : string list -> t =
let acc = (subcontent_id, id, json) :: acc in
(* Also query the multivaluated references *)
- let* ext = collect_references db subcontent id in
+ let* ext =
+ Common.collect_references db subcontent id
+ in
let acc = List.append ext acc in
Lwt.return acc)
acc entries
diff --git a/test/intf.ml b/test/intf.ml
index a68fa88..5012ba2 100644
--- a/test/intf.ml
+++ b/test/intf.ml
@@ -2,8 +2,12 @@ module type T = sig
type t
val exec : string list -> t
+ (** [exec args] execute the test.
+
+ [args] is the list of the anonymous arguments given in the command line *)
+
val pp : Format.formatter -> t -> unit
- val speclist : (string * Arg.spec * string) list
+ val speclist : unit -> (string * Arg.spec * string) list
val name : string
val description : string
end
diff --git a/test/parent.ml b/test/parent.ml
index a13afda..232de34 100644
--- a/test/parent.ml
+++ b/test/parent.ml
@@ -6,7 +6,7 @@ let description =
let parent = ref Model.Content.parent
-let speclist =
+let speclist () =
[
( "--root",
Arg.Unit
diff --git a/test/schema.ml b/test/schema.ml
index 0dc386d..b063270 100644
--- a/test/schema.ml
+++ b/test/schema.ml
@@ -1,6 +1,6 @@
let name = __FILE__
let description = "Print the schema for the given tables"
-let speclist = []
+let speclist () = []
type t = (string list, Configuration.Read_conf.error) result
diff --git a/test/splay_tree.ml b/test/splay_tree.ml
index acd2f2b..7a9d2f7 100644
--- a/test/splay_tree.ml
+++ b/test/splay_tree.ml
@@ -12,7 +12,7 @@ type t = unit T.t
let pp : Format.formatter -> t -> unit = T.pp
let tree : unit T.t ref = ref (T.empty ())
-let speclist =
+let speclist () =
[
( "--add",
Arg.Int (fun n -> tree := T.add n () !tree),
diff --git a/test/tests.ml b/test/tests.ml
index 9242495..d396ac0 100644
--- a/test/tests.ml
+++ b/test/tests.ml
@@ -18,7 +18,7 @@ let register : (module Intf.T) -> string * Arg.spec * string =
( "--" ^ name,
Arg.Unit
(fun () ->
- speclist := T.speclist;
+ speclist := T.speclist ();
submodule := Some (module T : Intf.T)),
T.description )
@@ -34,6 +34,7 @@ let () =
register (module Hash);
register (module Configuration_);
register (module Insert);
+ register (module Update);
]
let args = ref []
diff --git a/test/update.ml b/test/update.ml
new file mode 100644
index 0000000..1e94fc2
--- /dev/null
+++ b/test/update.ml
@@ -0,0 +1,207 @@
+let name = __FILE__
+let description = "Update a content"
+
+type actions =
+ | Commit
+ | Unset of string
+ | Text of string * string
+ | Integer of string * int
+ | Reference of Model.Reference.t Model.Typ.reference * string * int
+ | References of Model.Reference.t Model.Typ.reference * string * int64 Seq.t
+
+let actions : actions list ref = ref []
+
+type t = string list
+
+let pp : Format.formatter -> t -> unit = Format.(pp_print_list pp_print_string)
+
+let configuration =
+ lazy
+ (let model =
+ {|
+ {
+ "content": [
+ {
+ "id": "entity",
+ "section": [
+ {
+ "field": [
+ {
+ "name": "references",
+ "label": {},
+ "type": {
+ "content": "entity",
+ "multivaluated": true
+ }
+ },
+ {
+ "name": "reference",
+ "label": {},
+ "type": {
+ "content": "entity",
+ "multivaluated": false
+ }
+ },
+ {
+ "name": "integer",
+ "label": {},
+ "type": "integer"
+ },
+ {
+ "name": "text",
+ "label": {},
+ "type": "text"
+ },
+ ]
+ }
+ ]
+ }
+ ]
+ }|}
+ in
+ Configuration.Read_conf.read_string_conf model
+ |> Result.map_error (fun e ->
+ Croquette_common.Format.format_string (fun fmt ->
+ Configuration.Read_conf.pp_error fmt e))
+ |> Result.get_ok')
+
+let speclist () =
+ let (lazy configuration) = configuration in
+ let content = Configuration.Ast.get_content configuration "entity" in
+ let fields = Model.Content.fields (Option.get content) in
+ Seq.fold_left
+ (fun acc feature ->
+ let key = "--" ^ Model.Field.name feature in
+ let (Model.Field.T type_) = Model.Field.type_ feature in
+ let argument =
+ match type_ with
+ | Model.Typ.Text ->
+ Some
+ ( key,
+ Arg.String
+ (fun value ->
+ actions :=
+ Text (Model.Field.name feature, value) :: !actions),
+ "<v> Set field with the value <v>" )
+ | Model.Typ.Integer ->
+ Some
+ ( key,
+ Arg.Int
+ (fun value ->
+ actions :=
+ Integer (Model.Field.name feature, value) :: !actions),
+ "<n> Set field with the value <n>" )
+ | Model.Typ.MonoReference target ->
+ Some
+ ( key,
+ Arg.Int
+ (fun value ->
+ actions :=
+ Reference (target, Model.Field.name feature, value)
+ :: !actions),
+ "<id> Set field with the id" )
+ | Model.Typ.MultiReference target ->
+ Some
+ ( key,
+ Arg.String
+ (fun value ->
+ let ids =
+ String.split_on_char ',' value
+ |> List.map (fun v -> Int64.of_string (String.trim v))
+ |> List.to_seq
+ in
+
+ actions :=
+ References (target, Model.Field.name feature, ids)
+ :: !actions),
+ "<id,..> Set this list of values" )
+ in
+
+ match argument with None -> acc | Some v -> v :: acc)
+ [
+ ( "--commit",
+ Arg.Unit (fun () -> actions := Commit :: !actions),
+ "\tCommit this group of update" );
+ ( "--clear",
+ Arg.String (fun feature -> actions := Unset feature :: !actions),
+ "<f> Clear the field <f>" );
+ ]
+ fields
+ |> Arg.align
+
+let exec : string list -> t =
+ fun _ ->
+ let (lazy configuration) = configuration in
+ let content =
+ Configuration.Ast.get_content configuration "entity" |> Option.get
+ in
+
+ Lwt_main.run
+ (let ( let* ) = Lwt.bind in
+ let* db = Common.connect configuration in
+ let module Db = (val db) in
+ (* Insert a content without any value *)
+ let* id = Query.insert db content (fun _ -> Model.Typ.None) in
+
+ let group_commit : actions Seq.t Seq.t =
+ List.rev !actions |> List.to_seq
+ |> Seq.group (fun a b ->
+ match (a, b) with _, Commit -> false | _ -> true)
+ in
+ (* Update the values from the argument in the command line *)
+ let* printers =
+ Seq.fold_left
+ (fun acc actions ->
+ let* acc = acc in
+ let* () =
+ Query.update db id content (fun key ->
+ let value =
+ Seq.find_map
+ (function
+ | Unset k when String.equal k key ->
+ let field =
+ Model.Content.fields content
+ |> Seq.find (fun f ->
+ String.equal key (Model.Field.name f))
+ |> Option.get
+ in
+ let (Model.Field.T t) = Model.Field.type_ field in
+ begin match t with
+ | Model.Typ.MultiReference _ as e ->
+ Some Model.Typ.(Seq (e, Seq.empty))
+ | Integer as e -> Some Model.Typ.(V (e, None))
+ | Text as e -> Some Model.Typ.(V (e, None))
+ | MonoReference _ as e ->
+ Some Model.Typ.(V (e, None))
+ end
+ | Text (k, v) when String.equal k key ->
+ Some Model.Typ.(V (Text, Some v))
+ | Integer (k, v) when String.equal k key ->
+ Some Model.Typ.(V (Integer, Some (Int64.of_int v)))
+ | Reference (target, k, v) when String.equal k key ->
+ Some
+ Model.Typ.(
+ V (MonoReference target, Some (Int64.of_int v)))
+ | References (target, k, v) when String.equal k key ->
+ Some Model.Typ.(Seq (MultiReference target, v))
+ | _ -> None)
+ actions
+ in
+ match value with Some v -> v | None -> Model.Typ.None)
+ in
+ (* Get the values from the content registered in the database *)
+ let* json_result = Db.find (Common.content_as_json content) id in
+ let* json = Caqti_lwt.or_fail json_result in
+
+ (* Also query for the referenoces *)
+ let* refs = Common.collect_references db content id in
+ let acc =
+ List.fold_left
+ (fun acc (_, _, ref) -> ref :: acc)
+ (json :: acc) (List.rev refs)
+ in
+
+ Lwt.return acc)
+ (Lwt.return []) group_commit
+ in
+ Lwt.return (List.rev printers))