@@ -32,6 +32,7 @@ module Database.PostgreSQL.Simple.Copy
3232 ( copy
3333 , copy_
3434 , CopyOutResult(..)
35+ , foldCopyData
3536 , getCopyData
3637 , putCopyData
3738 , putCopyEnd
@@ -104,6 +105,30 @@ data CopyOutResult
104105 deriving (Eq, Typeable, Show)
105106
106107
108+-- | Fold over @COPY TO STDOUT@ query passing each copied row to an accumulator
109+-- and calling a post-process at the end. A connection must be in the
110+-- @CopyOut@ state in order to call this function.
111+--
112+-- __Example__
113+--
114+-- > (acc, count) <- foldCopyData conn
115+-- > (\acc row -> return (row:acc))
116+-- > (\acc count -> return (acc, count))
117+-- > []
118+
119+foldCopyData
120+ :: Connection -- ^ Database connection
121+ -> (a -> B.ByteString -> IO a) -- ^ Accumulate one row of the result
122+ -> (a -> Int64 -> IO b) -- ^ Post-process accumulator with a count of rows
123+ -> a -- ^ Initial accumulator
124+ -> IO b -- ^ Result
125+foldCopyData conn f g !acc = do
126+ result <- getCopyData conn
127+ case result of
128+ CopyOutRow row -> f acc row >>= foldCopyData conn f g
129+ CopyOutDone count -> g acc count
130+
131+
107132-- | Retrieve some data from a @COPY TO STDOUT@ query. A connection
108133-- must be in the @CopyOut@ state in order to call this function. If this
109134-- returns a 'CopyOutRow', the connection remains in the @CopyOut@ state,