/
ToField.hs
362 lines (301 loc) · 12 KB
/
ToField.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
{-# LANGUAGE CPP, DeriveDataTypeable, DeriveFunctor #-}
{-# LANGUAGE FlexibleInstances, TypeSynonymInstances #-}
------------------------------------------------------------------------------
-- |
-- Module: Database.PostgreSQL.Simple.ToField
-- Copyright: (c) 2011 MailRank, Inc.
-- (c) 2011-2012 Leon P Smith
-- License: BSD3
-- Maintainer: Leon P Smith <leon@melding-monads.com>
-- Stability: experimental
--
-- The 'ToField' typeclass, for rendering a parameter to a SQL query.
--
------------------------------------------------------------------------------
module Database.PostgreSQL.Simple.ToField
(
Action(..)
, ToField(..)
, toJSONField
, inQuotes
) where
import Blaze.ByteString.Builder (Builder, fromByteString, toByteString)
import Blaze.ByteString.Builder.Char8 (fromChar)
import Blaze.Text (integral, double, float)
import qualified Data.Aeson as JSON
import Data.ByteString (ByteString)
import Data.Int (Int8, Int16, Int32, Int64)
import Data.List (intersperse)
import Data.Monoid (mappend)
import Data.Time (Day, TimeOfDay, LocalTime, UTCTime, ZonedTime, DiffTime)
import Data.Typeable (Typeable)
import Data.Word (Word, Word8, Word16, Word32, Word64)
import {-# SOURCE #-} Database.PostgreSQL.Simple.ToRow
import Database.PostgreSQL.Simple.Types
import qualified Blaze.ByteString.Builder.Char.Utf8 as Utf8
import qualified Data.ByteString as SB
import qualified Data.ByteString.Lazy as LB
import qualified Data.Text as ST
import qualified Data.Text.Encoding as ST
import qualified Data.Text.Lazy as LT
import qualified Data.Text.Lazy.Builder as LT
import Data.UUID (UUID)
import qualified Data.UUID as UUID
import Data.Vector (Vector)
import qualified Data.Vector as V
import qualified Database.PostgreSQL.LibPQ as PQ
import Database.PostgreSQL.Simple.Time
import Data.Scientific (Scientific)
#if MIN_VERSION_scientific(0,3,0)
import Data.Text.Lazy.Builder.Scientific (scientificBuilder)
#else
import Data.Scientific (scientificBuilder)
#endif
-- | How to render an element when substituting it into a query.
data Action =
Plain Builder
-- ^ Render without escaping or quoting. Use for non-text types
-- such as numbers, when you are /certain/ that they will not
-- introduce formatting vulnerabilities via use of characters such
-- as spaces or \"@'@\".
| Escape ByteString
-- ^ Escape and enclose in quotes before substituting. Use for all
-- text-like types, and anything else that may contain unsafe
-- characters when rendered.
| EscapeByteA ByteString
-- ^ Escape binary data for use as a @bytea@ literal. Include surrounding
-- quotes. This is used by the 'Binary' newtype wrapper.
| EscapeIdentifier ByteString
-- ^ Escape before substituting. Use for all sql identifiers like
-- table, column names, etc. This is used by the 'Identifier' newtype
-- wrapper.
| Many [Action]
-- ^ Concatenate a series of rendering actions.
deriving (Typeable)
instance Show Action where
show (Plain b) = "Plain " ++ show (toByteString b)
show (Escape b) = "Escape " ++ show b
show (EscapeByteA b) = "EscapeByteA " ++ show b
show (EscapeIdentifier b) = "EscapeIdentifier " ++ show b
show (Many b) = "Many " ++ show b
-- | A type that may be used as a single parameter to a SQL query.
class ToField a where
toField :: a -> Action
-- ^ Prepare a value for substitution into a query string.
instance ToField Action where
toField a = a
{-# INLINE toField #-}
instance (ToField a) => ToField (Maybe a) where
toField Nothing = renderNull
toField (Just a) = toField a
{-# INLINE toField #-}
instance (ToField a) => ToField (In [a]) where
toField (In []) = Plain $ fromByteString "(null)"
toField (In xs) = Many $
Plain (fromChar '(') :
(intersperse (Plain (fromChar ',')) . map toField $ xs) ++
[Plain (fromChar ')')]
renderNull :: Action
renderNull = Plain (fromByteString "null")
instance ToField Null where
toField _ = renderNull
{-# INLINE toField #-}
instance ToField Default where
toField _ = Plain (fromByteString "default")
{-# INLINE toField #-}
instance ToField Bool where
toField True = Plain (fromByteString "true")
toField False = Plain (fromByteString "false")
{-# INLINE toField #-}
instance ToField Int8 where
toField = Plain . integral
{-# INLINE toField #-}
instance ToField Int16 where
toField = Plain . integral
{-# INLINE toField #-}
instance ToField Int32 where
toField = Plain . integral
{-# INLINE toField #-}
instance ToField Int where
toField = Plain . integral
{-# INLINE toField #-}
instance ToField Int64 where
toField = Plain . integral
{-# INLINE toField #-}
instance ToField Integer where
toField = Plain . integral
{-# INLINE toField #-}
instance ToField Word8 where
toField = Plain . integral
{-# INLINE toField #-}
instance ToField Word16 where
toField = Plain . integral
{-# INLINE toField #-}
instance ToField Word32 where
toField = Plain . integral
{-# INLINE toField #-}
instance ToField Word where
toField = Plain . integral
{-# INLINE toField #-}
instance ToField Word64 where
toField = Plain . integral
{-# INLINE toField #-}
instance ToField PQ.Oid where
toField = Plain . integral . \(PQ.Oid x) -> x
{-# INLINE toField #-}
instance ToField Float where
toField v | isNaN v || isInfinite v = Plain (inQuotes (float v))
| otherwise = Plain (float v)
{-# INLINE toField #-}
instance ToField Double where
toField v | isNaN v || isInfinite v = Plain (inQuotes (double v))
| otherwise = Plain (double v)
{-# INLINE toField #-}
instance ToField Scientific where
toField x = toField (LT.toLazyText (scientificBuilder x))
{-# INLINE toField #-}
instance ToField (Binary SB.ByteString) where
toField (Binary bs) = EscapeByteA bs
{-# INLINE toField #-}
instance ToField (Binary LB.ByteString) where
toField (Binary bs) = (EscapeByteA . SB.concat . LB.toChunks) bs
{-# INLINE toField #-}
instance ToField Identifier where
toField (Identifier bs) = EscapeIdentifier (ST.encodeUtf8 bs)
{-# INLINE toField #-}
instance ToField QualifiedIdentifier where
toField (QualifiedIdentifier (Just s) t) =
Many [ EscapeIdentifier (ST.encodeUtf8 s)
, Plain (fromChar '.')
, EscapeIdentifier (ST.encodeUtf8 t)
]
toField (QualifiedIdentifier Nothing t) =
EscapeIdentifier (ST.encodeUtf8 t)
{-# INLINE toField #-}
instance ToField SB.ByteString where
toField = Escape
{-# INLINE toField #-}
instance ToField LB.ByteString where
toField = toField . SB.concat . LB.toChunks
{-# INLINE toField #-}
instance ToField ST.Text where
toField = Escape . ST.encodeUtf8
{-# INLINE toField #-}
instance ToField [Char] where
toField = Escape . toByteString . Utf8.fromString
{-# INLINE toField #-}
instance ToField LT.Text where
toField = toField . LT.toStrict
{-# INLINE toField #-}
instance ToField UTCTime where
toField = Plain . inQuotes . utcTimeToBuilder
{-# INLINE toField #-}
instance ToField ZonedTime where
toField = Plain . inQuotes . zonedTimeToBuilder
{-# INLINE toField #-}
instance ToField LocalTime where
toField = Plain . inQuotes . localTimeToBuilder
{-# INLINE toField #-}
instance ToField Day where
toField = Plain . inQuotes . dayToBuilder
{-# INLINE toField #-}
instance ToField TimeOfDay where
toField = Plain . inQuotes . timeOfDayToBuilder
{-# INLINE toField #-}
instance ToField UTCTimestamp where
toField = Plain . inQuotes . utcTimestampToBuilder
{-# INLINE toField #-}
instance ToField ZonedTimestamp where
toField = Plain . inQuotes . zonedTimestampToBuilder
{-# INLINE toField #-}
instance ToField LocalTimestamp where
toField = Plain . inQuotes . localTimestampToBuilder
{-# INLINE toField #-}
instance ToField Date where
toField = Plain . inQuotes . dateToBuilder
{-# INLINE toField #-}
instance ToField DiffTime where
toField = Plain . inQuotes . diffTimeToBuilder
{-# INLINE toField #-}
instance (ToField a) => ToField (PGArray a) where
toField xs = Many $
Plain (fromByteString "ARRAY[") :
(intersperse (Plain (fromChar ',')) . map toField $ fromPGArray xs) ++
[Plain (fromChar ']')]
-- Because the ARRAY[...] input syntax is being used, it is possible
-- that the use of type-specific separator characters is unnecessary.
instance (ToField a) => ToField (Vector a) where
toField = toField . PGArray . V.toList
instance ToField UUID where
toField = Plain . inQuotes . fromByteString . UUID.toASCIIBytes
instance ToField JSON.Value where
toField = toField . JSON.encode
-- | Convert a Haskell value to a JSON 'JSON.Value' using
-- 'JSON.toJSON' and convert that to a field using 'toField'.
--
-- This can be used as the default implementation for the 'toField'
-- method for Haskell types that have a JSON representation in
-- PostgreSQL.
toJSONField :: JSON.ToJSON a => a -> Action
toJSONField = toField . JSON.toJSON
-- | Surround a string with single-quote characters: \"@'@\"
--
-- This function /does not/ perform any other escaping.
inQuotes :: Builder -> Builder
inQuotes b = quote `mappend` b `mappend` quote
where quote = Utf8.fromChar '\''
interleaveFoldr :: (a -> [b] -> [b]) -> b -> [b] -> [a] -> [b]
interleaveFoldr f b bs as = foldr (\a bs -> b : f a bs) bs as
{-# INLINE interleaveFoldr #-}
instance ToRow a => ToField (Values a) where
toField (Values types rows) =
case rows of
[] -> case types of
[] -> error norows
(_:_) -> values $ typedRow (repeat (lit "null"))
types
[lit " LIMIT 0)"]
(_:_) -> case types of
[] -> values $ untypedRows rows [litC ')']
(_:_) -> values $ typedRows rows types [litC ')']
where
funcname = "Database.PostgreSQL.Simple.toField :: Values a -> Action"
norows = funcname ++ " either values or types must be non-empty"
emptyrow = funcname ++ " each row must contain at least one column"
lit = Plain . fromByteString
litC = Plain . fromChar
values x = Many (lit "(VALUES ": x)
typedField :: (Action, QualifiedIdentifier) -> [Action] -> [Action]
typedField (val,typ) rest = val : lit "::" : toField typ : rest
typedRow :: [Action] -> [QualifiedIdentifier] -> [Action] -> [Action]
typedRow (val:vals) (typ:typs) rest =
litC '(' :
typedField (val,typ) ( interleaveFoldr
typedField
(litC ',')
(litC ')' : rest)
(zip vals typs) )
typedRow _ _ _ = error emptyrow
untypedRow :: [Action] -> [Action] -> [Action]
untypedRow (val:vals) rest =
litC '(' : val :
interleaveFoldr
(:)
(litC ',')
(litC ')' : rest)
vals
untypedRow _ _ = error emptyrow
typedRows :: ToRow a => [a] -> [QualifiedIdentifier] -> [Action] -> [Action]
typedRows [] _ _ = error funcname
typedRows (val:vals) types rest =
typedRow (toRow val) types (multiRows vals rest)
untypedRows :: ToRow a => [a] -> [Action] -> [Action]
untypedRows [] _ = error funcname
untypedRows (val:vals) rest =
untypedRow (toRow val) (multiRows vals rest)
multiRows :: ToRow a => [a] -> [Action] -> [Action]
multiRows vals rest = interleaveFoldr
(untypedRow . toRow)
(litC ',')
rest
vals