使用postgresql-simple创建流媒体管道源

时间:2017-01-13 21:10:40

标签: haskell conduit postgresql-simple

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)

如何实现这一点的任何指针将不胜感激!谢谢!

2 个答案:

答案 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