module Database.Persist.Query.Internal
(
PersistQuery (..)
, selectList
, SelectOpt (..)
, limitOffsetOrder
, Filter (..)
, PersistUpdate (..)
, Update (..)
, updateFieldDef
, deleteCascadeWhere
) where
import Database.Persist.Store
import Database.Persist.EntityDef
import qualified Data.Conduit as C
import qualified Data.Conduit.List as CL
class PersistStore b m => PersistQuery b m where
update :: PersistEntity val => Key b val -> [Update val] -> b m ()
updateWhere :: PersistEntity val => [Filter val] -> [Update val] -> b m ()
deleteWhere :: PersistEntity val => [Filter val] -> b m ()
selectSource
:: PersistEntity val
=> [Filter val]
-> [SelectOpt val]
-> C.Source (b m) (Entity b val)
selectFirst :: PersistEntity val
=> [Filter val]
-> [SelectOpt val]
-> b m (Maybe (Entity b val))
selectFirst filts opts = C.runResourceT
$ selectSource filts ((LimitTo 1):opts) C.$$ CL.head
selectKeys :: PersistEntity val
=> [Filter val]
-> C.Source (b m) (Key b val)
count :: PersistEntity val => [Filter val] -> b m Int
data Filter v = forall typ. PersistField typ => Filter
{ filterField :: EntityField v typ
, filterValue :: Either typ [typ]
, filterFilter :: PersistFilter
}
| FilterAnd [Filter v]
| FilterOr [Filter v]
data SelectOpt v = forall typ. Asc (EntityField v typ)
| forall typ. Desc (EntityField v typ)
| OffsetBy Int
| LimitTo Int
selectList :: (PersistEntity val, PersistQuery b m)
=> [Filter val]
-> [SelectOpt val]
-> b m [Entity b val]
selectList a b = C.runResourceT $ selectSource a b C.$$ CL.consume
data PersistUpdate = Assign | Add | Subtract | Multiply | Divide
deriving (Read, Show, Enum, Bounded)
data Update v = forall typ. PersistField typ => Update
{ updateField :: EntityField v typ
, updateValue :: typ
, updateUpdate :: PersistUpdate
}
limitOffsetOrder :: PersistEntity val => [SelectOpt val] -> (Int, Int, [SelectOpt val])
limitOffsetOrder opts =
foldr go (0, 0, []) opts
where
go (LimitTo l) (_, b, c) = (l, b ,c)
go (OffsetBy o) (a, _, c) = (a, o, c)
go x (a, b, c) = (a, b, x : c)
updateFieldDef :: PersistEntity v => Update v -> FieldDef
updateFieldDef (Update f _ _) = persistFieldDef f
deleteCascadeWhere :: (DeleteCascade a b m, PersistQuery b m)
=> [Filter a] -> b m ()
deleteCascadeWhere filts = do
C.runResourceT $ selectKeys filts C.$$ CL.mapM_ deleteCascade