如何在Haskell中使用postgresql simple插入bytea值
我有一个表定义为如何在Haskell中使用postgresql simple插入bytea值,postgresql,haskell,Postgresql,Haskell,我有一个表定义为 CREATE TABLE users (id SERIAL PRIMARY KEY, val BYTEA); 然后我想用binary序列化我的数据结构并存储在表中,然后检索并反序列化回来 {-# LANGUAGE OverloadedStrings, DeriveAnyClass #-} import Control.Monad (forM_) import Data.Binary (encode, decode, Binary) import Database.Postgr
CREATE TABLE users (id SERIAL PRIMARY KEY, val BYTEA);
然后我想用binary
序列化我的数据结构并存储在表中,然后检索并反序列化回来
{-# LANGUAGE OverloadedStrings, DeriveAnyClass #-}
import Control.Monad (forM_)
import Data.Binary (encode, decode, Binary)
import Database.PostgreSQL.Simple
import GHC.Generics (Generic)
data User = { name :: Text, email :: Text } deriving (Show, Generic, Binary)
main = do
conn <- connect --...
let encoded = encode User {name = "me", email = "me@home.net" }
execute conn "INSERT INTO users(val) values(?)" $ Only encoded
rs <- query_ conn "SELECT id, val FROM users"
forM_ rs $ \(id,val) ->
putStrLn $ (show (id :: Int)) ++ ": " ++ show (decode val :: User)
给予
我不知道如何将
ByteString
s映射到'BYTEA's。根据计划,一切都应该是好的。我做错了什么?通过更换线路进行修复
execute conn "INSERT INTO users(val) values(?)" $ Only encoded
与
这是因为
toField(ByteString)
产生Escape
,而toField(Binary ByteString)
产生EscapeByteA
似乎问题在于引导\NUL
s。
id | val
----+-----
1 | \x
execute conn "INSERT INTO users(val) values(?)" $ Only encoded
execute conn "INSERT INTO users(val) values(?)" $ Only $ Binary encoded