module Data.Csv.Embed
( embedRecords
, embedNamedRecords
) where
import Data.ByteString.Lazy as BSL
import Data.Csv
import Data.Proxy
import Data.Vector
import Language.Haskell.TH
import Language.Haskell.TH.Syntax
embedRecords
:: (Lift a, FromRecord a)
=> Proxy a
-> FilePath
-> ExpQ
embedRecords proxy path = do
content <- runIO $ BSL.readFile path
let
Right rows = decode HasHeader content
Right xs = traverse (fmap cast . runParser . parseRecord) $ toList rows
ListE <$> Prelude.mapM lift xs
where
cast x = x `asProxyTypeOf` proxy
embedNamedRecords
:: (Lift a, FromNamedRecord a)
=> Proxy a
-> FilePath
-> ExpQ
embedNamedRecords proxy path = do
content <- runIO $ BSL.readFile path
let
Right (_, rows) = decodeByName content
Right xs = traverse (fmap cast . runParser . parseNamedRecord) $ toList rows
ListE <$> Prelude.mapM lift xs
where
cast x = x `asProxyTypeOf` proxy