summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--lib/common/sql.ml8
-rw-r--r--lib/configuration/ast.ml21
-rw-r--r--lib/configuration/ast.mli9
-rw-r--r--lib/configuration/graph_tree.ml14
-rw-r--r--lib/configuration/read_conf.ml48
-rw-r--r--lib/configuration/tests/errors.t98
-rw-r--r--lib/model/content.ml7
-rw-r--r--lib/model/content.mli4
-rw-r--r--lib/model/field.ml6
-rw-r--r--lib/model/field.mli4
-rw-r--r--lib/model/identifier.ml35
-rw-r--r--lib/model/identifier.mli49
-rw-r--r--lib/model/tests/identifier.t38
-rw-r--r--lib/query/create.ml89
-rw-r--r--lib/query/encoder.ml13
-rw-r--r--lib/query/insert.ml26
-rw-r--r--lib/query/insert.mli2
-rw-r--r--lib/query/intf.ml2
-rw-r--r--lib/query/tests/create.t9
-rw-r--r--lib/query/update.ml42
-rw-r--r--test/common.ml33
-rw-r--r--test/identifier.ml42
-rw-r--r--test/insert.ml6
-rw-r--r--test/parent.ml5
-rw-r--r--test/tests.ml1
-rw-r--r--test/update.ml16
26 files changed, 476 insertions, 151 deletions
diff --git a/lib/common/sql.ml b/lib/common/sql.ml
new file mode 100644
index 0000000..1c0e2bb
--- /dev/null
+++ b/lib/common/sql.ml
@@ -0,0 +1,8 @@
+(** Helper to embed an SQL string literal into a query string.
+
+ Identifiers are not handled here: they have the abstract type
+ [Model.Identifier.t], whose only constructor validates the string, and are
+ quoted with [Model.Identifier.quote]. *)
+
+let quote_literal : string -> string =
+ fun s -> "'" ^ String.concat "''" (String.split_on_char '\'' s) ^ "'"
diff --git a/lib/configuration/ast.ml b/lib/configuration/ast.ml
index 36ba349..d874428 100644
--- a/lib/configuration/ast.ml
+++ b/lib/configuration/ast.ml
@@ -1,10 +1,6 @@
open StdLabels
-module Splay = Splay.Make (struct
- include String
-
- let pp = Format.pp_print_string
-end)
+module Splay = Splay.Make (Model.Identifier)
let escaped = String.escaped
@@ -18,19 +14,19 @@ type setting = {
let init : unit -> setting = fun () -> { contents = Splay.empty (); lists = [] }
(** Get the content from the setting. *)
-let get_content : setting -> string -> Model.Reference.t Model.Content.t option
- =
+let get_content :
+ setting -> Model.Identifier.t -> Model.Reference.t Model.Content.t option =
fun settings name -> Splay.find name settings.contents
-exception BrokenLink : ('a Type.Id.t * 'a * string) -> exn
-exception NotImplemented : ('a Type.Id.t * 'a * string) -> exn
+exception BrokenLink : ('a Type.Id.t * 'a * Model.Identifier.t) -> exn
+exception NotImplemented : ('a Type.Id.t * 'a * Model.Identifier.t) -> exn
(** Convert the content having fields referencing element by name into content
having fields referencing other contents *)
let rec convert :
'a Type.Id.t ->
setting ->
- ('a * string) Model.Content.t ->
+ ('a * Model.Identifier.t) Model.Content.t ->
Model.Reference.t Model.Content.t =
fun ty setting content ->
let subcontents =
@@ -56,7 +52,8 @@ let rec convert :
(* Also check from the list catalog *)
begin match
List.find_opt setting.lists ~f:(fun { id; _ } ->
- String.equal id name)
+ String.equal id
+ (Model.Identifier.to_string name))
with
| Some v ->
ignore v;
@@ -77,7 +74,7 @@ let rec convert :
giving the possibility to fetch any content or subcontent by is’s name
without traversing the whole tree each time. *)
let register_content :
- 'a Type.Id.t -> setting -> ('a * string) Model.Content.t -> unit =
+ 'a Type.Id.t -> setting -> ('a * Model.Identifier.t) Model.Content.t -> unit =
fun ty setting content ->
let rec traverse content =
let () =
diff --git a/lib/configuration/ast.mli b/lib/configuration/ast.mli
index 9fba7f6..33d9bc8 100644
--- a/lib/configuration/ast.mli
+++ b/lib/configuration/ast.mli
@@ -3,7 +3,8 @@ type list' = { id : string; source : string }
val init : unit -> setting
-val get_content : setting -> string -> Model.Reference.t Model.Content.t option
+val get_content :
+ setting -> Model.Identifier.t -> Model.Reference.t Model.Content.t option
(** Get the content from the setting. *)
val root_contents : setting -> Model.Reference.t Model.Content.t list
@@ -12,16 +13,16 @@ val root_contents : setting -> Model.Reference.t Model.Content.t list
Only the root content are repored in the list *)
val register_content :
- 'a Type.Id.t -> setting -> ('a * string) Model.Content.t -> unit
+ 'a Type.Id.t -> setting -> ('a * Model.Identifier.t) Model.Content.t -> unit
(** Register a content and all the associated subcontent in the top level,
giving the possibility to fetch any content or subcontent by is’s name
without traversing the whole tree each time. *)
-exception BrokenLink : ('a Type.Id.t * 'a * string) -> exn
+exception BrokenLink : ('a Type.Id.t * 'a * Model.Identifier.t) -> exn
(** Exception raised when a reference in the configuration targets a
non-existing content *)
-exception NotImplemented : ('a Type.Id.t * 'a * string) -> exn
+exception NotImplemented : ('a Type.Id.t * 'a * Model.Identifier.t) -> exn
val register_list : setting -> list' -> setting
diff --git a/lib/configuration/graph_tree.ml b/lib/configuration/graph_tree.ml
index 25c9366..240c1c9 100644
--- a/lib/configuration/graph_tree.ml
+++ b/lib/configuration/graph_tree.ml
@@ -9,9 +9,13 @@
module Vertex = struct
type t = Model.Reference.t Model.Content.t
- let compare t1 t2 = String.compare (Model.Content.id t1) (Model.Content.id t2)
- let equal t1 t2 = String.equal (Model.Content.id t1) (Model.Content.id t2)
- let hash t = Hashtbl.hash (Model.Content.id t)
+ let compare t1 t2 =
+ Model.Identifier.compare (Model.Content.id t1) (Model.Content.id t2)
+
+ let equal t1 t2 =
+ Model.Identifier.equal (Model.Content.id t1) (Model.Content.id t2)
+
+ let hash t = Model.Identifier.hash (Model.Content.id t)
end
module Edge = struct
@@ -20,7 +24,7 @@ module Edge = struct
let compare e1 e2 =
match (e1, e2) with
| Field f1, Field f2 ->
- String.compare (Model.Field.name f1) (Model.Field.name f2)
+ Model.Identifier.compare (Model.Field.name f1) (Model.Field.name f2)
| Default, Default -> 0
| _, _ -> Stdlib.compare e1 e2
@@ -33,7 +37,7 @@ module GV_Printer = Graph.Graphviz.Dot (struct
include G
let graph_attributes _ = []
- let vertex_name v = Model.Content.id v
+ let vertex_name v = Model.Identifier.to_string (Model.Content.id v)
let vertex_attributes _ = []
let default_vertex_attributes _ = []
let edge_attributes _ = []
diff --git a/lib/configuration/read_conf.ml b/lib/configuration/read_conf.ml
index 66cd1fe..4150295 100644
--- a/lib/configuration/read_conf.ml
+++ b/lib/configuration/read_conf.ml
@@ -7,10 +7,12 @@ module Make (S : Decoders.Decode.S) = struct
(** Recursive type declaring a content and the subcontents *)
type declared_content =
| C of
- string * (S.value * string) Model.Section.t list * declared_content list
+ Model.Identifier.t
+ * (S.value * Model.Identifier.t) Model.Section.t list
+ * declared_content list
let rec content_builder :
- declared_content -> (S.value * string) Model.Content.t =
+ declared_content -> (S.value * Model.Identifier.t) Model.Content.t =
fun c ->
let (C (content_id, sections, declared_subcontents)) = c in
let children = List.map declared_subcontents ~f:content_builder in
@@ -31,8 +33,17 @@ module Make (S : Decoders.Decode.S) = struct
let dsl = Parser.ExpressionParser.of_string content in
Result.map_error Decoders.Error.make dsl |> S.from_result
- let field_type : (S.value * string) Model.Field.field_ex S.decoder =
- let text_type : (S.value * string) Model.Field.field_ex S.decoder =
+ let identifier : Model.Identifier.t S.decoder =
+ let* id = S.string in
+ if String.equal String.empty id then
+ S.fail "Expected a non empty identifier"
+ else
+ match Model.Identifier.of_string_opt id with
+ | Some id -> S.succeed id
+ | None -> S.fail "Expected an identifier with only the accepted characters"
+
+ let field_type : (S.value * Model.Identifier.t) Model.Field.field_ex S.decoder =
+ let text_type : (S.value * Model.Identifier.t) Model.Field.field_ex S.decoder =
S.and_then
(fun value ->
match String.lowercase_ascii value with
@@ -40,8 +51,8 @@ module Make (S : Decoders.Decode.S) = struct
| "integer" -> S.succeed (Model.Field.T Integer)
| other -> S.fail other)
S.string
- and content : (S.value * string) Model.Field.field_ex S.decoder =
- let* content_t = keep @@ S.field "content" S.string
+ and content : (S.value * Model.Identifier.t) Model.Field.field_ex S.decoder =
+ let* content_t = keep @@ S.field "content" identifier
and* multivaluated = S.field_opt_or ~default:false "multivaluated" S.bool
and* constraints = S.field_opt "constraints" dsl in
@@ -62,8 +73,8 @@ module Make (S : Decoders.Decode.S) = struct
let* rule = S.field "rule" dsl and* message = S.field "message" textI18n in
S.succeed Model.Field.{ rule; message }
- let field : (S.value * string) Model.Field.t S.decoder =
- let* name = S.field "name" S.string
+ let field : (S.value * Model.Identifier.t) Model.Field.t S.decoder =
+ let* name = S.field "name" identifier
and* label = S.field "label" textI18n
and* type' = S.field "type" field_type
and* required = S.field_opt_or ~default:false "required" S.bool
@@ -76,22 +87,14 @@ module Make (S : Decoders.Decode.S) = struct
(Model.Field.create type' label ~required ?placeholder ~validation
?criteria ?icon name)
- let section : (S.value * string) Model.Section.t S.decoder =
+ let section : (S.value * Model.Identifier.t) Model.Section.t S.decoder =
let* label = S.field_opt_or ~default:[] "label" textI18n
and* criteria = S.field_opt "criteria" dsl
and* fields = S.field "field" (S.list field) in
let icon = None in
S.succeed Model.Section.{ label; criteria; fields; icon }
- let identifier : string S.decoder =
- let* id = S.string in
- if String.equal String.empty id then
- S.fail "Expected a non empty identifier"
- else if String.contains id '.' then
- S.fail "Expected an identifier with only the accepted characters"
- else S.succeed id
-
- let content : (S.value * string) Model.Content.t S.decoder =
+ let content : (S.value * Model.Identifier.t) Model.Content.t S.decoder =
(* Build a temporary type without the parent information *)
let* c =
S.fix (fun content_decoder ->
@@ -130,7 +133,7 @@ module Make (S : Decoders.Decode.S) = struct
| None -> raise e
| Some Type.Equal ->
let message =
- "Undefined target \"" ^ name
+ "Undefined target \"" ^ Model.Identifier.to_string name
^ "\". Expected existing list or content"
in
S.fail_with (Decoders.Error.make ~context message))
@@ -139,12 +142,15 @@ module Make (S : Decoders.Decode.S) = struct
| None -> raise e
| Some Type.Equal ->
let message =
- "Unsupported target \"" ^ name
+ "Unsupported target \"" ^ Model.Identifier.to_string name
^ "\". Lists as target are not implemented yet"
in
S.fail_with (Decoders.Error.make ~context message))
| Error (Graph_tree.Cycle contents) ->
- let content_name = List.map contents ~f:(fun c -> Model.Content.id c) in
+ let content_name =
+ List.map contents ~f:(fun c ->
+ Model.Identifier.to_string (Model.Content.id c))
+ in
let message =
String.concat ~sep:" "
("Dependency circle found between:" :: content_name)
diff --git a/lib/configuration/tests/errors.t b/lib/configuration/tests/errors.t
index 58c15ed..bad5b3b 100644
--- a/lib/configuration/tests/errors.t
+++ b/lib/configuration/tests/errors.t
@@ -117,3 +117,101 @@ Cycles between required content are not accepted
> ]
> }
Dependency circle found between: entity user
+
+Identifiers are validated when the configuration is parsed: characters
+outside letters, digits and underscore are rejected (a double quote could
+otherwise break out of the quoted SQL identifiers):
+
+ $ tests --configuration <<EOF
+ > {
+ > "content": [
+ > {
+ > "id": "evil\"; DROP TABLE entity;--"
+ > }
+ > ]
+ > }
+ > EOF
+ in field "content":
+ while decoding a list:
+ element 0:
+ in field "id":
+ Expected an identifier with only the accepted characters, but got
+ "evil\"; DROP TABLE entity;--"
+
+Field names are validated the same way:
+
+ $ tests --configuration <<EOF
+ > {
+ > "content": [
+ > {
+ > "id": "entity",
+ > "section": [
+ > {
+ > "field": [
+ > {
+ > "name": "bad\"name",
+ > "label": {},
+ > "type": "text"
+ > }
+ > ]
+ > }
+ > ]
+ > }
+ > ]
+ > }
+ > EOF
+ in field "content":
+ while decoding a list:
+ element 0:
+ in field "section":
+ while decoding a list:
+ element 0:
+ in field "field":
+ while decoding a list:
+ element 0:
+ in field "name":
+ Expected an identifier with only the accepted characters, but got
+ "bad\"name"
+
+Reference targets are validated the same way:
+
+ $ tests --configuration <<EOF
+ > {
+ > "content": [
+ > {
+ > "id": "entity",
+ > "section": [
+ > {
+ > "field": [
+ > {
+ > "name": "ref",
+ > "label": {},
+ > "type": {
+ > "content": "bad\"target"
+ > }
+ > }
+ > ]
+ > }
+ > ]
+ > }
+ > ]
+ > }
+ > EOF
+ in field "content":
+ while decoding a list:
+ element 0:
+ in field "section":
+ while decoding a list:
+ element 0:
+ in field "field":
+ while decoding a list:
+ element 0:
+ in field "type":
+ I tried the following decoders but they all failed:
+ "text" decoder:
+ Expected a string, but got
+ { "content": "bad\"target" }
+ "content" decoder:
+ in field "content":
+ Expected an identifier with only the accepted characters, but got
+ "bad\"target"
diff --git a/lib/model/content.ml b/lib/model/content.ml
index 4fe8e92..7b9d9a4 100644
--- a/lib/model/content.ml
+++ b/lib/model/content.ml
@@ -1,13 +1,13 @@
open StdLabels
type 'a t = {
- id : string;
+ id : Identifier.t;
sections : 'a Section.t list;
subcontents : 'a t list;
parent : 'a t Weak.t;
}
-let v : string -> 'a Section.t list -> 'a t list -> 'a t =
+let v : Identifier.t -> 'a Section.t list -> 'a t list -> 'a t =
fun id sections subcontents ->
let parent = Weak.create 1 in
let content = { id; sections; subcontents; parent } in
@@ -32,7 +32,8 @@ let fields : 'a t -> 'a Field.t Seq.t =
let find_target : 'a t -> string -> 'a option =
fun t name ->
let feature_opt =
- Seq.find (fun f -> String.equal (Field.name f) name) (fields t)
+ Seq.find (fun f -> String.equal (Identifier.to_string (Field.name f)) name)
+ (fields t)
in
let ( let* ) = Option.bind in
diff --git a/lib/model/content.mli b/lib/model/content.mli
index e972b83..7f0e2cb 100644
--- a/lib/model/content.mli
+++ b/lib/model/content.mli
@@ -1,7 +1,7 @@
type 'a t
-val v : string -> 'a Section.t list -> 'a t list -> 'a t
-val id : _ t -> string
+val v : Identifier.t -> 'a Section.t list -> 'a t list -> 'a t
+val id : _ t -> Identifier.t
val subcontents : 'a t -> 'a t list
(** Return the direct subcontent *)
diff --git a/lib/model/field.ml b/lib/model/field.ml
index 8ea38fd..c7e4667 100644
--- a/lib/model/field.ml
+++ b/lib/model/field.ml
@@ -5,7 +5,7 @@ type validation = { rule : string list Dsl.t; message : textI18n }
type 't field_ex = T : ('a, 't) Typ.t -> 't field_ex
type 't t = {
- name : string; (** The internal name *)
+ name : Identifier.t; (** The internal name *)
label : textI18n;
placeholder : textI18n option;
icon : unit option;
@@ -16,7 +16,7 @@ type 't t = {
(** Display the field when the criteria is valid *)
}
-let name : 'ref t -> string = fun t -> t.name
+let name : 'ref t -> Identifier.t = fun t -> t.name
let label : 'ref t -> textI18n = fun t -> t.label
let placeholder : 'ref t -> textI18n option = fun t -> t.placeholder
let icon : 'ref t -> unit option = fun t -> t.icon
@@ -33,7 +33,7 @@ let create :
?required:bool ->
?validation:validation list ->
?criteria:string list Dsl.t ->
- string ->
+ Identifier.t ->
't t =
fun type_ label ?placeholder ?icon ?(required = false) ?(validation = [])
?criteria name ->
diff --git a/lib/model/field.mli b/lib/model/field.mli
index 8e1432a..0bcb209 100644
--- a/lib/model/field.mli
+++ b/lib/model/field.mli
@@ -15,10 +15,10 @@ val create :
?required:bool ->
?validation:validation list ->
?criteria:string list Dsl.t ->
- string ->
+ Identifier.t ->
'ref t
-val name : _ t -> string
+val name : _ t -> Identifier.t
(** Name (identifier) for the field *)
val label : _ t -> textI18n
diff --git a/lib/model/identifier.ml b/lib/model/identifier.ml
new file mode 100644
index 0000000..f1a981e
--- /dev/null
+++ b/lib/model/identifier.ml
@@ -0,0 +1,35 @@
+type t = string
+
+exception Invalid of string
+
+let is_valid : string -> bool =
+ fun id ->
+ id <> ""
+ && String.for_all
+ (fun c ->
+ (c >= 'a' && c <= 'z')
+ || (c >= 'A' && c <= 'Z')
+ || (c >= '0' && c <= '9')
+ || c = '_' || c = '-')
+ id
+
+let of_string_opt : string -> t option =
+ fun id -> if is_valid id then Some id else None
+
+let of_string : string -> t =
+ fun id ->
+ match of_string_opt id with Some id -> id | None -> raise (Invalid id)
+
+let to_string : t -> string = fun id -> id
+
+(** The fixed columns of the generated schema, predefined so that the SQL
+ generation can refer to them directly. *)
+let id : t = of_string "id"
+let parent : t = of_string "parent"
+let target : t = of_string "target"
+let quote : t -> string = fun id -> "\"" ^ id ^ "\""
+let dot : t -> t -> t = fun a b -> a ^ "." ^ b
+let equal : t -> t -> bool = String.equal
+let compare : t -> t -> int = String.compare
+let hash : t -> int = Hashtbl.hash
+let pp : Format.formatter -> t -> unit = Format.pp_print_string
diff --git a/lib/model/identifier.mli b/lib/model/identifier.mli
new file mode 100644
index 0000000..eed5d83
--- /dev/null
+++ b/lib/model/identifier.mli
@@ -0,0 +1,49 @@
+type t
+(** An SQL identifier (table or column name).
+
+ The type is abstract and implemented as a string: the only way to create a
+ value is {!of_string}, which validates the string. A [t] is therefore always
+ safe to embed in a quoted SQL identifier, and the query layer never
+ manipulates raw strings for table or column names. *)
+
+exception Invalid of string
+(** Raised by {!of_string} when the string is not a valid identifier. *)
+
+val is_valid : string -> bool
+(** [is_valid s] is [true] iff [s] is a non-empty sequence of letters, digits,
+ underscores or hyphens. In particular the double quote (which could break
+ out of a quoted identifier) and the dot (used internally to build the names
+ of the dedicated tables for multivalued fields) are rejected. *)
+
+val of_string : string -> t
+(** The only way to build an identifier. @raise Invalid if the string is not
+ valid. *)
+
+val of_string_opt : string -> t option
+(** [of_string_opt s] is [Some id] if [s] is valid, [None] otherwise. *)
+
+val to_string : t -> string
+(** The underlying string. *)
+
+val id : t
+(** The [id] column: primary key of every content table. *)
+
+val parent : t
+(** The [parent] column: foreign key to the parent content, present in
+ subcontent tables and in the dedicated tables of multivalued fields. *)
+
+val target : t
+(** The [target] column of the dedicated tables for multivalued fields. *)
+
+val quote : t -> string
+(** [quote id] is the SQL quoted form ["..."] of the identifier. *)
+
+val dot : t -> t -> t
+(** [dot a b] is the identifier ["a.b"], used for the dedicated tables of
+ multivalued fields. Both parts are already validated and contain no dot, so
+ the result is safe to quote as a single identifier. *)
+
+val equal : t -> t -> bool
+val compare : t -> t -> int
+val hash : t -> int
+val pp : Format.formatter -> t -> unit
diff --git a/lib/model/tests/identifier.t b/lib/model/tests/identifier.t
new file mode 100644
index 0000000..39460ff
--- /dev/null
+++ b/lib/model/tests/identifier.t
@@ -0,0 +1,38 @@
+Test the [Model.Identifier] module: validation of the names, their quoted SQL
+form, the predefined columns and the composite names used for the dedicated
+tables of multivalued fields.
+
+Valid identifiers are printed in their quoted SQL form:
+
+ $ tests --identifier check entity user-details user_type_list
+ "entity"
+ "user-details"
+ "user_type_list"
+
+Invalid identifiers are rejected: the empty string, and any character outside
+letters, digits, underscore and hyphen — in particular the double quote (which
+could break out of a quoted identifier) and the dot (reserved for the composite
+table names):
+
+ $ tests --identifier check 'evil"; DROP TABLE entity;--' foo.bar ''
+ invalid: "evil"; DROP TABLE entity;--"
+ invalid: "foo.bar"
+ invalid: ""
+
+The fixed columns of the generated schema are predefined:
+
+ $ tests --identifier predefined
+ id = "id"
+ parent = "parent"
+ target = "target"
+
+A composite name is built from two valid identifiers:
+
+ $ tests --identifier dot entity references
+ "entity.references"
+
+An invalid part is rejected when building a composite name:
+
+ $ tests --identifier dot 'bad"name' ref
+ Fatal error: exception Model.Identifier.Invalid("bad\"name")
+ [2]
diff --git a/lib/query/create.ml b/lib/query/create.ml
index d34339b..05aec0f 100644
--- a/lib/query/create.ml
+++ b/lib/query/create.ml
@@ -17,14 +17,15 @@ let get_field_query : _ Model.Field.t -> string option =
in
Option.map
(fun t ->
- String.concat ~sep:" " [ "\"" ^ Model.Field.name field ^ "\""; t ])
+ String.concat ~sep:" "
+ [ Model.Identifier.quote (Model.Field.name field); t ])
ty
type foreign = {
- src_table : string;
- src_column : string;
- dst_table : string;
- dst_column : string;
+ src_table : Model.Identifier.t;
+ src_column : Model.Identifier.t;
+ dst_table : Model.Identifier.t;
+ dst_column : Model.Identifier.t;
}
(** Foreign key between a column referencing a content and the referenced value
*)
@@ -35,10 +36,15 @@ ADD FOREIGN KEY (best_a_id)
REFERENCES answer(a_id);
*)
-let get_foreign_statement : string -> _ Model.Content.t -> string =
+let get_foreign_statement : Model.Identifier.t -> _ Model.Content.t -> string =
fun property content ->
- "FOREIGN KEY(\"" ^ property ^ "\") REFERENCES " ^ Model.Content.id content
- ^ "(\"id\")"
+ "FOREIGN KEY("
+ ^ Model.Identifier.quote property
+ ^ ") REFERENCES "
+ ^ Model.Identifier.quote (Model.Content.id content)
+ ^ "("
+ ^ Model.Identifier.quote Model.Identifier.id
+ ^ ")"
(** Create the dedicated table required for multivaluated fields *)
let create_external_reference_table :
@@ -62,13 +68,15 @@ let create_external_reference_table :
"\"id\" INTEGER PRIMARY KEY";
"\"parent\" INTEGER NOT NULL";
"\"target\" INTEGER NOT NULL";
- get_foreign_statement "parent" content;
- get_foreign_statement "target" target;
+ get_foreign_statement Model.Identifier.parent content;
+ get_foreign_statement Model.Identifier.target target;
]
in
let () =
- Format.fprintf format "CREATE TABLE \"%s.%s\"@; @[@[<v>( %a@] )@]"
- (Model.Content.id content) (Model.Field.name field)
+ Format.fprintf format "CREATE TABLE %s@; @[@[<v>( %a@] )@]"
+ (Model.Identifier.quote
+ (Model.Identifier.dot (Model.Content.id content)
+ (Model.Field.name field)))
(Format.pp_print_list
~pp_sep:(fun f () ->
Format.pp_print_break f 0 0;
@@ -94,6 +102,7 @@ let rec create_table :
_ Model.Content.t ->
(foreign list * Model.Reference.t Model.Content.t list) Lwt.t =
fun db (alter_queries, created) content ->
+ let module Identifier = Model.Identifier in
(* The foreign keys are added at the end of the query, and need to be
defined first *)
let alter_queries =
@@ -102,9 +111,9 @@ let rec create_table :
| Some p ->
{
src_table = Model.Content.id content;
- src_column = "parent";
+ src_column = Model.Identifier.parent;
dst_table = Model.Content.id p;
- dst_column = "id";
+ dst_column = Model.Identifier.id;
}
:: alter_queries
in
@@ -115,7 +124,7 @@ let rec create_table :
the foreign key constraint *)
let init_foreign =
match Model.Content.parent content with
- | Some parent -> [ get_foreign_statement "parent" parent ]
+ | Some parent -> [ get_foreign_statement Identifier.parent parent ]
| None -> []
in
let foreign, alter_queries =
@@ -140,7 +149,7 @@ let rec create_table :
src_table = Model.Content.id content;
src_column = column;
dst_table = Model.Content.id dst;
- dst_column = "id";
+ dst_column = Model.Identifier.id;
}
:: alter_queries
in
@@ -162,8 +171,8 @@ let rec create_table :
let buff = Buffer.create 128 in
let format = Format.formatter_of_buffer buff in
let () =
- Format.fprintf format "CREATE TABLE \"%s\"@; @[@[<v>( %a@] )@]"
- (Model.Content.id content)
+ Format.fprintf format "CREATE TABLE %s@; @[@[<v>( %a@] )@]"
+ (Identifier.quote (Model.Content.id content))
(Format.pp_print_list
~pp_sep:(fun f () ->
Format.pp_print_break f 0 0;
@@ -197,28 +206,30 @@ let rec create_table :
(** Modify the table and add the foreign key in case of cyclic references *)
let add_foreign_statement : Caqti_lwt.connection -> foreign list -> unit Lwt.t =
fun db foreigns ->
- let request_str =
- "ALTER TABLE ? ADD CONSTRAINT FOREIGN KEY(?) REFERENCES ?(?)"
- in
- let request =
- let open Caqti.Templater in
- direct T.(t4 string string string string -->. unit) request_str
- in
let module Db = (val db) in
- let* () =
- Lwt_list.iter_s
- (fun foreign ->
- let* result =
- Db.exec request
- ( foreign.src_table,
- foreign.src_column,
- foreign.dst_table,
- foreign.dst_column )
- in
- Caqti_lwt.or_fail result)
- foreigns
- in
- Lwt.return_unit
+ let module Identifier = Model.Identifier in
+ (* Identifiers cannot be passed as query parameters, so the statement is
+ built with validated and quoted identifiers for each constraint. *)
+ Lwt_list.iter_s
+ (fun foreign ->
+ let request_str =
+ "ALTER TABLE "
+ ^ Identifier.quote foreign.src_table
+ ^ " ADD CONSTRAINT FOREIGN KEY("
+ ^ Identifier.quote foreign.src_column
+ ^ ") REFERENCES "
+ ^ Identifier.quote foreign.dst_table
+ ^ "("
+ ^ Identifier.quote foreign.dst_column
+ ^ ")"
+ in
+ let request =
+ let open Caqti.Templater in
+ direct T.(unit -->. unit) request_str
+ in
+ let* result = Db.exec request () in
+ Caqti_lwt.or_fail result)
+ foreigns
let create : Caqti_lwt.connection -> Configuration.Ast.setting -> unit Lwt.t =
fun db conf ->
diff --git a/lib/query/encoder.ml b/lib/query/encoder.ml
index 6897ec7..5ee6727 100644
--- a/lib/query/encoder.ml
+++ b/lib/query/encoder.ml
@@ -271,10 +271,13 @@ module InsertTableName = Map (struct
let f : type a. unit -> a data -> a t =
fun () -> function
- | { name = column; content_type = Text; _ } -> column
- | { name = column; content_type = Integer; _ } -> column
- | { name = column; content_type = MultiReference _; _ } -> column
- | { name = column; content_type = MonoReference _; _ } -> column
+ | { name = column; content_type = Text; _ } -> Model.Identifier.quote column
+ | { name = column; content_type = Integer; _ } ->
+ Model.Identifier.quote column
+ | { name = column; content_type = MultiReference _; _ } ->
+ Model.Identifier.quote column
+ | { name = column; content_type = MonoReference _; _ } ->
+ Model.Identifier.quote column
include ConcatParam
end)
@@ -292,7 +295,7 @@ module DataToCaqtiValues = Map (struct
let f : type a. env -> a Intf.data -> a t =
fun provider Intf.{ name; content_type } ->
- let result = provider name in
+ let result = provider (Model.Identifier.to_string name) in
(* Check the value given by the provider and ensure it’s match the
expected type *)
match result with
diff --git a/lib/query/insert.ml b/lib/query/insert.ml
index c124f0a..6e95631 100644
--- a/lib/query/insert.ml
+++ b/lib/query/insert.ml
@@ -60,9 +60,12 @@ module MultiReferencesInsert = struct
fun ({ db; parent_id; provider; k; content } as acc)
Intf.{ name; content_type } ->
let module Db = (val db) in
+ let module Identifier = Model.Identifier in
+ let parent = Identifier.quote Identifier.parent
+ and target = Identifier.quote Identifier.target in
match content_type with
| Model.Typ.MultiReference _target -> (
- let result = provider name in
+ let result = provider (Model.Identifier.to_string name) in
match result with
| Model.Typ.None -> acc
| Model.Typ.V _ -> raise Encoder.TypeMismatch
@@ -73,9 +76,10 @@ module MultiReferencesInsert = struct
let q =
Croquette_common.Format.format_string (fun format ->
Format.fprintf format
- "INSERT INTO \"%s.%s\" (\"parent\", \"target\") VALUES \
- (?, ?)"
- (Model.Content.id content) name)
+ "INSERT INTO %s (%s, %s) VALUES (?, ?)"
+ (Identifier.quote
+ (Identifier.dot (Model.Content.id content) name))
+ parent target)
in
let request : request =
Caqti.Templater.(dynamic T.(t2 int64 int64 -->. unit) q)
@@ -109,7 +113,9 @@ let insert_returning :
let init_fields =
match Model.Content.parent content with
| None -> []
- | Some _ -> Model.Field.[ create (T Integer) [] ~required:true "parent" ]
+ | Some _ ->
+ Model.Field.
+ [ create (T Integer) [] ~required:true Model.Identifier.parent ]
in
(* Remove the mulivaluated content fields from the request because they are
@@ -131,10 +137,12 @@ let insert_returning :
| _ -> "(" ^ (Encoder.InsertTableName.f ()) t ^ ")"
in
+ let module Identifier = Model.Identifier in
let q =
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)
+ Format.fprintf format "INSERT INTO %s %s VALUES %s RETURNING ID"
+ (Identifier.quote (Model.Content.id content))
+ columns insert_template)
in
let types_param = (Encoder.CaqtiRequest.f ()) t in
let request = Caqti.Templater.(direct T.(types_param -->! int64) q) in
@@ -194,13 +202,13 @@ let insert_references :
Caqti_lwt.connection ->
Model.Reference.t Model.Content.t ->
Int64.t ->
- string ->
+ Model.Identifier.t ->
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
+ | n when String.equal n (Model.Identifier.to_string field_name) -> value
| _ -> Model.Typ.None
in
let acc =
diff --git a/lib/query/insert.mli b/lib/query/insert.mli
index 798c37b..3f39bd5 100644
--- a/lib/query/insert.mli
+++ b/lib/query/insert.mli
@@ -12,7 +12,7 @@ val insert_references :
Caqti_lwt.connection ->
Model.Reference.t Model.Content.t ->
Int64.t ->
- string ->
+ Model.Identifier.t ->
Model.Reference.t Model.Typ.value ->
Int64.t Intf.data ->
unit Lwt.t
diff --git a/lib/query/intf.ml b/lib/query/intf.ml
index 4c09eef..8c7ead5 100644
--- a/lib/query/intf.ml
+++ b/lib/query/intf.ml
@@ -1,5 +1,5 @@
type 'a data = {
- name : string;
+ name : Model.Identifier.t;
content_type : ('a, Model.Reference.t) Model.Typ.t;
}
(** The data is the name of the field and the type associated with *)
diff --git a/lib/query/tests/create.t b/lib/query/tests/create.t
index 6ba48c3..38a4630 100644
--- a/lib/query/tests/create.t
+++ b/lib/query/tests/create.t
@@ -69,7 +69,7 @@ A subcontent is linked to the parent:
CREATE TABLE "details"
( "parent" INTEGER NOT NULL
, "id" INTEGER PRIMARY KEY
- , FOREIGN KEY("parent") REFERENCES entity("id") )
+ , FOREIGN KEY("parent") REFERENCES "entity"("id") )
A reference field is declared as a foreign key to the linked element
@@ -109,7 +109,7 @@ A reference field is declared as a foreign key to the linked element
( "id" INTEGER PRIMARY KEY
, "user_type" INTEGER
, "name" VARCHAR
- , FOREIGN KEY("user_type") REFERENCES user_type_list("id") )
+ , FOREIGN KEY("user_type") REFERENCES "user_type_list"("id") )
When the field is multivaluated, there is no column for this property in the
table but a dedicated table is created:
@@ -146,5 +146,6 @@ table but a dedicated table is created:
( "id" INTEGER PRIMARY KEY
, "parent" INTEGER NOT NULL
, "target" INTEGER NOT NULL
- , FOREIGN KEY("parent") REFERENCES entity("id")
- , FOREIGN KEY("target") REFERENCES user_type_list("id") )
+ , FOREIGN KEY("parent") REFERENCES "entity"("id")
+ , FOREIGN KEY("target") REFERENCES "user_type_list"("id") )
+
diff --git a/lib/query/update.ml b/lib/query/update.ml
index 6d20999..d828b6b 100644
--- a/lib/query/update.ml
+++ b/lib/query/update.ml
@@ -8,9 +8,12 @@ module UpdateTemplate = Encoder.Map (struct
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 = column; content_type = Text; _ } ->
+ Model.Identifier.quote column ^ "=?"
+ | { name = column; content_type = Integer; _ } ->
+ Model.Identifier.quote column ^ "=?"
+ | { name = column; content_type = MonoReference _; _ } ->
+ Model.Identifier.quote column ^ "=?"
| { name = _; content_type = MultiReference _; _ } -> raise Not_found
include Encoder.ConcatParam
@@ -33,10 +36,13 @@ let update_fields :
let types_param =
Caqti.Templater.T.(t2 (Encoder.CaqtiRequest.f () query_fields) int64)
in
+ let module Identifier = Model.Identifier in
+ let id_key = Identifier.quote Identifier.id 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)
+ Format.fprintf format "UPDATE %s SET %s WHERE %s = ?"
+ (Identifier.quote (Model.Content.id content))
+ format_param id_key)
in
let request = Caqti.Templater.(direct T.(types_param -->. unit) q) in
let query_param =
@@ -72,7 +78,8 @@ 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 ->
+ (Model.Identifier.t * (int64, Model.Reference.t) Model.Typ.t * int64 Seq.t)
+ list ->
int64 ->
unit Lwt.t =
fun db content fields id ->
@@ -93,11 +100,16 @@ let update_mulivaluated_field :
ignore ref;
Intf.(TT data_type))
in
+ let module Identifier = Model.Identifier in
+ let id_key = Identifier.quote Identifier.id
+ and parent = Identifier.quote Identifier.parent
+ and target = Identifier.quote Identifier.target 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
+ Format.fprintf f "DELETE FROM %s where %s=? and %s not in (%s)"
+ (Identifier.quote
+ (Identifier.dot (Model.Content.id content) field_name))
+ parent target
(Encoder.EncodeParameter.f () existing_references_t))
in
let caqti_param = Encoder.CaqtiRequest.f () existing_references_t in
@@ -114,8 +126,10 @@ let update_mulivaluated_field :
(* 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)
+ Format.fprintf f "SELECT %s FROM %s WHERE %s=?" id_key
+ (Identifier.quote
+ (Identifier.dot (Model.Content.id content) field_name))
+ parent)
in
let request_select =
Caqti.Templater.(direct T.(int64 -->* int64) q_select)
@@ -154,10 +168,12 @@ let q :
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
+ let value = provider (Model.Identifier.to_string name) in
match value with
| Model.Typ.None -> acc
- | Model.Typ.V _ as value -> ((tt, (name, value)) :: fields, references)
+ | Model.Typ.V _ as value ->
+ ( (tt, (Model.Identifier.to_string name, value)) :: fields,
+ references )
| Model.Typ.Seq (t, seq) -> (fields, (name, t, seq) :: references))
([], [])
(Model.Content.fields content)
diff --git a/test/common.ml b/test/common.ml
index 0ef5cb3..98871a3 100644
--- a/test/common.ml
+++ b/test/common.ml
@@ -31,12 +31,10 @@ let content_as_json :
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 ",")
+ let name = Model.Field.name field in
+ Buffer.add_string buff
+ ( Croquette_common.Sql.quote_literal (Model.Identifier.to_string name)
+ ^ "," ^ Model.Identifier.quote name ^ "," ))
fields
in
@@ -46,21 +44,28 @@ let content_as_json :
let length = Buffer.length buff in
if length > 1 then Buffer.truncate buff (length - 1);
()
- | Some _ -> Buffer.add_string buff "'parent',parent"
+ | Some _ ->
+ Buffer.add_string buff
+ ( Croquette_common.Sql.quote_literal "parent" ^ ","
+ ^ Model.Identifier.quote (Model.Identifier.parent) )
in
let q = Buffer.contents buff in
let open Caqti.Templater in
direct T.(int64 -->! string)
- ("SELECT json_object(" ^ q ^ ") from " ^ Model.Content.id content
- ^ " where id=?")
+ ("SELECT json_object(" ^ q ^ ") from "
+ ^ Model.Identifier.quote (Model.Content.id content)
+ ^ " where " ^ Model.Identifier.quote (Model.Identifier.id) ^ "=?")
-let query_values (table : Model.Reference.t Model.Content.t) (feature : string)
- =
+let query_values (table : Model.Reference.t Model.Content.t)
+ (feature : Model.Identifier.t) =
let open Caqti.Templater in
direct T.(int64 -->* string)
- ("SELECT json_object('" ^ feature ^ "', target) from \""
- ^ Model.Content.id table ^ "." ^ feature ^ "\" where parent=?")
+ ("SELECT json_object("
+ ^ Croquette_common.Sql.quote_literal (Model.Identifier.to_string feature)
+ ^ ", " ^ Model.Identifier.quote (Model.Identifier.target) ^ ") from "
+ ^ Model.Identifier.quote (Model.Identifier.dot (Model.Content.id table) feature)
+ ^ " where " ^ Model.Identifier.quote (Model.Identifier.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
@@ -73,7 +78,7 @@ let collect_references :
fun db content id ->
let module Db = (val db) in
let ( let* ) = Lwt.bind in
- let content_id = Model.Content.id content in
+ let content_id = Model.Identifier.to_string (Model.Content.id content) in
(* Only keep the multivaluated fields *)
let fields =
diff --git a/test/identifier.ml b/test/identifier.ml
new file mode 100644
index 0000000..322f459
--- /dev/null
+++ b/test/identifier.ml
@@ -0,0 +1,42 @@
+let name = __FILE__
+
+let description =
+ "Check the [Model.Identifier] module: validation of the names given as \
+ arguments, their quoted SQL form, the predefined columns and the composite \
+ names"
+
+let speclist () = []
+
+type t = string list
+
+let pp : Format.formatter -> t -> unit =
+ Format.pp_print_list ~pp_sep:Format.pp_print_newline Format.pp_print_string
+
+(** A valid name is printed in its quoted SQL form, an invalid one is
+ reported *)
+let check : string -> string =
+ fun s ->
+ match Model.Identifier.of_string_opt s with
+ | Some id -> Model.Identifier.quote id
+ | None -> "invalid: \"" ^ s ^ "\""
+
+let exec : string list -> t =
+ fun args ->
+ (* The anonymous arguments are collected in reverse order by the test
+ harness *)
+ match List.rev args with
+ | "check" :: names -> List.map check names
+ | "predefined" :: [] ->
+ [
+ "id = " ^ Model.Identifier.quote Model.Identifier.id;
+ "parent = " ^ Model.Identifier.quote Model.Identifier.parent;
+ "target = " ^ Model.Identifier.quote Model.Identifier.target;
+ ]
+ | "dot" :: [ a; b ] ->
+ [
+ Model.Identifier.quote
+ (Model.Identifier.dot
+ (Model.Identifier.of_string a)
+ (Model.Identifier.of_string b));
+ ]
+ | _ -> failwith "Invalid arguments"
diff --git a/test/insert.ml b/test/insert.ml
index bc65422..451d857 100644
--- a/test/insert.ml
+++ b/test/insert.ml
@@ -35,7 +35,7 @@ let insert_and_get_result :
Query.insert ?parent db content (fun v ->
match List.assoc_opt v entry with Some v -> v | None -> Model.Typ.None)
in
- let content_id = Model.Content.id content in
+ let content_id = Model.Identifier.to_string (Model.Content.id content) in
let module Db = (val db) in
let* json_result = Db.find (Common.content_as_json content) id in
let* json = Caqti_lwt.or_fail json_result in
@@ -144,7 +144,7 @@ module Make (S : Decoders.Decode.S) = struct
[
( "content",
fun v ->
- match (Configuration.Ast.get_content conf) key with
+ match (Configuration.Ast.get_content conf) (Model.Identifier.of_string key) with
| None -> Error (Decoders.Error.make "no content")
| Some subcontent ->
let values = self#values subcontent v in
@@ -172,7 +172,7 @@ module Make (S : Decoders.Decode.S) = struct
fun name ->
(* In this syntax, the content is supposed to follow the definition
and will never be None *)
- let content = Configuration.Ast.get_content conf name |> Option.get in
+ let content = Configuration.Ast.get_content conf (Model.Identifier.of_string name) |> Option.get in
let* properties =
S.field_opt_or ~default:(Lwt.return []) "values"
(self#values content)
diff --git a/test/parent.ml b/test/parent.ml
index 232de34..6e07c90 100644
--- a/test/parent.ml
+++ b/test/parent.ml
@@ -33,10 +33,11 @@ let exec : string list -> t = function
let+ configuration = Configuration.Read_conf.read_string_conf stdin in
let ( let+ ) opt cont = Option.map cont opt in
let+ subcontent =
- Configuration.Ast.get_content configuration subcontent_id
+ Configuration.Ast.get_content configuration
+ (Model.Identifier.of_string subcontent_id)
in
let+ v = !parent subcontent in
- Model.Content.id v
+ Model.Identifier.to_string (Model.Content.id v)
in
parent_id
| _ -> failwith "Invalid arguments"
diff --git a/test/tests.ml b/test/tests.ml
index d396ac0..0f0fdc5 100644
--- a/test/tests.ml
+++ b/test/tests.ml
@@ -35,6 +35,7 @@ let () =
register (module Configuration_);
register (module Insert);
register (module Update);
+ register (module Identifier);
]
let args = ref []
diff --git a/test/update.ml b/test/update.ml
index 1e94fc2..6f22466 100644
--- a/test/update.ml
+++ b/test/update.ml
@@ -67,11 +67,11 @@ let configuration =
let speclist () =
let (lazy configuration) = configuration in
- let content = Configuration.Ast.get_content configuration "entity" in
+ let content = Configuration.Ast.get_content configuration (Model.Identifier.of_string "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 key = "--" ^ Model.Identifier.to_string (Model.Field.name feature) in
let (Model.Field.T type_) = Model.Field.type_ feature in
let argument =
match type_ with
@@ -81,7 +81,7 @@ let speclist () =
Arg.String
(fun value ->
actions :=
- Text (Model.Field.name feature, value) :: !actions),
+ Text (Model.Identifier.to_string (Model.Field.name feature), value) :: !actions),
"<v> Set field with the value <v>" )
| Model.Typ.Integer ->
Some
@@ -89,7 +89,7 @@ let speclist () =
Arg.Int
(fun value ->
actions :=
- Integer (Model.Field.name feature, value) :: !actions),
+ Integer (Model.Identifier.to_string (Model.Field.name feature), value) :: !actions),
"<n> Set field with the value <n>" )
| Model.Typ.MonoReference target ->
Some
@@ -97,7 +97,7 @@ let speclist () =
Arg.Int
(fun value ->
actions :=
- Reference (target, Model.Field.name feature, value)
+ Reference (target, Model.Identifier.to_string (Model.Field.name feature), value)
:: !actions),
"<id> Set field with the id" )
| Model.Typ.MultiReference target ->
@@ -112,7 +112,7 @@ let speclist () =
in
actions :=
- References (target, Model.Field.name feature, ids)
+ References (target, Model.Identifier.to_string (Model.Field.name feature), ids)
:: !actions),
"<id,..> Set this list of values" )
in
@@ -133,7 +133,7 @@ let exec : string list -> t =
fun _ ->
let (lazy configuration) = configuration in
let content =
- Configuration.Ast.get_content configuration "entity" |> Option.get
+ Configuration.Ast.get_content configuration (Model.Identifier.of_string "entity") |> Option.get
in
Lwt_main.run
@@ -162,7 +162,7 @@ let exec : string list -> t =
let field =
Model.Content.fields content
|> Seq.find (fun f ->
- String.equal key (Model.Field.name f))
+ String.equal key (Model.Identifier.to_string (Model.Field.name f)))
|> Option.get
in
let (Model.Field.T t) = Model.Field.type_ field in