2 | import public Sqlite3
8 | Resource (Async e) Stmt where
9 | cleanup = liftIO . sqliteFinalize'
12 | Resource (Async e) DB where
13 | cleanup = liftIO . sqliteClose'
15 | toRes : Chunk a -> UnfoldRes () () (List a)
16 | toRes (More xs) = More xs ()
17 | toRes (Done xs) = Last () xs
19 | parameters {auto has : Has SqlError es}
22 | openSqlite : String -> Async e es DB
23 | openSqlite = injectIO . sqliteOpen
26 | openStmt : DB => String -> Async e es Stmt
27 | openStmt = injectIO . sqlitePrepare
35 | withDB : String -> (DB => Async e es a) -> Async e es a
36 | withDB s f = use1 (openSqlite s) $
\_ => f
43 | withStmt : DB => String -> (Stmt => Async e es a) -> Async e es a
44 | withStmt s f = use1 (openStmt s) $
\_ => f
51 | bindParams : DB => Stmt => List Parameter -> Async e es ()
52 | bindParams = injectIO . sqliteBind
55 | openBoundStmt : DB => ParamStmt -> Async e es Stmt
56 | openBoundStmt st = Prelude.do
57 | let (ps, str) := runState init st
69 | withBoundStmt : DB => ParamStmt -> (Stmt => Async e es a) -> Async e es a
70 | withBoundStmt st f = use1 (openBoundStmt st) $
\_ => f
74 | step : (s : Stmt) => Async e es SqlResult
75 | step @{s} = liftIO $
sqliteStep s
82 | commit : DB => ParamStmt -> Async e es ()
83 | commit st = withBoundStmt st (ignore step)
88 | selectRows : DB => FromRow a => ParamStmt -> (n : Nat) -> Async e es (List a)
89 | selectRows st n = withBoundStmt st (injectIO $
loadRows n)
94 | selectRow : DB => FromRow a => ParamStmt -> Async e es a
96 | [v] <- selectRows st 1 | _ => throw NoMoreData
102 | findRow : DB => FromRow a => ParamStmt -> Async e es (Maybe a)
104 | [v] <- selectRows st 1 | _ => pure Nothing
109 | {auto cs : ChunkSize}
111 | -> {auto fr : FromRow a}
113 | -> AsyncStream e es (List a)
114 | rows {cs = CS sz} st =
115 | resource (openBoundStmt st) $
\_ =>
116 | unfoldEval () $
\_ => toRes <$> injectIO (loadChunk {a} sz)
124 | cmd : DB => Cmd t -> Async e es ()
125 | cmd = commit . encodeCmd
127 | rollback : DB => HSum es -> Async e es a
128 | rollback x = ignore (withStmt "ROLLBACK TRANSACTION" step) >> fail x
134 | cmds : DB => Cmds -> Async e es ()
136 | uncancelable $
\poll => Prelude.do
137 | ignore $
withStmt "BEGIN TRANSACTION" step
138 | handleErrors rollback (runCommands cs)
139 | ignore $
withStmt "COMMIT TRANSACTION" step
142 | runCommands : Cmds -> Async e es ()
143 | runCommands [] = pure ()
144 | runCommands (c::cs) = cmd c >> runCommands cs
148 | query : DB => Query t -> (n : Nat) -> Async e es (List t)
149 | query q = selectRows (encodeQuery q)
153 | query1 : DB => Query t -> Async e es (Maybe t)
154 | query1 q = map (\case h::_ => Just h;
[] => Nothing) $
query q 1
158 | queryRows : (cs : ChunkSize) => DB => Query t -> AsyncStream e es (List t)
159 | queryRows q = rows (encodeQuery q)
168 | -> {auto tr : ToRow t}
170 | -> {auto 0 prf : ToRowTypes t === FromRowTypes t}
172 | -> Async e es (Table t)
173 | queryTable {prf} q n = do
175 | pure (T (rewrite prf in hmap columnName q.columns) rs)