Source file caqti_sql_io.ml
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
module type MONAD = sig
type +'a t
val (>>=) : 'a t -> ('a -> 'b t) -> 'b t
val return : 'a -> 'a t
end
module type S = sig
type +'a future
val read_sql_statement :
('a -> char option future) -> 'a -> string option future
end
module Make (Io : MONAD) = struct
open Io
let read_sql_statement read_char ic =
let buf = Buffer.create 256 in
let finish () =
match String.trim (Buffer.contents buf) with
| "" -> return None
| s -> return (Some s) in
let rec scan level = function
| Some ';' when level = 0 -> finish ()
| Some '\'' -> Buffer.add_char buf '\''; read_char ic >>= scan_quote level
| Some '-' ->
read_char ic >>=
begin function
| Some '-' -> read_char ic >>= scan_comment level
| c_opt -> Buffer.add_char buf '-'; scan level c_opt
end
| Some '(' -> Buffer.add_char buf '('; read_char ic >>= scan (succ level)
| Some ')' -> Buffer.add_char buf ')'; read_char ic >>= scan (pred level)
| Some c -> Buffer.add_char buf c; read_char ic >>= scan level
| None -> finish ()
and scan_quote level = function
| Some '\'' -> Buffer.add_char buf '\''; read_char ic >>= scan level
| Some c -> Buffer.add_char buf c; read_char ic >>= scan_quote level
| None -> finish ()
and level = function
| Some '\n' -> read_char ic >>= scan level
| Some _ -> read_char ic >>= scan_comment level
| None -> finish () in
read_char ic >>= scan 0
end