0 | module Control.RIO.Sqlite3
2 | import public Control.RIO.App
3 | import public Sqlite3
4 | import public Data.List.Quantifiers
8 | parameters {auto has : Has SqlError es}
16 | withDB : String -> (DB => App es a) -> App es a
18 | db <- injectIO $
sqliteOpen s
19 | finally (liftIO $
sqliteClose' db) (f @{db})
26 | withStmt : DB => String -> (Stmt => App es a) -> App es a
28 | stmt <- injectIO $
sqlitePrepare str
29 | finally (liftIO $
sqliteFinalize' stmt) (f @{stmt})
38 | bindParams : DB => Stmt => List Parameter -> App es ()
39 | bindParams ps = injectIO (sqliteBind ps)
48 | withBoundStmt : DB => ParamStmt -> (Stmt => App es a) -> App es a
49 | withBoundStmt st f =
50 | let (ps, str) := runState init st
51 | in withStmt str (bindParams ps.args >> f)
55 | step : (s : Stmt) => App es SqlResult
56 | step @{s} = liftIO $
sqliteStep s
63 | commit : DB => ParamStmt -> App es ()
64 | commit st = withBoundStmt st (ignore step)
69 | selectRows : DB => FromRow a => ParamStmt -> (n : Nat) -> App es (List a)
70 | selectRows st n = withBoundStmt st (injectIO $
loadRows n)
75 | selectRow : DB => FromRow a => ParamStmt -> App es a
77 | [v] <- selectRows st 1 | _ => throw NoMoreData
83 | findRow : DB => FromRow a => ParamStmt -> App es (Maybe a)
85 | [v] <- selectRows st 1 | _ => pure Nothing
94 | cmd : DB => Cmd t -> App es ()
95 | cmd = commit . encodeCmd
97 | rollback : DB => HSum es -> App es a
98 | rollback x = ignore (withStmt "ROLLBACK TRANSACTION" step) >> fail x
104 | cmds : DB => Cmds -> App es ()
106 | ignore $
withStmt "BEGIN TRANSACTION" step
107 | catch rollback (runCommands cs)
108 | ignore $
withStmt "COMMIT TRANSACTION" step
111 | runCommands : Cmds -> App es ()
112 | runCommands [] = pure ()
113 | runCommands (c::cs) = cmd c >> runCommands cs
117 | query : DB => Query t -> (n : Nat) -> App es (List t)
118 | query q = selectRows (encodeQuery q)
127 | -> {auto tr : ToRow t}
129 | -> {auto 0 prf : ToRowTypes t === FromRowTypes t}
131 | -> App es (Table t)
132 | queryTable {prf} q n = do
134 | pure (T (rewrite prf in hmap columnName q.columns) rs)