diff options
Diffstat (limited to 'lib/query.ml')
-rw-r--r-- | lib/query.ml | 20 |
1 files changed, 16 insertions, 4 deletions
diff --git a/lib/query.ml b/lib/query.ml index 70285fc..179deb6 100644 --- a/lib/query.ml +++ b/lib/query.ml @@ -145,15 +145,27 @@ let sqlite_pragmas = [ (* Example of how to execute raw SQL with Caqti *) let init_connection conn = let module C = (val conn : Rapper_helper.CONNECTION) in - (* Create a request: unit input -> unit output using Caqti infix operators *) - let pragma_req sql = + (* For PRAGMA commands, we don't know the return type, so use a custom approach *) + (* Some return strings, some return ints, some return nothing *) + let exec_pragma sql = let open Caqti_request.Infix in let open Caqti_type in - (unit ->. unit) sql + (* Try to execute as a simple exec first (for pragmas that return nothing) *) + match C.exec ((unit ->. unit) sql) () with + | Ok () -> Ok () + | Error _ -> + (* If that fails, try as a query that returns a string *) + match C.find_opt ((unit ->? string) sql) () with + | Ok _ -> Ok () + | Error _ -> + (* If that also fails, try as a query that returns an int *) + match C.find_opt ((unit ->? int) sql) () with + | Ok _ -> Ok () + | Error e -> Error e in (* Execute each pragma *) List.fold_left (fun acc sql -> match acc with | Error e -> Error e - | Ok () -> C.exec (pragma_req sql) () + | Ok () -> exec_pragma sql ) (Ok ()) sqlite_pragmas |