postgresql-simple
提供流式查询功能,例如
fold
:: (FromRow row, ToRow params)
=> Connection -> Query -> params -> a -> (a -> row -> IO a) -> IO a
我想创建一个充分利用流媒体的管道源。
mySource :: (FromRow row, Monad m) => Source m row
不幸的是,由于IO
出现在fold
的逆变位置(我认为?),我真的在与这些类型进行斗争。以下类型检查,但在产生值之前折叠整个流。
getConduit :: Connection -> IO (C.ConduitM () Event IO ())
getConduit conn = fold_ conn queryEventRecord CL.sourceNull foo
where
foo :: C.ConduitM () Event IO () -> Event -> IO (C.ConduitM () Event IO ())
foo cond evt = pure (cond >> C.yield evt)
如何实现这一点的任何指针将不胜感激!谢谢!
答案 0 :(得分:5)
一个(不太好)的方式来解决这个问题
TMChan
以接收行foreach_
设置为只将行转储到此频道stm-conduit
从频道中制作出来源我没有办法对此进行测试,但以下情况应该有效
import Conduit
import Database.PostgreSQL.Simple (foreach_)
import Data.Conduit.TMChan (sourceTMChan)
import Control.Concurrent.STM.TMChan (newTMChanIO, writeTMChan, atomically)
mySource :: (FromRow row, MonadIO m) => Connection -> Query -> IO (Source m row)
mySource connection query = do
chan <- newTMChanIO
forEach_ connection query (atomically . writeTMChan chan)
pure (sourceTMChan chan)
如果我们只有forEach_ :: (MonadIO m, FromRow r) => Connection -> Query -> (r -> m ()) -> m ()
这可能会更容易......
答案 1 :(得分:0)
以上是对Alec以上编辑和运行的修改。 mkPgSource
是Alec在其职位末尾提到的一般功能。
import Database.PostgreSQL.Simple
import Database.PostgreSQL.Simple.FromRow
import Database.PostgreSQL.Simple.ToRow
import Control.Monad.IO.Class (MonadIO)
import Data.Conduit.TMChan (sourceTMChan)
import Control.Concurrent.STM.TMChan (newTMChanIO, writeTMChan,
closeTMChan, TMChan)
import GHC.Conc (atomically, forkIO)
import Conduit
--closes the channel after action is done to terminate the source
mkPgSource :: (MonadIO m, FromRow r) => ((r -> IO ()) -> IO ()) -> IO (Source m r)
mkPgSource action = do
chan <- newTMChanIO
_ <- forkIO $ do action $ atomically . (writeTMChan chan)
atomically $ closeTMChan chan
pure $ sourceTMChan chan
sourceQuery :: (ToRow params, FromRow r, MonadIO m) =>
Connection -> Query -> params -> IO (Source m r)
sourceQuery conn q params = mkPgSource $ forEach conn q params
sourceQuery_ :: (FromRow r, MonadIO m) => Connection -> Query -> IO
(Source m r)
sourceQuery_ conn q = mkPgSource $ forEach_ conn q