@@ -21,13 +21,10 @@ module Database.PostgreSQL.Simple.ToField
2121 , inQuotes
2222 ) where
2323
24−import Blaze.ByteString.Builder (Builder, fromByteString, fromLazyByteString,
25− toByteString)
24+import Blaze.ByteString.Builder (Builder, fromByteString, toByteString)
2625import Blaze.ByteString.Builder.Char8 (fromChar)
2726import Blaze.Text (integral, double, float)
2827import Data.ByteString (ByteString)
29−import qualified Data.ByteString.Base16 as B16
30−import qualified Data.ByteString.Base16.Lazy as L16
3128import Data.Int (Int8, Int16, Int32, Int64)
3229import Data.List (intersperse)
3330import Data.Monoid (mappend)
@@ -58,14 +55,18 @@ data Action =
5855 -- ^ Escape and enclose in quotes before substituting. Use for all
5956 -- text-like types, and anything else that may contain unsafe
6057 -- characters when rendered.
58+ | EscapeBytea ByteString
59+ -- ^ Escape binary data for use as a @bytea@ literal. Include surrounding
60+ -- quotes. This is used by the 'Binary' newtype wrapper.
6161 | Many [Action]
6262 -- ^ Concatenate a series of rendering actions.
6363 deriving (Typeable)
6464
6565instance Show Action where
66− show (Plain b) = "Plain " ++ show (toByteString b)
67− show (Escape b) = "Escape " ++ show b
68− show (Many b) = "Many " ++ show b
66+ show (Plain b) = "Plain " ++ show (toByteString b)
67+ show (Escape b) = "Escape " ++ show b
68+ show (EscapeBytea b) = "EscapeBytea " ++ show b
69+ show (Many b) = "Many " ++ show b
6970
7071-- | A type that may be used as a single parameter to a SQL query.
7172class ToField a where
@@ -88,16 +89,6 @@ instance (ToField a) => ToField (In [a]) where
8889 (intersperse (Plain (fromChar ',')) . map toField $ xs) ++
8990 [Plain (fromChar ')')]
9091
91−instance ToField (Binary SB.ByteString) where
92− toField (Binary bs) = Plain $ fromByteString "'\\x" `mappend`
93− fromByteString (B16.encode bs) `mappend`
94− fromChar '\''
95−
96−instance ToField (Binary LB.ByteString) where
97− toField (Binary bs) = Plain $ fromByteString "'\\x" `mappend`
98− fromLazyByteString (L16.encode bs) `mappend`
99− fromChar '\''
100−
10192renderNull :: Action
10293renderNull = Plain (fromByteString "null")
10394
@@ -168,6 +159,14 @@ instance ToField Double where
168159 | otherwise = Plain (double v)
169160 {-# INLINE toField #-}
170161
162+instance ToField (Binary SB.ByteString) where
163+ toField (Binary bs) = EscapeBytea bs
164+ {-# INLINE toField #-}
165+
166+instance ToField (Binary LB.ByteString) where
167+ toField (Binary bs) = (EscapeBytea . SB.concat . LB.toChunks) bs
168+ {-# INLINE toField #-}
169+
171170instance ToField SB.ByteString where
172171 toField = Escape
173172 {-# INLINE toField #-}