我有一张桌子被定义为
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 = "[email protected]" }
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)
但我得到了错误
Data.Binary.Get.runGet at position 0: not enough bytes
。查询
SELECT * FROM users;
给予
id | val
----+-----
1 | \x
我不知道怎么把
ByteString
s映射到'BYTEA's。根据docs一切都应该正常。我做错什么了? 最佳答案
换线固定
execute conn "INSERT INTO users(val) values(?)" $ Only encoded
具有
execute conn "INSERT INTO users(val) values(?)" $ Only $ Binary encoded
因为
toField(ByteString)
产生Escape
而toField(Binary ByteString)
产生EscapeByteA
关于postgresql - 如何在Haskell中使用postgresql-simple插入bytea值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52198898/