--------------------------------------------------------------------------------
toTable
    :: (MonadIO m, Pipes.MonadSafe m, Pipes.Base m ~ IO)
    => Pg.Connection
    -> Format
    -> String
    -> Pipes.Consumer ByteString m a
toTable c fmt tblName = do
  putCopyEnd <- Pipes.register (void $ Pg.putCopyEnd c)

  Pipes.liftBase $ Pg.copy_ c $ fromString $ concat
    [ "COPY ", tblName
    , " FROM STDIN WITH (FORMAT " , show fmt, ")"
    ]

  Pipes.for Pipes.cat (liftIO . Pg.putCopyData c)
    `onException` (\e -> do Pipes.release putCopyEnd
                            Pipes.liftBase $ Pg.putCopyError c $
                              Text.encodeUtf8 . Text.pack $ show e)

 where

  action `onException` handler =
    action `catchAll` \e -> handler e >> throwM e


toTable
    :: (MonadIO m, Pipes.MonadSafe m, Pipes.Base m ~ IO)
    => Pg.Connection
    -> Format
    -> String
    -> Pipes.Consumer ByteString m a
toTable c fmt tblName = do
  putCopyEnd <- Pipes.register (void $ Pg.putCopyEnd c)

  Pipes.liftBase $ Pg.copy_ c $ fromString $ concat
    [ "COPY ", tblName
    , " FROM STDIN WITH (FORMAT " , show fmt, ")"
    ]

  Pipes.for Pipes.cat (liftIO . Pg.putCopyData c)
    `onException` (\e -> do Pipes.release putCopyEnd
                            Pipes.liftBase $ Pg.putCopyError c $
                              Text.encodeUtf8 . Text.pack $ show e)

 where

  action `onException` handler =
    action `catchAll` \e -> handler e >> throwM e


toTable c fmt tblName = do
  putCopyEnd <- Pipes.register (void $ Pg.putCopyEnd c)

  Pipes.liftBase $ Pg.copy_ c $ fromString $ concat
    [ "COPY ", tblName
    , " FROM STDIN WITH (FORMAT " , show fmt, ")"
    ]

  Pipes.for Pipes.cat (liftIO . Pg.putCopyData c)
    `onException` (\e -> do Pipes.release putCopyEnd
                            Pipes.liftBase $ Pg.putCopyError c $
                              Text.encodeUtf8 . Text.pack $ show e)

 where

  action `onException` handler =
    action `catchAll` \e -> handler e >> throwM e

