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 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
|
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE UndecidableInstances #-} -- FIXME
module Database.Persist.Query.GenericSql
( PersistQuery (..)
, SqlPersist (..)
, filterClauseNoWhere
, filterClauseNoWhereOrNull
, getFiltsValues
, selectSourceConn
, dummyFromFilts
, orderClause
)
where
import qualified Prelude
import Prelude hiding ((++), unlines, concat, show)
import Data.Text (Text, pack, concat)
import Database.Persist.Store
import Database.Persist.Query.Internal
import Database.Persist.GenericSql
import Database.Persist.GenericSql.Internal
import qualified Database.Persist.GenericSql.Raw as R
import Control.Monad.IO.Class
import Control.Monad.Trans.Class
import Control.Monad.Trans.Reader
import Control.Monad.Trans.Control (MonadBaseControl)
import qualified Data.Conduit as C
import qualified Data.Conduit.List as CL
import Control.Monad.Trans.Resource (transResourceT)
import Control.Exception (throwIO)
import qualified Data.Text as T
import Database.Persist.EntityDef
import Data.Monoid (Monoid, mappend, mconcat)
-- orphaned instance for convenience of modularity
instance (C.MonadThrow m, MonadIO m, C.MonadUnsafeIO m, MonadBaseControl IO m) => PersistQuery SqlPersist m where
update _ [] = return ()
update k upds = do
conn <- SqlPersist ask
let go'' n Assign = n ++ "=?"
go'' n Add = concat [n, "=", n, "+?"]
go'' n Subtract = concat [n, "=", n, "-?"]
go'' n Multiply = concat [n, "=", n, "*?"]
go'' n Divide = concat [n, "=", n, "/?"]
let go' (x, pu) = go'' (escapeName conn x) pu
let sql = concat
[ "UPDATE "
, escapeName conn $ entityDB t
, " SET "
, T.intercalate "," $ map (go' . go) upds
, " WHERE id=?"
]
execute' sql $
map updatePersistValue upds `mappend` [unKey k]
where
t = entityDef $ dummyFromKey k
go x = (fieldDB $ updateFieldDef x, updateUpdate x)
count filts = do
conn <- SqlPersist ask
let wher = if null filts
then ""
else filterClause False conn filts
let sql = concat
[ "SELECT COUNT(*) FROM "
, escapeName conn $ entityDB t
, wher
]
C.runResourceT $ R.withStmt sql (getFiltsValues conn filts) C.$$ do
Just [PersistInt64 i] <- CL.head
return $ fromIntegral i
where
t = entityDef $ dummyFromFilts filts
selectSource filts opts = C.PipeM
(do
conn <- lift $ SqlPersist ask
return $ R.withStmt (sql conn) (getFiltsValues conn filts) C.$= CL.mapM parse)
(return ())
where
(limit, offset, orders) = limitOffsetOrder opts
parse vals =
case fromPersistValues' vals of
Left s -> liftIO $ throwIO $ PersistMarshalError s
Right row -> return row
t = entityDef $ dummyFromFilts filts
fromPersistValues' (PersistInt64 x:xs) = do
case fromPersistValues xs of
Left e -> Left e
Right xs' -> Right (Entity (Key $ PersistInt64 x) xs')
fromPersistValues' _ = Left "error in fromPersistValues'"
wher conn = if null filts
then ""
else filterClause False conn filts
ord conn =
case map (orderClause False conn) orders of
[] -> ""
ords -> " ORDER BY " ++ T.intercalate "," ords
lim conn = case (limit, offset) of
(0, 0) -> ""
(0, _) -> T.cons ' ' $ noLimit conn
(_, _) -> " LIMIT " ++ show limit
off = if offset == 0
then ""
else " OFFSET " ++ show offset
cols conn = T.intercalate ","
$ (escapeName conn $ entityID t)
: map (escapeName conn . fieldDB) (entityFields t)
sql conn = concat
[ "SELECT "
, cols conn
, " FROM "
, escapeName conn $ entityDB t
, wher conn
, ord conn
, lim conn
, off
]
selectKeys filts = C.PipeM
(do
conn <- lift $ SqlPersist ask
return $ R.withStmt (sql conn) (getFiltsValues conn filts) C.$= CL.mapM parse)
(return ())
where
parse [PersistInt64 i] = return $ Key $ PersistInt64 i
parse y = liftIO $ throwIO $ PersistMarshalError $ "Unexpected in selectKeys: " ++ show y
t = entityDef $ dummyFromFilts filts
wher conn = if null filts
then ""
else filterClause False conn filts
sql conn = concat
[ "SELECT "
, escapeName conn $ entityID t
, " FROM "
, escapeName conn $ entityDB t
, wher conn
]
deleteWhere filts = do
conn <- SqlPersist ask
let t = entityDef $ dummyFromFilts filts
let wher = if null filts
then ""
else filterClause False conn filts
sql = concat
[ "DELETE FROM "
, escapeName conn $ entityDB t
, wher
]
execute' sql $ getFiltsValues conn filts
updateWhere _ [] = return ()
updateWhere filts upds = do
conn <- SqlPersist ask
let wher = if null filts
then ""
else filterClause False conn filts
let sql = concat
[ "UPDATE "
, escapeName conn $ entityDB t
, " SET "
, T.intercalate "," $ map (go' conn . go) upds
, wher
]
let dat = map updatePersistValue upds `mappend`
getFiltsValues conn filts
execute' sql dat
where
t = entityDef $ dummyFromFilts filts
go'' n Assign = n ++ "=?"
go'' n Add = concat [n, "=", n, "+?"]
go'' n Subtract = concat [n, "=", n, "-?"]
go'' n Multiply = concat [n, "=", n, "*?"]
go'' n Divide = concat [n, "=", n, "/?"]
go' conn (x, pu) = go'' (escapeName conn x) pu
go x = (fieldDB $ updateFieldDef x, updateUpdate x)
updatePersistValue :: Update v -> PersistValue
updatePersistValue (Update _ v _) = toPersistValue v
dummyFromKey :: Key SqlPersist v -> v
dummyFromKey _ = error "dummyFromKey"
execute' :: MonadIO m => Text -> [PersistValue] -> SqlPersist m ()
execute' = R.execute
getFiltsValues :: forall val. PersistEntity val => Connection -> [Filter val] -> [PersistValue]
getFiltsValues conn = snd . filterClauseHelper False False conn OrNullNo
filterClause :: PersistEntity val
=> Bool -- ^ include table name?
-> Connection
-> [Filter val]
-> Text
filterClause b c = fst . filterClauseHelper b True c OrNullNo
data OrNull = OrNullYes | OrNullNo
filterClauseNoWhere :: PersistEntity val
=> Bool -- ^ include table name?
-> Connection
-> [Filter val]
-> Text
filterClauseNoWhere b c = fst . filterClauseHelper b False c OrNullNo
filterClauseNoWhereOrNull :: PersistEntity val
=> Bool -- ^ include table name?
-> Connection
-> [Filter val]
-> Text
filterClauseNoWhereOrNull b c = fst . filterClauseHelper b False c OrNullYes
filterClauseHelper :: PersistEntity val
=> Bool -- ^ include table name?
-> Bool -- ^ include WHERE?
-> Connection
-> OrNull
-> [Filter val]
-> (Text, [PersistValue])
filterClauseHelper includeTable includeWhere conn orNull filters =
(if not (T.null sql) && includeWhere
then " WHERE " ++ sql
else sql, vals)
where
(sql, vals) = combineAND filters
combineAND = combine " AND "
combine s fs =
(T.intercalate s $ map wrapP a, mconcat b)
where
(a, b) = unzip $ map go fs
wrapP x = T.concat ["(", x, ")"]
go (FilterAnd []) = ("1=1", [])
go (FilterAnd fs) = combineAND fs
go (FilterOr []) = ("1=0", [])
go (FilterOr fs) = combine " OR " fs
go (Filter field value pfilter) =
case (isNull, pfilter, varCount) of
(True, Eq, _) -> (name ++ " IS NULL", [])
(True, Ne, _) -> (name ++ " IS NOT NULL", [])
(False, Ne, _) -> (T.concat
[ "("
, name
, " IS NULL OR "
, name
, " <> "
, qmarks
, ")"
], notNullVals)
-- We use 1=2 (and below 1=1) to avoid using TRUE and FALSE, since
-- not all databases support those words directly.
(_, In, 0) -> ("1=2" ++ orNullSuffix, [])
(False, In, _) -> (name ++ " IN " ++ qmarks ++ orNullSuffix, allVals)
(True, In, _) -> (T.concat
[ "("
, name
, " IS NULL OR "
, name
, " IN "
, qmarks
, ")"
], notNullVals)
(_, NotIn, 0) -> ("1=1", [])
(False, NotIn, _) -> (T.concat
[ "("
, name
, " IS NULL OR "
, name
, " NOT IN "
, qmarks
, ")"
], notNullVals)
(True, NotIn, _) -> (T.concat
[ "("
, name
, " IS NOT NULL AND "
, name
, " NOT IN "
, qmarks
, ")"
], notNullVals)
_ -> (name ++ showSqlFilter pfilter ++ "?" ++ orNullSuffix, allVals)
where
filterValueToPersistValues :: forall a. PersistField a => Either a [a] -> [PersistValue]
filterValueToPersistValues v = map toPersistValue $ either return id v
orNullSuffix =
case orNull of
OrNullYes -> concat [" OR ", name, " IS NULL"]
OrNullNo -> ""
isNull = any (== PersistNull) allVals
notNullVals = filter (/= PersistNull) allVals
allVals = filterValueToPersistValues value
tn = escapeName conn $ entityDB
$ entityDef $ dummyFromFilts [Filter field value pfilter]
name =
(if includeTable
then ((tn ++ ".") ++)
else id)
$ escapeName conn $ fieldDB $ persistFieldDef field
qmarks = case value of
Left _ -> "?"
Right x ->
let x' = filter (/= PersistNull) $ map toPersistValue x
in "(" ++ T.intercalate "," (map (const "?") x') ++ ")"
varCount = case value of
Left _ -> 1
Right x -> length x
showSqlFilter Eq = "="
showSqlFilter Ne = "++"
showSqlFilter Gt = ">"
showSqlFilter Lt = "<"
showSqlFilter Ge = ">="
showSqlFilter Le = "<="
showSqlFilter In = " IN "
showSqlFilter NotIn = " NOT IN "
showSqlFilter (BackendSpecificFilter s) = s
infixr 5 ++
(++) :: Text -> Text -> Text
(++) = mappend
show :: Show a => a -> Text
show = pack . Prelude.show
-- | Equivalent to 'selectSource', but instead of getting the connection from
-- the environment inside a 'SqlPersist' monad, provide an explicit
-- 'Connection'. This can allow you to use the returned 'Source' in an
-- arbitrary monad.
selectSourceConn :: (PersistEntity val, SqlPersist ~ PersistEntityBackend val, C.MonadThrow m, C.MonadUnsafeIO m, MonadIO m, MonadBaseControl IO m)
=> Connection
-> [Filter val]
-> [SelectOpt val]
-> C.Source (C.ResourceT m) (Entity val)
selectSourceConn conn fs opts =
C.transPipe (transResourceT $ flip runSqlConn conn) (selectSource fs opts)
dummyFromFilts :: [Filter v] -> v
dummyFromFilts _ = error "dummyFromFilts"
orderClause :: PersistEntity val
=> Bool -- ^ include the table name
-> Connection
-> SelectOpt val
-> Text
orderClause includeTable conn o =
case o of
Asc x -> name $ persistFieldDef x
Desc x -> name (persistFieldDef x) ++ " DESC"
_ -> error $ "orderClause: expected Asc or Desc, not limit or offset"
where
dummyFromOrder :: SelectOpt a -> a
dummyFromOrder _ = undefined
tn = escapeName conn $ entityDB $ entityDef $ dummyFromOrder o
name x =
(if includeTable
then ((tn ++ ".") ++)
else id)
$ escapeName conn $ fieldDB x
|