persistent-2.14.6.3: Type-safe, multi-backend data serialization.

Safe Haskell | None
Language | Haskell2010

Database.Persist.Class

Contents

- PersistStore
- PersistUnique
- PersistQuery
- PersistEntity
- PersistField
- PersistConfig
- Lifting
- PersistCore
- JSON utilities

Description

This module exports all of the type classes in `persistent` for operating on the database backends.

`persistent` offers methods that are abstract in the specific `backend` type. For SQL databases, this wil be `SqlBackend`. Other database backends will define their own types.

Methods and functions in this module have examples documented under an "Example Usage" thing, that you need to click on to expand.

Synopsis

- type PersistStore a = PersistStoreWrite a
- class (Show (BackendKey backend), Read (BackendKey backend), Eq (BackendKey backend), Ord (BackendKey backend), PersistCore backend, PersistField (BackendKey backend), ToJSON (BackendKey backend), FromJSON (BackendKey backend)) => PersistStoreRead backend where
  - get :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend) => Key record -> ReaderT backend m (Maybe record)
  - getMany :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend) => [Key record] -> ReaderT backend m (Map (Key record) record)
- class (Show (BackendKey backend), Read (BackendKey backend), Eq (BackendKey backend), Ord (BackendKey backend), PersistStoreRead backend, PersistField (BackendKey backend), ToJSON (BackendKey backend), FromJSON (BackendKey backend)) => PersistStoreWrite backend where
  - insert :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => record -> ReaderT backend m (Key record)
  - insert_ :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => record -> ReaderT backend m ()
  - insertMany :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => [record] -> ReaderT backend m [Key record]
  - insertMany_ :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => [record] -> ReaderT backend m ()
  - insertEntityMany :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend) => [Entity record] -> ReaderT backend m ()
  - insertKey :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend) => Key record -> record -> ReaderT backend m ()
  - repsert :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend) => Key record -> record -> ReaderT backend m ()
  - repsertMany :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend) => [(Key record, record)] -> ReaderT backend m ()
  - replace :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend) => Key record -> record -> ReaderT backend m ()
  - delete :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend) => Key record -> ReaderT backend m ()
  - update :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend) => Key record -> [Update record] -> ReaderT backend m ()
  - updateGet :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend) => Key record -> [Update record] -> ReaderT backend m record
- type PersistRecordBackend record backend = (PersistEntity record, PersistEntityBackend record ~ BaseBackend backend)
- getJust :: forall record backend (m :: Type -> Type). (PersistStoreRead backend, PersistRecordBackend record backend, MonadIO m) => Key record -> ReaderT backend m record
- getJustEntity :: forall record backend (m :: Type -> Type). (PersistEntityBackend record ~ BaseBackend backend, MonadIO m, PersistEntity record, PersistStoreRead backend) => Key record -> ReaderT backend m (Entity record)
- getEntity :: forall e backend (m :: Type -> Type). (PersistStoreRead backend, PersistRecordBackend e backend, MonadIO m) => Key e -> ReaderT backend m (Maybe (Entity e))
- belongsTo :: forall ent1 ent2 backend (m :: Type -> Type). (PersistStoreRead backend, PersistEntity ent1, PersistRecordBackend ent2 backend, MonadIO m) => (ent1 -> Maybe (Key ent2)) -> ent1 -> ReaderT backend m (Maybe ent2)
- belongsToJust :: forall ent1 ent2 backend (m :: Type -> Type). (PersistStoreRead backend, PersistEntity ent1, PersistRecordBackend ent2 backend, MonadIO m) => (ent1 -> Key ent2) -> ent1 -> ReaderT backend m ent2
- class SafeToInsert a
- insertEntity :: forall e backend (m :: Type -> Type). (PersistStoreWrite backend, PersistRecordBackend e backend, SafeToInsert e, MonadIO m, HasCallStack) => e -> ReaderT backend m (Entity e)
- insertRecord :: forall record backend (m :: Type -> Type). (PersistEntityBackend record ~ BaseBackend backend, PersistEntity record, MonadIO m, PersistStoreWrite backend, SafeToInsert record, HasCallStack) => record -> ReaderT backend m record
- type PersistUnique a = PersistUniqueWrite a
- class PersistStoreRead backend => PersistUniqueRead backend where
  - getBy :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend) => Unique record -> ReaderT backend m (Maybe (Entity record))
  - existsBy :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend) => Unique record -> ReaderT backend m Bool
- class (PersistUniqueRead backend, PersistStoreWrite backend) => PersistUniqueWrite backend where
  - deleteBy :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend) => Unique record -> ReaderT backend m ()
  - insertUnique :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => record -> ReaderT backend m (Maybe (Key record))
  - insertUnique_ :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => record -> ReaderT backend m (Maybe ())
  - upsert :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend, OnlyOneUniqueKey record, SafeToInsert record) => record -> [Update record] -> ReaderT backend m (Entity record)
  - upsertBy :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => Unique record -> record -> [Update record] -> ReaderT backend m (Entity record)
  - putMany :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => [record] -> ReaderT backend m ()
- class PersistEntity record => OnlyOneUniqueKey record where
  - onlyUniqueP :: record -> Unique record
- class PersistEntity record => AtLeastOneUniqueKey record where
  - requireUniquesP :: record -> NonEmpty (Unique record)
- onlyOneUniqueDef :: (OnlyOneUniqueKey record, Monad proxy) => proxy record -> UniqueDef
- type NoUniqueKeysError ty = (('Text "The entity " ':<>: 'ShowType ty) ':<>: 'Text " does not have any unique keys.") ':$$: ('Text "The function you are trying to call requires a unique key " ':<>: 'Text "to be defined on the entity.")
- type MultipleUniqueKeysError ty = ((('Text "The entity " ':<>: 'ShowType ty) ':<>: 'Text " has multiple unique keys.") ':$$: ('Text "The function you are trying to call requires only a single " ':<>: 'Text "unique key.")) ':$$: (('Text "There is probably a variant of the function with 'By' " ':<>: 'Text "appended that will allow you to select a unique key ") ':<>: 'Text "for the operation.")
- getByValue :: forall record (m :: Type -> Type) backend. (MonadIO m, PersistUniqueRead backend, PersistRecordBackend record backend, AtLeastOneUniqueKey record) => record -> ReaderT backend m (Maybe (Entity record))
- insertBy :: forall record backend (m :: Type -> Type). (MonadIO m, PersistUniqueWrite backend, PersistRecordBackend record backend, AtLeastOneUniqueKey record, SafeToInsert record) => record -> ReaderT backend m (Either (Entity record) (Key record))
- insertUniqueEntity :: forall record backend (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend, PersistUniqueWrite backend, SafeToInsert record) => record -> ReaderT backend m (Maybe (Entity record))
- replaceUnique :: forall record backend (m :: Type -> Type). (MonadIO m, Eq (Unique record), PersistRecordBackend record backend, PersistUniqueWrite backend) => Key record -> record -> ReaderT backend m (Maybe (Unique record))
- checkUnique :: forall record backend (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend, PersistUniqueRead backend) => record -> ReaderT backend m (Maybe (Unique record))
- checkUniqueUpdateable :: forall record backend (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend, PersistUniqueRead backend) => Entity record -> ReaderT backend m (Maybe (Unique record))
- onlyUnique :: forall record backend (m :: Type -> Type). (MonadIO m, PersistUniqueWrite backend, PersistRecordBackend record backend, OnlyOneUniqueKey record) => record -> ReaderT backend m (Unique record)
- selectList :: forall record backend (m :: Type -> Type). (MonadIO m, PersistQueryRead backend, PersistRecordBackend record backend) => [Filter record] -> [SelectOpt record] -> ReaderT backend m [Entity record]
- selectKeys :: forall record backend (m :: Type -> Type). (PersistQueryRead backend, MonadResource m, PersistRecordBackend record backend, MonadReader backend m) => [Filter record] -> [SelectOpt record] -> ConduitM () (Key record) m ()
- type PersistQuery a = PersistQueryWrite a
- class (PersistCore backend, PersistStoreRead backend) => PersistQueryRead backend where
  - selectSourceRes :: forall record (m1 :: Type -> Type) (m2 :: Type -> Type). (PersistRecordBackend record backend, MonadIO m1, MonadIO m2) => [Filter record] -> [SelectOpt record] -> ReaderT backend m1 (Acquire (ConduitM () (Entity record) m2 ()))
  - selectFirst :: forall (m :: Type -> Type) record. (MonadIO m, PersistRecordBackend record backend) => [Filter record] -> [SelectOpt record] -> ReaderT backend m (Maybe (Entity record))
  - selectKeysRes :: forall (m1 :: Type -> Type) (m2 :: Type -> Type) record. (MonadIO m1, MonadIO m2, PersistRecordBackend record backend) => [Filter record] -> [SelectOpt record] -> ReaderT backend m1 (Acquire (ConduitM () (Key record) m2 ()))
  - count :: forall (m :: Type -> Type) record. (MonadIO m, PersistRecordBackend record backend) => [Filter record] -> ReaderT backend m Int
  - exists :: forall (m :: Type -> Type) record. (MonadIO m, PersistRecordBackend record backend) => [Filter record] -> ReaderT backend m Bool
- class (PersistQueryRead backend, PersistStoreWrite backend) => PersistQueryWrite backend where
  - updateWhere :: forall (m :: Type -> Type) record. (MonadIO m, PersistRecordBackend record backend) => [Filter record] -> [Update record] -> ReaderT backend m ()
  - deleteWhere :: forall (m :: Type -> Type) record. (MonadIO m, PersistRecordBackend record backend) => [Filter record] -> ReaderT backend m ()
- selectSource :: forall record backend (m :: Type -> Type). (PersistQueryRead backend, MonadResource m, PersistRecordBackend record backend, MonadReader backend m) => [Filter record] -> [SelectOpt record] -> ConduitM () (Entity record) m ()
- selectKeysList :: forall record backend (m :: Type -> Type). (MonadIO m, PersistQueryRead backend, PersistRecordBackend record backend) => [Filter record] -> [SelectOpt record] -> ReaderT backend m [Key record]
- class (PersistField (Key record), ToJSON (Key record), FromJSON (Key record), Show (Key record), Read (Key record), Eq (Key record), Ord (Key record)) => PersistEntity record where
  - type PersistEntityBackend record
  - data Key record
  - data EntityField record :: Type -> Type
  - data Unique record
  - keyToValues :: Key record -> [PersistValue]
  - keyFromValues :: [PersistValue] -> Either Text (Key record)
  - persistIdField :: EntityField record (Key record)
  - entityDef :: proxy record -> EntityDef
  - persistFieldDef :: EntityField record typ -> FieldDef
  - toPersistFields :: record -> [PersistValue]
  - fromPersistValues :: [PersistValue] -> Either Text record
  - tabulateEntityA :: Applicative f => (forall a. EntityField record a -> f a) -> f (Entity record)
  - persistUniqueKeys :: record -> [Unique record]
  - persistUniqueToFieldNames :: Unique record -> NonEmpty (FieldNameHS, FieldNameDB)
  - persistUniqueToValues :: Unique record -> [PersistValue]
  - fieldLens :: EntityField record field -> forall (f :: Type -> Type). Functor f => (field -> f field) -> Entity record -> f (Entity record)
  - keyFromRecordM :: Maybe (record -> Key record)
- tabulateEntity :: PersistEntity record => (forall a. EntityField record a -> a) -> Entity record
- class SymbolToField (sym :: Symbol) rec typ | sym rec -> typ where
  - symbolToField :: EntityField rec typ
- class PersistField a where
  - toPersistValue :: a -> PersistValue
  - fromPersistValue :: PersistValue -> Either Text a
- class PersistConfig c where
  - type PersistConfigBackend c :: (Type -> Type) -> Type -> Type
  - type PersistConfigPool c
  - loadConfig :: Value -> Parser c
  - applyEnv :: c -> IO c
  - createPoolConfig :: c -> IO (PersistConfigPool c)
  - runPool :: MonadUnliftIO m => c -> PersistConfigBackend c m a -> PersistConfigPool c -> m a
- entityValues :: PersistEntity record => Entity record -> [PersistValue]
- class HasPersistBackend backend where
  - type BaseBackend backend
  - persistBackend :: backend -> BaseBackend backend
- withBaseBackend :: forall backend (m :: Type -> Type) a. HasPersistBackend backend => ReaderT (BaseBackend backend) m a -> ReaderT backend m a
- class HasPersistBackend backend => IsPersistBackend backend
- liftPersist :: (MonadIO m, MonadReader backend m) => ReaderT backend IO b -> m b
- class BackendCompatible sup sub where
  - projectBackend :: sub -> sup
- withCompatibleBackend :: forall sup sub (m :: Type -> Type) a. BackendCompatible sup sub => ReaderT sup m a -> ReaderT sub m a
- class PersistCore backend where
  - data BackendKey backend
- class (PersistEntity record, PersistEntityBackend record ~ backend, PersistCore backend) => ToBackendKey backend record where
  - toBackendKey :: Key record -> BackendKey backend
  - fromBackendKey :: BackendKey backend -> Key record
- keyValueEntityToJSON :: (PersistEntity record, ToJSON record) => Entity record -> Value
- keyValueEntityFromJSON :: (PersistEntity record, FromJSON record) => Value -> Parser (Entity record)
- entityIdToJSON :: (PersistEntity record, ToJSON record) => Entity record -> Value
- entityIdFromJSON :: (PersistEntity record, FromJSON record) => Value -> Parser (Entity record)
- toPersistValueJSON :: ToJSON a => a -> PersistValue
- fromPersistValueJSON :: FromJSON a => PersistValue -> Either Text a

# PersistStore

The `PersistStore`, `PersistStoreRead`, and `PersistStoreWrite` type classes are used to define basic operations on the database. A database that implements these classes is capable of being used as a simple key-value store.

All the examples present here will be explained based on these schemas, datasets and functions:

# schema-1

    share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
    User
        name String
        age Int
        deriving Show
    |]

# dataset-1

    +----+-------+-----+
    | id | name  | age |
    +----+-------+-----+
    |  1 | SPJ   |  40 |
    +----+-------+-----+
    |  2 | Simon |  41 |
    +----+-------+-----+

type PersistStore a = PersistStoreWrite a #

A backwards-compatible alias for those that don't care about distinguishing between read and write queries. It signifies the assumption that, by default, a backend can write as well as read.

class (Show (BackendKey backend), Read (BackendKey backend), Eq (BackendKey backend), Ord (BackendKey backend), PersistCore backend, PersistField (BackendKey backend), ToJSON (BackendKey backend), FromJSON (BackendKey backend)) => PersistStoreRead backend where #

Minimal complete definition

get

Methods

get :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend) => Key record -> ReaderT backend m (Maybe record) #

Get a record by identifier, if available.

### Example usage

Expand

With schema-1 and dataset-1,

    getSpj :: MonadIO m => ReaderT SqlBackend m (Maybe User)
    getSpj = get spjId

    mspj <- getSpj

The above query when applied on dataset-1, will get this:

    +------+-----+
    | name | age |
    +------+-----+
    | SPJ  |  40 |
    +------+-----+

getMany :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend) => [Key record] -> ReaderT backend m (Map (Key record) record) #

Get many records by their respective identifiers, if available.

### Example usage

Expand

With schema-1 and dataset-1:

    getUsers :: MonadIO m => ReaderT SqlBackend m (Map (Key User) User)
    getUsers = getMany allkeys

    musers <- getUsers

The above query when applied on dataset-1, will get these records:

    +----+-------+-----+
    | id | name  | age |
    +----+-------+-----+
    |  1 | SPJ   |  40 |
    +----+-------+-----+
    |  2 | Simon |  41 |
    +----+-------+-----+

Since: 2.8.1

#### Instances

Instances details

PersistStoreRead SqlReadBackend # |
Instance details Defined in Database.Persist.Sql.Orphan.PersistStore Methods get :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlReadBackend) => Key record -> ReaderT SqlReadBackend m (Maybe record) # getMany :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlReadBackend) => [Key record] -> ReaderT SqlReadBackend m (Map (Key record) record) #
PersistStoreRead SqlWriteBackend # |
Instance details Defined in Database.Persist.Sql.Orphan.PersistStore Methods get :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlWriteBackend) => Key record -> ReaderT SqlWriteBackend m (Maybe record) # getMany :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlWriteBackend) => [Key record] -> ReaderT SqlWriteBackend m (Map (Key record) record) #
PersistStoreRead SqlBackend # |
Instance details Defined in Database.Persist.Sql.Orphan.PersistStore Methods get :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlBackend) => Key record -> ReaderT SqlBackend m (Maybe record) # getMany :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlBackend) => [Key record] -> ReaderT SqlBackend m (Map (Key record) record) #
(HasPersistBackend b, BackendCompatible b s, PersistStoreRead b) => PersistStoreRead (Compatible b s) # |
Instance details Defined in Database.Persist.Compatible.Types Methods get :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record (Compatible b s)) => Key record -> ReaderT (Compatible b s) m (Maybe record) # getMany :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record (Compatible b s)) => [Key record] -> ReaderT (Compatible b s) m (Map (Key record) record) #

class (Show (BackendKey backend), Read (BackendKey backend), Eq (BackendKey backend), Ord (BackendKey backend), PersistStoreRead backend, PersistField (BackendKey backend), ToJSON (BackendKey backend), FromJSON (BackendKey backend)) => PersistStoreWrite backend where #

Minimal complete definition

insert, insertKey, repsert, replace, delete, update

Methods

insert :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => record -> ReaderT backend m (Key record) #

Create a new record in the database, returning an automatically created key (in SQL an auto-increment id).

### Example usage

Expand

Using schema-1 and dataset-1, let's insert a new user `John`.

    insertJohn :: MonadIO m => ReaderT SqlBackend m (Key User)
    insertJohn = insert $ User "John" 30

    johnId <- insertJohn

The above query when applied on dataset-1, will produce this:

    +-----+------+-----+
    |id   |name  |age  |
    +-----+------+-----+
    |1    |SPJ   |40   |
    +-----+------+-----+
    |2    |Simon |41   |
    +-----+------+-----+
    |3    |John  |30   |
    +-----+------+-----+

insert_ :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => record -> ReaderT backend m () #

Same as `insert`, but doesn't return a `Key`.

### Example usage

Expand

with schema-1 and dataset-1,

    insertJohn :: MonadIO m => ReaderT SqlBackend m (Key User)
    insertJohn = insert_ $ User "John" 30

The above query when applied on dataset-1, will produce this:

    +-----+------+-----+
    |id   |name  |age  |
    +-----+------+-----+
    |1    |SPJ   |40   |
    +-----+------+-----+
    |2    |Simon |41   |
    +-----+------+-----+
    |3    |John  |30   |
    +-----+------+-----+

insertMany :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => [record] -> ReaderT backend m [Key record] #

Create multiple records in the database and return their `Key`s.

If you don't need the inserted `Key`s, use `insertMany_`.

The MongoDB and PostgreSQL backends insert all records and retrieve their keys in one database query.

The SQLite and MySQL backends use the slow, default implementation of `mapM insert`.

### Example usage

Expand

with schema-1 and dataset-1,

    insertUsers :: MonadIO m => ReaderT SqlBackend m [Key User]
    insertUsers = insertMany [User "John" 30, User "Nick" 32, User "Jane" 20]

    userIds <- insertUsers

The above query when applied on dataset-1, will produce this:

    +-----+------+-----+
    |id   |name  |age  |
    +-----+------+-----+
    |1    |SPJ   |40   |
    +-----+------+-----+
    |2    |Simon |41   |
    +-----+------+-----+
    |3    |John  |30   |
    +-----+------+-----+
    |4    |Nick  |32   |
    +-----+------+-----+
    |5    |Jane  |20   |
    +-----+------+-----+

insertMany_ :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => [record] -> ReaderT backend m () #

Same as `insertMany`, but doesn't return any `Key`s.

The MongoDB, PostgreSQL, SQLite and MySQL backends insert all records in one database query.

### Example usage

Expand

With schema-1 and dataset-1,

    insertUsers_ :: MonadIO m => ReaderT SqlBackend m ()
    insertUsers_ = insertMany_ [User "John" 30, User "Nick" 32, User "Jane" 20]

The above query when applied on dataset-1, will produce this:

    +-----+------+-----+
    |id   |name  |age  |
    +-----+------+-----+
    |1    |SPJ   |40   |
    +-----+------+-----+
    |2    |Simon |41   |
    +-----+------+-----+
    |3    |John  |30   |
    +-----+------+-----+
    |4    |Nick  |32   |
    +-----+------+-----+
    |5    |Jane  |20   |
    +-----+------+-----+

insertEntityMany :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend) => [Entity record] -> ReaderT backend m () #

Same as `insertMany_`, but takes an `Entity` instead of just a record.

Useful when migrating data from one entity to another and want to preserve ids.

The MongoDB, PostgreSQL, SQLite and MySQL backends insert all records in one database query.

### Example usage

Expand

With schema-1 and dataset-1,

    insertUserEntityMany :: MonadIO m => ReaderT SqlBackend m ()
    insertUserEntityMany = insertEntityMany [SnakeEntity, EvaEntity]

The above query when applied on dataset-1, will produce this:

    +-----+------+-----+
    |id   |name  |age  |
    +-----+------+-----+
    |1    |SPJ   |40   |
    +-----+------+-----+
    |2    |Simon |41   |
    +-----+------+-----+
    |3    |Snake |38   |
    +-----+------+-----+
    |4    |Eva   |38   |
    +-----+------+-----+

insertKey :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend) => Key record -> record -> ReaderT backend m () #

Create a new record in the database using the given key.

### Example usage

Expand

With schema-1 and dataset-1,

    insertAliceKey :: MonadIO m => Key User -> ReaderT SqlBackend m ()
    insertAliceKey key = insertKey key $ User "Alice" 20

    insertAliceKey $ UserKey {unUserKey = SqlBackendKey {unSqlBackendKey = 3}}

The above query when applied on dataset-1, will produce this:

    +-----+------+-----+
    |id   |name  |age  |
    +-----+------+-----+
    |1    |SPJ   |40   |
    +-----+------+-----+
    |2    |Simon |41   |
    +-----+------+-----+
    |3    |Alice |20   |
    +-----+------+-----+

repsert :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend) => Key record -> record -> ReaderT backend m () #

Put the record in the database with the given key. Unlike `replace`, if a record with the given key does not exist then a new record will be inserted.

### Example usage

Expand

We try to explain `upsertBy` using schema-1 and dataset-1.

First, we insert Philip to dataset-1.

    insertPhilip :: MonadIO m => ReaderT SqlBackend m (Key User)
    insertPhilip = insert $ User "Philip" 42

    philipId <- insertPhilip

This query will produce:

    +-----+------+-----+
    |id   |name  |age  |
    +-----+------+-----+
    |1    |SPJ   |40   |
    +-----+------+-----+
    |2    |Simon |41   |
    +-----+------+-----+
    |3    |Philip|42   |
    +-----+------+-----+

    repsertHaskell :: MonadIO m => Key record -> ReaderT SqlBackend m ()
    repsertHaskell id = repsert id $ User "Haskell" 81

    repsertHaskell philipId

This query will replace Philip's record with Haskell's one:

    +-----+-----------------+--------+
    |id   |name             |age     |
    +-----+-----------------+--------+
    |1    |SPJ              |40      |
    +-----+-----------------+--------+
    |2    |Simon            |41      |
    +-----+-----------------+--------+
    |3    |Philip -> Haskell|42 -> 81|
    +-----+-----------------+--------+

`repsert` inserts the given record if the key doesn't exist.

    repsertXToUnknown :: MonadIO m => ReaderT SqlBackend m ()
    repsertXToUnknown = repsert unknownId $ User "X" 999

For example, applying the above query to dataset-1 will produce this:

    +-----+------+-----+
    |id   |name  |age  |
    +-----+------+-----+
    |1    |SPJ   |40   |
    +-----+------+-----+
    |2    |Simon |41   |
    +-----+------+-----+
    |3    |X     |999  |
    +-----+------+-----+

repsertMany :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend) => [(Key record, record)] -> ReaderT backend m () #

Put many entities into the database.

Batch version of `repsert` for SQL backends.

Useful when migrating data from one entity to another and want to preserve ids.

### Example usage

Expand

With schema-1 and dataset-1,

    repsertManyUsers :: MonadIO m =>ReaderT SqlBackend m ()
    repsertManyusers = repsertMany [(simonId, User "Philip" 20), (unknownId999, User "Mr. X" 999)]

The above query when applied on dataset-1, will produce this:

    +-----+----------------+---------+
    |id   |name            |age      |
    +-----+----------------+---------+
    |1    |SPJ             |40       |
    +-----+----------------+---------+
    |2    |Simon -> Philip |41 -> 20 |
    +-----+----------------+---------+
    |999  |Mr. X           |999      |
    +-----+----------------+---------+

Since: 2.8.1

replace :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend) => Key record -> record -> ReaderT backend m () #

Replace the record in the database with the given key. Note that the result is undefined if such record does not exist, so you must use `insertKey` or `repsert` in these cases.

### Example usage

Expand

With schema-1 schama-1 and dataset-1,

    replaceSpj :: MonadIO m => User -> ReaderT SqlBackend m ()
    replaceSpj record = replace spjId record

The above query when applied on dataset-1, will produce this:

    +-----+------+-----+
    |id   |name  |age  |
    +-----+------+-----+
    |1    |Mike  |45   |
    +-----+------+-----+
    |2    |Simon |41   |
    +-----+------+-----+

delete :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend) => Key record -> ReaderT backend m () #

Delete a specific record by identifier. Does nothing if record does not exist.

### Example usage

Expand

With schema-1 and dataset-1,

    deleteSpj :: MonadIO m => ReaderT SqlBackend m ()
    deleteSpj = delete spjId

The above query when applied on dataset-1, will produce this:

    +-----+------+-----+
    |id   |name  |age  |
    +-----+------+-----+
    |2    |Simon |41   |
    +-----+------+-----+

update :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend) => Key record -> [Update record] -> ReaderT backend m () #

Update individual fields on a specific record.

### Example usage

Expand

With schema-1 and dataset-1,

    updateSpj :: MonadIO m => [Update User] -> ReaderT SqlBackend m ()
    updateSpj updates = update spjId updates

    updateSpj [UserAge +=. 100]

The above query when applied on dataset-1, will produce this:

    +-----+------+-----+
    |id   |name  |age  |
    +-----+------+-----+
    |1    |SPJ   |140  |
    +-----+------+-----+
    |2    |Simon |41   |
    +-----+------+-----+

updateGet :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend) => Key record -> [Update record] -> ReaderT backend m record #

Update individual fields on a specific record, and retrieve the updated value from the database.

Note that this function will throw an exception if the given key is not found in the database.

### Example usage

Expand

With schema-1 and dataset-1,

    updateGetSpj :: MonadIO m => [Update User] -> ReaderT SqlBackend m User
    updateGetSpj updates = updateGet spjId updates

    spj <- updateGetSpj [UserAge +=. 100]

The above query when applied on dataset-1, will produce this:

    +-----+------+-----+
    |id   |name  |age  |
    +-----+------+-----+
    |1    |SPJ   |140  |
    +-----+------+-----+
    |2    |Simon |41   |
    +-----+------+-----+

#### Instances

Instances details

PersistStoreWrite SqlWriteBackend # |
Instance details Defined in Database.Persist.Sql.Orphan.PersistStore Methods insert :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlWriteBackend, SafeToInsert record) => record -> ReaderT SqlWriteBackend m (Key record) # insert_ :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlWriteBackend, SafeToInsert record) => record -> ReaderT SqlWriteBackend m () # insertMany :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlWriteBackend, SafeToInsert record) => [record] -> ReaderT SqlWriteBackend m [Key record] # insertMany_ :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlWriteBackend, SafeToInsert record) => [record] -> ReaderT SqlWriteBackend m () # insertEntityMany :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlWriteBackend) => [Entity record] -> ReaderT SqlWriteBackend m () # insertKey :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlWriteBackend) => Key record -> record -> ReaderT SqlWriteBackend m () # repsert :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlWriteBackend) => Key record -> record -> ReaderT SqlWriteBackend m () # repsertMany :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlWriteBackend) => [(Key record, record)] -> ReaderT SqlWriteBackend m () # replace :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlWriteBackend) => Key record -> record -> ReaderT SqlWriteBackend m () # delete :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlWriteBackend) => Key record -> ReaderT SqlWriteBackend m () # update :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlWriteBackend) => Key record -> [Update record] -> ReaderT SqlWriteBackend m () # updateGet :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlWriteBackend) => Key record -> [Update record] -> ReaderT SqlWriteBackend m record #
PersistStoreWrite SqlBackend # |
Instance details Defined in Database.Persist.Sql.Orphan.PersistStore Methods insert :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlBackend, SafeToInsert record) => record -> ReaderT SqlBackend m (Key record) # insert_ :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlBackend, SafeToInsert record) => record -> ReaderT SqlBackend m () # insertMany :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlBackend, SafeToInsert record) => [record] -> ReaderT SqlBackend m [Key record] # insertMany_ :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlBackend, SafeToInsert record) => [record] -> ReaderT SqlBackend m () # insertEntityMany :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlBackend) => [Entity record] -> ReaderT SqlBackend m () # insertKey :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlBackend) => Key record -> record -> ReaderT SqlBackend m () # repsert :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlBackend) => Key record -> record -> ReaderT SqlBackend m () # repsertMany :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlBackend) => [(Key record, record)] -> ReaderT SqlBackend m () # replace :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlBackend) => Key record -> record -> ReaderT SqlBackend m () # delete :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlBackend) => Key record -> ReaderT SqlBackend m () # update :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlBackend) => Key record -> [Update record] -> ReaderT SqlBackend m () # updateGet :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlBackend) => Key record -> [Update record] -> ReaderT SqlBackend m record #
(HasPersistBackend b, BackendCompatible b s, PersistStoreWrite b) => PersistStoreWrite (Compatible b s) # |
Instance details Defined in Database.Persist.Compatible.Types Methods insert :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record (Compatible b s), SafeToInsert record) => record -> ReaderT (Compatible b s) m (Key record) # insert_ :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record (Compatible b s), SafeToInsert record) => record -> ReaderT (Compatible b s) m () # insertMany :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record (Compatible b s), SafeToInsert record) => [record] -> ReaderT (Compatible b s) m [Key record] # insertMany_ :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record (Compatible b s), SafeToInsert record) => [record] -> ReaderT (Compatible b s) m () # insertEntityMany :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record (Compatible b s)) => [Entity record] -> ReaderT (Compatible b s) m () # insertKey :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record (Compatible b s)) => Key record -> record -> ReaderT (Compatible b s) m () # repsert :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record (Compatible b s)) => Key record -> record -> ReaderT (Compatible b s) m () # repsertMany :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record (Compatible b s)) => [(Key record, record)] -> ReaderT (Compatible b s) m () # replace :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record (Compatible b s)) => Key record -> record -> ReaderT (Compatible b s) m () # delete :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record (Compatible b s)) => Key record -> ReaderT (Compatible b s) m () # update :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record (Compatible b s)) => Key record -> [Update record] -> ReaderT (Compatible b s) m () # updateGet :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record (Compatible b s)) => Key record -> [Update record] -> ReaderT (Compatible b s) m record #

type PersistRecordBackend record backend = (PersistEntity record, PersistEntityBackend record ~ BaseBackend backend) #

A convenient alias for common type signatures

getJust :: forall record backend (m :: Type -> Type). (PersistStoreRead backend, PersistRecordBackend record backend, MonadIO m) => Key record -> ReaderT backend m record #

Same as `get`, but for a non-null (not Maybe) foreign key. Unsafe unless your database is enforcing that the foreign key is valid.

### Example usage

Expand

With schema-1 and dataset-1,

    getJustSpj :: MonadIO m => ReaderT SqlBackend m User
    getJustSpj = getJust spjId

    spj <- getJust spjId

The above query when applied on dataset-1, will get this record:

    +----+------+-----+
    | id | name | age |
    +----+------+-----+
    |  1 | SPJ  |  40 |
    +----+------+-----+

    getJustUnknown :: MonadIO m => ReaderT SqlBackend m User
    getJustUnknown = getJust unknownId

mrx <- getJustUnknown

This just throws an error.

getJustEntity :: forall record backend (m :: Type -> Type). (PersistEntityBackend record ~ BaseBackend backend, MonadIO m, PersistEntity record, PersistStoreRead backend) => Key record -> ReaderT backend m (Entity record) #

Same as `getJust`, but returns an `Entity` instead of just the record.

### Example usage

Expand

With schema-1 and dataset-1,

    getJustEntitySpj :: MonadIO m => ReaderT SqlBackend m (Entity User)
    getJustEntitySpj = getJustEntity spjId

    spjEnt <- getJustEntitySpj

The above query when applied on dataset-1, will get this entity:

    +----+------+-----+
    | id | name | age |
    +----+------+-----+
    |  1 | SPJ  |  40 |
    +----+------+-----+

Since: 2.6.1

getEntity :: forall e backend (m :: Type -> Type). (PersistStoreRead backend, PersistRecordBackend e backend, MonadIO m) => Key e -> ReaderT backend m (Maybe (Entity e)) #

Like `get`, but returns the complete `Entity`.

### Example usage

Expand

With schema-1 and dataset-1,

    getSpjEntity :: MonadIO m => ReaderT SqlBackend m (Maybe (Entity User))
    getSpjEntity = getEntity spjId

    mSpjEnt <- getSpjEntity

The above query when applied on dataset-1, will get this entity:

    +----+------+-----+
    | id | name | age |
    +----+------+-----+
    |  1 | SPJ  |  40 |
    +----+------+-----+

belongsTo :: forall ent1 ent2 backend (m :: Type -> Type). (PersistStoreRead backend, PersistEntity ent1, PersistRecordBackend ent2 backend, MonadIO m) => (ent1 -> Maybe (Key ent2)) -> ent1 -> ReaderT backend m (Maybe ent2) #

Curry this to make a convenience function that loads an associated model.

    foreign = belongsTo foreignId

belongsToJust :: forall ent1 ent2 backend (m :: Type -> Type). (PersistStoreRead backend, PersistEntity ent1, PersistRecordBackend ent2 backend, MonadIO m) => (ent1 -> Key ent2) -> ent1 -> ReaderT backend m ent2 #

Same as `belongsTo`, but uses `getJust` and therefore is similarly unsafe.

class SafeToInsert a #

A type class which is used to witness that a type is safe to insert into the database without providing a primary key.

The `TemplateHaskell` function `mkPersist` will generate instances of this class for any entity that it works on. If the entity has a default primary key, then it provides a regular instance. If the entity has a `Primary` natural key, then this works fine. But if the entity has an `Id` column with no `default=`, then this does a `TypeError` and forces the user to use `insertKey`.

Since: 2.14.0.0

#### Instances

Instances details

(TypeError (EntityErrorMessage a) :: Constraint) => SafeToInsert (Entity a) # |
Instance details Defined in Database.Persist.Class.PersistEntity
(TypeError (FunctionErrorMessage a b) :: Constraint) => SafeToInsert (a -> b) # |
Instance details Defined in Database.Persist.Class.PersistEntity

insertEntity :: forall e backend (m :: Type -> Type). (PersistStoreWrite backend, PersistRecordBackend e backend, SafeToInsert e, MonadIO m, HasCallStack) => e -> ReaderT backend m (Entity e) #

Like `insert`, but returns the complete `Entity`.

### Example usage

Expand

With schema-1 and dataset-1,

    insertHaskellEntity :: MonadIO m => ReaderT SqlBackend m (Entity User)
    insertHaskellEntity = insertEntity $ User "Haskell" 81

    haskellEnt <- insertHaskellEntity

The above query when applied on dataset-1, will produce this:

    +----+---------+-----+
    | id |  name   | age |
    +----+---------+-----+
    |  1 | SPJ     |  40 |
    +----+---------+-----+
    |  2 | Simon   |  41 |
    +----+---------+-----+
    |  3 | Haskell |  81 |
    +----+---------+-----+

insertRecord :: forall record backend (m :: Type -> Type). (PersistEntityBackend record ~ BaseBackend backend, PersistEntity record, MonadIO m, PersistStoreWrite backend, SafeToInsert record, HasCallStack) => record -> ReaderT backend m record #

Like `insertEntity` but just returns the record instead of `Entity`.

### Example usage

Expand

With schema-1 and dataset-1,

    insertDaveRecord :: MonadIO m => ReaderT SqlBackend m User
    insertDaveRecord = insertRecord $ User "Dave" 50

    dave <- insertDaveRecord

The above query when applied on dataset-1, will produce this:

    +-----+------+-----+
    |id   |name  |age  |
    +-----+------+-----+
    |1    |SPJ   |40   |
    +-----+------+-----+
    |2    |Simon |41   |
    +-----+------+-----+
    |3    |Dave  |50   |
    +-----+------+-----+

Since: 2.6.1

# PersistUnique

The `PersistUnique` type class is relevant for database backends that offer uniqueness keys. Uniquenes keys allow us to perform operations like `getBy`, `deleteBy`, as well as `upsert` and `putMany`.

All the examples present here will be explained based on these two schemas and the dataset:

# schema-1

This schema has single unique constraint.

    share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
    User
        name String
        age Int
        UniqueUserName name
        deriving Show
    |]

# schema-2

This schema has two unique constraints.

    share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
    User
        name String
        age Int
        UniqueUserName name
        UniqueUserAge age
        deriving Show
    |]

# dataset-1

    +-----+-----+-----+
    |id   |name |age  |
    +-----+-----+-----+
    |1    |SPJ  |40   |
    +-----+-----+-----+
    |2    |Simon|41   |
    +-----+-----+-----+

type PersistUnique a = PersistUniqueWrite a #

A backwards-compatible alias for those that don't care about distinguishing between read and write queries. It signifies the assumption that, by default, a backend can write as well as read.

class PersistStoreRead backend => PersistUniqueRead backend where #

Queries against `Unique` keys (other than the id `Key`).

Please read the general Persistent documentation to learn how to create `Unique` keys.

Using this with an Entity without a Unique key leads to undefined behavior. A few of these functions require a single `Unique`, so using an Entity with multiple `Unique`s is also undefined. In these cases persistent's goal is to throw an exception as soon as possible, but persistent is still transitioning to that.

SQL backends automatically create uniqueness constraints, but for MongoDB you must manually place a unique index on a field to have a uniqueness constraint.

Minimal complete definition

getBy

Methods

getBy :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend) => Unique record -> ReaderT backend m (Maybe (Entity record)) #

Get a record by unique key, if available. Returns also the identifier.

### Example usage

Expand

With schema-1 and dataset-1:

    getBySpjName :: MonadIO m  => ReaderT SqlBackend m (Maybe (Entity User))
    getBySpjName = getBy $ UniqueUserName "SPJ"

    mSpjEnt <- getBySpjName

The above query when applied on dataset-1, will get this entity:

    +----+------+-----+
    | id | name | age |
    +----+------+-----+
    |  1 | SPJ  |  40 |
    +----+------+-----+

existsBy :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend) => Unique record -> ReaderT backend m Bool #

Returns True if a record with this unique key exists, otherwise False.

### Example usage

Expand

With schema-1 and dataset-1:

    existsBySpjName :: MonadIO m  => ReaderT SqlBackend m Bool
    existsBySpjName = existsBy $ UniqueUserName "SPJ"

    spjEntExists <- existsBySpjName

The above query when applied on dataset-1, will return the value True.

Since: 2.14.5

#### Instances

Instances details

PersistUniqueRead SqlReadBackend # |
Instance details Defined in Database.Persist.Sql.Orphan.PersistUnique Methods getBy :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlReadBackend) => Unique record -> ReaderT SqlReadBackend m (Maybe (Entity record)) # existsBy :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlReadBackend) => Unique record -> ReaderT SqlReadBackend m Bool #
PersistUniqueRead SqlWriteBackend # |
Instance details Defined in Database.Persist.Sql.Orphan.PersistUnique Methods getBy :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlWriteBackend) => Unique record -> ReaderT SqlWriteBackend m (Maybe (Entity record)) # existsBy :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlWriteBackend) => Unique record -> ReaderT SqlWriteBackend m Bool #
PersistUniqueRead SqlBackend # |
Instance details Defined in Database.Persist.Sql.Orphan.PersistUnique Methods getBy :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlBackend) => Unique record -> ReaderT SqlBackend m (Maybe (Entity record)) # existsBy :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlBackend) => Unique record -> ReaderT SqlBackend m Bool #
(HasPersistBackend b, BackendCompatible b s, PersistUniqueRead b) => PersistUniqueRead (Compatible b s) # |
Instance details Defined in Database.Persist.Compatible.Types Methods getBy :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record (Compatible b s)) => Unique record -> ReaderT (Compatible b s) m (Maybe (Entity record)) # existsBy :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record (Compatible b s)) => Unique record -> ReaderT (Compatible b s) m Bool #

class (PersistUniqueRead backend, PersistStoreWrite backend) => PersistUniqueWrite backend where #

Some functions in this module (`insertUnique`, `insertBy`, and `replaceUnique`) first query the unique indexes to check for conflicts. You could instead optimistically attempt to perform the operation (e.g. `replace` instead of `replaceUnique`). However,

- there is some fragility to trying to catch the correct exception and determing the column of failure;
- an exception will automatically abort the current SQL transaction.

Minimal complete definition

deleteBy

Methods

deleteBy :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend) => Unique record -> ReaderT backend m () #

Delete a specific record by unique key. Does nothing if no record matches.

### Example usage

Expand

With schema-1 and dataset-1,

    deleteBySpjName :: MonadIO m => ReaderT SqlBackend m ()
    deleteBySpjName = deleteBy UniqueUserName "SPJ"

The above query when applied on dataset-1, will produce this:

    +-----+------+-----+
    |id   |name  |age  |
    +-----+------+-----+
    |2    |Simon |41   |
    +-----+------+-----+

insertUnique :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => record -> ReaderT backend m (Maybe (Key record)) #

Like `insert`, but returns `Nothing` when the record couldn't be inserted because of a uniqueness constraint.

### Example usage

Expand

With schema-1 and dataset-1, we try to insert the following two records:

    linusId <- insertUnique $ User "Linus" 48
    spjId   <- insertUnique $ User "SPJ" 90

    +-----+------+-----+
    |id   |name  |age  |
    +-----+------+-----+
    |1    |SPJ   |40   |
    +-----+------+-----+
    |2    |Simon |41   |
    +-----+------+-----+
    |3    |Linus |48   |
    +-----+------+-----+

Linus's record was inserted to dataset-1, while SPJ wasn't because SPJ already exists in dataset-1.

insertUnique_ :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => record -> ReaderT backend m (Maybe ()) #

Same as `insertUnique` but doesn't return a `Key`.

### Example usage

Expand

With schema-1 and dataset-1, we try to insert the following two records:

    linusId <- insertUnique_ $ User "Linus" 48
    spjId   <- insertUnique_ $ User "SPJ" 90

    +-----+------+-----+
    |id   |name  |age  |
    +-----+------+-----+
    |1    |SPJ   |40   |
    +-----+------+-----+
    |2    |Simon |41   |
    +-----+------+-----+
    |3    |Linus |48   |
    +-----+------+-----+

Linus's record was inserted to dataset-1, while SPJ wasn't because SPJ already exists in dataset-1.

Since: 2.14.5.0

upsert #

Arguments

:: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend, OnlyOneUniqueKey record, SafeToInsert record) |
=> record | new record to insert
-> [Update record] | updates to perform if the record already exists
-> ReaderT backend m (Entity record) | the record in the database after the operation

Update based on a uniqueness constraint or insert:

- insert the new record if it does not exist;
- If the record exists (matched via it's uniqueness constraint), then update the existing record with the parameters which is passed on as list to the function.

### Example usage

Expand

First, we try to explain `upsert` using schema-1 and dataset-1.

    upsertSpj :: MonadIO m => [Update User] -> ReaderT SqlBackend m (Maybe (Entity User))
    upsertSpj updates = upsert (User "SPJ" 999) updates

    mSpjEnt <- upsertSpj [UserAge +=. 15]

The above query when applied on dataset-1, will produce this:

    +-----+-----+--------+
    |id   |name |age     |
    +-----+-----+--------+
    |1    |SPJ  |40 -> 55|
    +-----+-----+--------+
    |2    |Simon|41      |
    +-----+-----+--------+

    upsertX :: MonadIO m => [Update User] -> ReaderT SqlBackend m (Maybe (Entity User))
    upsertX updates = upsert (User "X" 999) updates

    mXEnt <- upsertX [UserAge +=. 15]

The above query when applied on dataset-1, will produce this:

    +-----+-----+--------+
    |id   |name |age     |
    +-----+-----+--------+
    |1    |SPJ  |40      |
    +-----+-----+--------+
    |2    |Simon|41      |
    +-----+-----+--------+
    |3    |X    |999     |
    +-----+-----+--------+

Next, what if the schema has two uniqueness constraints? Let's check it out using schema-2:

    mSpjEnt <- upsertSpj [UserAge +=. 15]

This fails with a compile-time type error alerting us to the fact that this record has multiple unique keys, and suggests that we look for `upsertBy` to select the unique key we want.

upsertBy #

Arguments

:: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend, SafeToInsert record) |
=> Unique record | uniqueness constraint to find by
-> record | new record to insert
-> [Update record] | updates to perform if the record already exists
-> ReaderT backend m (Entity record) | the record in the database after the operation

Update based on a given uniqueness constraint or insert:

- insert the new record if it does not exist;
- update the existing record that matches the given uniqueness constraint.

### Example usage

Expand

We try to explain `upsertBy` using schema-2 and dataset-1.

    upsertBySpjName :: MonadIO m => User -> [Update User] -> ReaderT SqlBackend m (Entity User)
    upsertBySpjName record updates = upsertBy (UniqueUserName "SPJ") record updates

    mSpjEnt <- upsertBySpjName (Person "X" 999) [PersonAge += .15]

The above query will alter dataset-1 to:

    +-----+-----+--------+
    |id   |name |age     |
    +-----+-----+--------+
    |1    |SPJ  |40 -> 55|
    +-----+-----+--------+
    |2    |Simon|41      |
    +-----+-----+--------+

    upsertBySimonAge :: MonadIO m => User -> [Update User] -> ReaderT SqlBackend m (Entity User)
    upsertBySimonAge record updates = upsertBy (UniqueUserName "SPJ") record updates

    mPhilipEnt <- upsertBySimonAge (User "X" 999) [UserName =. "Philip"]

The above query will alter dataset-1 to:

    +----+-----------------+-----+
    | id |      name       | age |
    +----+-----------------+-----+
    |  1 | SPJ             |  40 |
    +----+-----------------+-----+
    |  2 | Simon -> Philip |  41 |
    +----+-----------------+-----+

    upsertByUnknownName :: MonadIO m => User -> [Update User] -> ReaderT SqlBackend m (Entity User)
    upsertByUnknownName record updates = upsertBy (UniqueUserName "Unknown") record updates

    mXEnt <- upsertByUnknownName (User "X" 999) [UserAge +=. 15]

This query will alter dataset-1 to:

    +-----+-----+-----+
    |id   |name |age  |
    +-----+-----+-----+
    |1    |SPJ  |40   |
    +-----+-----+-----+
    |2    |Simon|41   |
    +-----+-----+-----+
    |3    |X    |999  |
    +-----+-----+-----+

putMany #

Arguments

:: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend, SafeToInsert record) |
=> [record] | A list of the records you want to insert or replace.
-> ReaderT backend m () |

Put many records into db

- insert new records that do not exist (or violate any unique constraints)
- replace existing records (matching any unique constraint)

Since: 2.8.1

#### Instances

Instances details

PersistUniqueWrite SqlWriteBackend # |
Instance details Defined in Database.Persist.Sql.Orphan.PersistUnique Methods deleteBy :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlWriteBackend) => Unique record -> ReaderT SqlWriteBackend m () # insertUnique :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlWriteBackend, SafeToInsert record) => record -> ReaderT SqlWriteBackend m (Maybe (Key record)) # insertUnique_ :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlWriteBackend, SafeToInsert record) => record -> ReaderT SqlWriteBackend m (Maybe ()) # upsert :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlWriteBackend, OnlyOneUniqueKey record, SafeToInsert record) => record -> [Update record] -> ReaderT SqlWriteBackend m (Entity record) # upsertBy :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlWriteBackend, SafeToInsert record) => Unique record -> record -> [Update record] -> ReaderT SqlWriteBackend m (Entity record) # putMany :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlWriteBackend, SafeToInsert record) => [record] -> ReaderT SqlWriteBackend m () #
PersistUniqueWrite SqlBackend # |
Instance details Defined in Database.Persist.Sql.Orphan.PersistUnique Methods deleteBy :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlBackend) => Unique record -> ReaderT SqlBackend m () # insertUnique :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlBackend, SafeToInsert record) => record -> ReaderT SqlBackend m (Maybe (Key record)) # insertUnique_ :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlBackend, SafeToInsert record) => record -> ReaderT SqlBackend m (Maybe ()) # upsert :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlBackend, OnlyOneUniqueKey record, SafeToInsert record) => record -> [Update record] -> ReaderT SqlBackend m (Entity record) # upsertBy :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlBackend, SafeToInsert record) => Unique record -> record -> [Update record] -> ReaderT SqlBackend m (Entity record) # putMany :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record SqlBackend, SafeToInsert record) => [record] -> ReaderT SqlBackend m () #
(HasPersistBackend b, BackendCompatible b s, PersistUniqueWrite b) => PersistUniqueWrite (Compatible b s) # |
Instance details Defined in Database.Persist.Compatible.Types Methods deleteBy :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record (Compatible b s)) => Unique record -> ReaderT (Compatible b s) m () # insertUnique :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record (Compatible b s), SafeToInsert record) => record -> ReaderT (Compatible b s) m (Maybe (Key record)) # insertUnique_ :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record (Compatible b s), SafeToInsert record) => record -> ReaderT (Compatible b s) m (Maybe ()) # upsert :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record (Compatible b s), OnlyOneUniqueKey record, SafeToInsert record) => record -> [Update record] -> ReaderT (Compatible b s) m (Entity record) # upsertBy :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record (Compatible b s), SafeToInsert record) => Unique record -> record -> [Update record] -> ReaderT (Compatible b s) m (Entity record) # putMany :: forall record (m :: Type -> Type). (MonadIO m, PersistRecordBackend record (Compatible b s), SafeToInsert record) => [record] -> ReaderT (Compatible b s) m () #

class PersistEntity record => OnlyOneUniqueKey record where #

This class is used to ensure that `upsert` is only called on records that have a single `Unique` key. The quasiquoter automatically generates working instances for appropriate records, and generates `TypeError` instances for records that have 0 or multiple unique keys.

Since: 2.10.0

Methods

onlyUniqueP :: record -> Unique record #

class PersistEntity record => AtLeastOneUniqueKey record where #

This class is used to ensure that functions requring at least one unique key are not called with records that have 0 unique keys. The quasiquoter automatically writes working instances for appropriate entities, and generates `TypeError` instances for records that have 0 unique keys.

Since: 2.10.0

Methods

requireUniquesP :: record -> NonEmpty (Unique record) #

onlyOneUniqueDef :: (OnlyOneUniqueKey record, Monad proxy) => proxy record -> UniqueDef #

Given a proxy for a `PersistEntity` record, this returns the sole `UniqueDef` for that entity.

Since: 2.13.0.0

type NoUniqueKeysError ty = (('Text "The entity " ':<>: 'ShowType ty) ':<>: 'Text " does not have any unique keys.") ':$$: ('Text "The function you are trying to call requires a unique key " ':<>: 'Text "to be defined on the entity.") #

This is an error message. It is used when writing instances of `OnlyOneUniqueKey` for an entity that has no unique keys.

Since: 2.10.0

type MultipleUniqueKeysError ty = ((('Text "The entity " ':<>: 'ShowType ty) ':<>: 'Text " has multiple unique keys.") ':$$: ('Text "The function you are trying to call requires only a single " ':<>: 'Text "unique key.")) ':$$: (('Text "There is probably a variant of the function with 'By' " ':<>: 'Text "appended that will allow you to select a unique key ") ':<>: 'Text "for the operation.") #

This is an error message. It is used when an entity has multiple unique keys, and the function expects a single unique key.

Since: 2.10.0

getByValue :: forall record (m :: Type -> Type) backend. (MonadIO m, PersistUniqueRead backend, PersistRecordBackend record backend, AtLeastOneUniqueKey record) => record -> ReaderT backend m (Maybe (Entity record)) #

A modification of `getBy`, which takes the `PersistEntity` itself instead of a `Unique` record. Returns a record matching one of the unique keys. This function makes the most sense on entities with a single `Unique` constructor.

### Example usage

Expand

With schema-1 and dataset-1,

getBySpjValue :: MonadIO m => ReaderT SqlBackend m (Maybe (Entity User)) getBySpjValue = getByValue $ User SPJ 999

    mSpjEnt <- getBySpjValue

The above query when applied on dataset-1, will get this record:

    +----+------+-----+
    | id | name | age |
    +----+------+-----+
    |  1 | SPJ  |  40 |
    +----+------+-----+

insertBy :: forall record backend (m :: Type -> Type). (MonadIO m, PersistUniqueWrite backend, PersistRecordBackend record backend, AtLeastOneUniqueKey record, SafeToInsert record) => record -> ReaderT backend m (Either (Entity record) (Key record)) #

Insert a value, checking for conflicts with any unique constraints. If a duplicate exists in the database, it is returned as `Left`. Otherwise, the new 'Key is returned as `Right`.

### Example usage

Expand

With schema-2 and dataset-1, we have following lines of code:

    l1 <- insertBy $ User "SPJ" 20
    l2 <- insertBy $ User "XXX" 41
    l3 <- insertBy $ User "SPJ" 40
    r1 <- insertBy $ User "XXX" 100

First three lines return `Left` because there're duplicates in given record's uniqueness constraints. While the last line returns a new key as `Right`.

insertUniqueEntity :: forall record backend (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend, PersistUniqueWrite backend, SafeToInsert record) => record -> ReaderT backend m (Maybe (Entity record)) #

Like `insertEntity`, but returns `Nothing` when the record couldn't be inserted because of a uniqueness constraint.

### Example usage

Expand

We use schema-2 and dataset-1 here.

    insertUniqueSpjEntity :: MonadIO m => ReaderT SqlBackend m (Maybe (Entity User))
    insertUniqueSpjEntity = insertUniqueEntity $ User "SPJ" 50

    mSpjEnt <- insertUniqueSpjEntity

The above query results `Nothing` as SPJ already exists.

    insertUniqueAlexaEntity :: MonadIO m => ReaderT SqlBackend m (Maybe (Entity User))
    insertUniqueAlexaEntity = insertUniqueEntity $ User "Alexa" 3

    mAlexaEnt <- insertUniqueSpjEntity

Because there's no such unique keywords of the given record, the above query when applied on dataset-1, will produce this:

    +----+-------+-----+
    | id | name  | age |
    +----+-------+-----+
    |  1 | SPJ   |  40 |
    +----+-------+-----+
    |  2 | Simon |  41 |
    +----+-------+-----+
    |  3 | Alexa |   3 |
    +----+-------+-----+

Since: 2.7.1

replaceUnique :: forall record backend (m :: Type -> Type). (MonadIO m, Eq (Unique record), PersistRecordBackend record backend, PersistUniqueWrite backend) => Key record -> record -> ReaderT backend m (Maybe (Unique record)) #

Attempt to replace the record of the given key with the given new record. First query the unique fields to make sure the replacement maintains uniqueness constraints.

Return `Nothing` if the replacement was made. If uniqueness is violated, return a `Just` with the `Unique` violation

Since: 1.2.2.0

checkUnique :: forall record backend (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend, PersistUniqueRead backend) => record -> ReaderT backend m (Maybe (Unique record)) #

Check whether there are any conflicts for unique keys with this entity and existing entities in the database.

Returns `Nothing` if the entity would be unique, and could thus safely be inserted. on a conflict returns the conflicting key

### Example usage

Expand

We use schema-1 and dataset-1 here.

This would be `Nothing`:

    mAlanConst <- checkUnique $ User "Alan" 70

While this would be `Just` because SPJ already exists:

    mSpjConst <- checkUnique $ User "SPJ" 60

checkUniqueUpdateable :: forall record backend (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend, PersistUniqueRead backend) => Entity record -> ReaderT backend m (Maybe (Unique record)) #

Check whether there are any conflicts for unique keys with this entity and existing entities in the database.

Returns `Nothing` if the entity would stay unique, and could thus safely be updated. on a conflict returns the conflicting key

This is similar to `checkUnique`, except it's useful for updating - when the particular entity already exists, it would normally conflict with itself. This variant ignores those conflicts

### Example usage

Expand

We use schema-1 and dataset-1 here.

This would be `Nothing`:

    mAlanConst <- checkUnique $ User "Alan" 70

While this would be `Just` because SPJ already exists:

    mSpjConst <- checkUnique $ User "SPJ" 60

Since: 2.11.0.0

onlyUnique :: forall record backend (m :: Type -> Type). (MonadIO m, PersistUniqueWrite backend, PersistRecordBackend record backend, OnlyOneUniqueKey record) => record -> ReaderT backend m (Unique record) #

Return the single unique key for a record.

### Example usage

Expand

We use shcema-1 and dataset-1 here.

    onlySimonConst :: MonadIO m => ReaderT SqlBackend m (Unique User)
    onlySimonConst = onlyUnique $ User "Simon" 999

    mSimonConst <- onlySimonConst

`mSimonConst` would be Simon's uniqueness constraint. Note that `onlyUnique` doesn't work if there're more than two constraints. It will fail with a type error instead.

# PersistQuery

The `PersistQuery` type class allows us to select lists and filter database models. `selectList` is the canonical read operation, and we can write `updateWhere` and `deleteWhere` to modify based on filters.

selectList :: forall record backend (m :: Type -> Type). (MonadIO m, PersistQueryRead backend, PersistRecordBackend record backend) => [Filter record] -> [SelectOpt record] -> ReaderT backend m [Entity record] #

Returns a `[`Entity` record]` corresponding to the filters and options provided.

Filters are constructed using the operators defined in Database.Persist (and re-exported from Database.Persist.Sql). Let's look at some examples:

    usersWithAgeOver40 :: SqlPersistT IO [Entity User]
    usersWithAgeOver40 =
        selectList [UserAge >=. 40] []

If you provide multiple values in the list, the conditions are `AND`ed together.

    usersWithAgeBetween30And50 :: SqlPersistT IO [Entity User]
    usersWithAgeBetween30And50 =
         selectList
             [ UserAge >=. 30
             , UserAge <=. 50
             ]
             []

The second list contains the `SelectOpt` for a record. We can select the first ten records with `LimitTo`

    firstTenUsers =
        selectList [] [LimitTo 10]

And we can select the second ten users with `OffsetBy`.

    secondTenUsers =
        selectList [] [LimitTo 10, OffsetBy 10]

Warning that LIMIT/OFFSET is bad for pagination!

The type of record can usually be infered from the types of the provided filters and select options. In the previous two examples, though, you'll notice that the select options are polymorphic, applying to any record type. In order to help type inference in such situations, or simply as an enhancement to readability, you might find type application useful, illustrated below.

    {-# LANGUAGE TypeApplications #-}
    ...

    firstTenUsers =
        selectList User [] [LimitTo 10]

    secondTenUsers =
        selectList User [] [LimitTo 10, OffsetBy 10]

With `Asc` and `Desc`, we can provide the field we want to sort on. We can provide multiple sort orders - later ones are used to sort records that are equal on the first field.

    newestUsers =
        selectList [] [Desc UserCreatedAt, LimitTo 10]

    oldestUsers =
        selectList [] [Asc UserCreatedAt, LimitTo 10]

selectKeys :: forall record backend (m :: Type -> Type). (PersistQueryRead backend, MonadResource m, PersistRecordBackend record backend, MonadReader backend m) => [Filter record] -> [SelectOpt record] -> ConduitM () (Key record) m () #

Get the `Key`s of all records matching the given criterion.

For an example, see `selectList`.

type PersistQuery a = PersistQueryWrite a #

A backwards-compatible alias for those that don't care about distinguishing between read and write queries. It signifies the assumption that, by default, a backend can write as well as read.

class (PersistCore backend, PersistStoreRead backend) => PersistQueryRead backend where #

Backends supporting conditional read operations.

Minimal complete definition

selectSourceRes, selectKeysRes, count, exists

Methods

selectSourceRes :: forall record (m1 :: Type -> Type) (m2 :: Type -> Type). (PersistRecordBackend record backend, MonadIO m1, MonadIO m2) => [Filter record] -> [SelectOpt record] -> ReaderT backend m1 (Acquire (ConduitM () (Entity record) m2 ())) #

Get all records matching the given criterion in the specified order. Returns also the identifiers.

NOTE: This function returns an `Acquire` and a `ConduitM`, which implies that it streams from the database. It does not. Please use `selectList` to simplify the code. If you want streaming behavior, consider `persistent-pagination` which efficiently chunks a query into ranges, or investigate a backend-specific streaming solution.

selectFirst :: forall (m :: Type -> Type) record. (MonadIO m, PersistRecordBackend record backend) => [Filter record] -> [SelectOpt record] -> ReaderT backend m (Maybe (Entity record)) #

Get just the first record for the criterion.

selectKeysRes :: forall (m1 :: Type -> Type) (m2 :: Type -> Type) record. (MonadIO m1, MonadIO m2, PersistRecordBackend record backend) => [Filter record] -> [SelectOpt record] -> ReaderT backend m1 (Acquire (ConduitM () (Key record) m2 ())) #

Get the `Key`s of all records matching the given criterion.

count :: forall (m :: Type -> Type) record. (MonadIO m, PersistRecordBackend record backend) => [Filter record] -> ReaderT backend m Int #

The total number of records fulfilling the given criterion.

exists :: forall (m :: Type -> Type) record. (MonadIO m, PersistRecordBackend record backend) => [Filter record] -> ReaderT backend m Bool #

Check if there is at least one record fulfilling the given criterion.

Since: 2.11

#### Instances

Instances details

PersistQueryRead SqlReadBackend # |
Instance details Defined in Database.Persist.Sql.Orphan.PersistQuery Methods selectSourceRes :: forall record (m1 :: Type -> Type) (m2 :: Type -> Type). (PersistRecordBackend record SqlReadBackend, MonadIO m1, MonadIO m2) => [Filter record] -> [SelectOpt record] -> ReaderT SqlReadBackend m1 (Acquire (ConduitM () (Entity record) m2 ())) # selectFirst :: forall (m :: Type -> Type) record. (MonadIO m, PersistRecordBackend record SqlReadBackend) => [Filter record] -> [SelectOpt record] -> ReaderT SqlReadBackend m (Maybe (Entity record)) # selectKeysRes :: forall (m1 :: Type -> Type) (m2 :: Type -> Type) record. (MonadIO m1, MonadIO m2, PersistRecordBackend record SqlReadBackend) => [Filter record] -> [SelectOpt record] -> ReaderT SqlReadBackend m1 (Acquire (ConduitM () (Key record) m2 ())) # count :: forall (m :: Type -> Type) record. (MonadIO m, PersistRecordBackend record SqlReadBackend) => [Filter record] -> ReaderT SqlReadBackend m Int # exists :: forall (m :: Type -> Type) record. (MonadIO m, PersistRecordBackend record SqlReadBackend) => [Filter record] -> ReaderT SqlReadBackend m Bool #
PersistQueryRead SqlWriteBackend # |
Instance details Defined in Database.Persist.Sql.Orphan.PersistQuery Methods selectSourceRes :: forall record (m1 :: Type -> Type) (m2 :: Type -> Type). (PersistRecordBackend record SqlWriteBackend, MonadIO m1, MonadIO m2) => [Filter record] -> [SelectOpt record] -> ReaderT SqlWriteBackend m1 (Acquire (ConduitM () (Entity record) m2 ())) # selectFirst :: forall (m :: Type -> Type) record. (MonadIO m, PersistRecordBackend record SqlWriteBackend) => [Filter record] -> [SelectOpt record] -> ReaderT SqlWriteBackend m (Maybe (Entity record)) # selectKeysRes :: forall (m1 :: Type -> Type) (m2 :: Type -> Type) record. (MonadIO m1, MonadIO m2, PersistRecordBackend record SqlWriteBackend) => [Filter record] -> [SelectOpt record] -> ReaderT SqlWriteBackend m1 (Acquire (ConduitM () (Key record) m2 ())) # count :: forall (m :: Type -> Type) record. (MonadIO m, PersistRecordBackend record SqlWriteBackend) => [Filter record] -> ReaderT SqlWriteBackend m Int # exists :: forall (m :: Type -> Type) record. (MonadIO m, PersistRecordBackend record SqlWriteBackend) => [Filter record] -> ReaderT SqlWriteBackend m Bool #
PersistQueryRead SqlBackend # |
Instance details Defined in Database.Persist.Sql.Orphan.PersistQuery Methods selectSourceRes :: forall record (m1 :: Type -> Type) (m2 :: Type -> Type). (PersistRecordBackend record SqlBackend, MonadIO m1, MonadIO m2) => [Filter record] -> [SelectOpt record] -> ReaderT SqlBackend m1 (Acquire (ConduitM () (Entity record) m2 ())) # selectFirst :: forall (m :: Type -> Type) record. (MonadIO m, PersistRecordBackend record SqlBackend) => [Filter record] -> [SelectOpt record] -> ReaderT SqlBackend m (Maybe (Entity record)) # selectKeysRes :: forall (m1 :: Type -> Type) (m2 :: Type -> Type) record. (MonadIO m1, MonadIO m2, PersistRecordBackend record SqlBackend) => [Filter record] -> [SelectOpt record] -> ReaderT SqlBackend m1 (Acquire (ConduitM () (Key record) m2 ())) # count :: forall (m :: Type -> Type) record. (MonadIO m, PersistRecordBackend record SqlBackend) => [Filter record] -> ReaderT SqlBackend m Int # exists :: forall (m :: Type -> Type) record. (MonadIO m, PersistRecordBackend record SqlBackend) => [Filter record] -> ReaderT SqlBackend m Bool #
(HasPersistBackend b, BackendCompatible b s, PersistQueryRead b) => PersistQueryRead (Compatible b s) # |
Instance details Defined in Database.Persist.Compatible.Types Methods selectSourceRes :: forall record (m1 :: Type -> Type) (m2 :: Type -> Type). (PersistRecordBackend record (Compatible b s), MonadIO m1, MonadIO m2) => [Filter record] -> [SelectOpt record] -> ReaderT (Compatible b s) m1 (Acquire (ConduitM () (Entity record) m2 ())) # selectFirst :: forall (m :: Type -> Type) record. (MonadIO m, PersistRecordBackend record (Compatible b s)) => [Filter record] -> [SelectOpt record] -> ReaderT (Compatible b s) m (Maybe (Entity record)) # selectKeysRes :: forall (m1 :: Type -> Type) (m2 :: Type -> Type) record. (MonadIO m1, MonadIO m2, PersistRecordBackend record (Compatible b s)) => [Filter record] -> [SelectOpt record] -> ReaderT (Compatible b s) m1 (Acquire (ConduitM () (Key record) m2 ())) # count :: forall (m :: Type -> Type) record. (MonadIO m, PersistRecordBackend record (Compatible b s)) => [Filter record] -> ReaderT (Compatible b s) m Int # exists :: forall (m :: Type -> Type) record. (MonadIO m, PersistRecordBackend record (Compatible b s)) => [Filter record] -> ReaderT (Compatible b s) m Bool #

class (PersistQueryRead backend, PersistStoreWrite backend) => PersistQueryWrite backend where #

Backends supporting conditional write operations

Methods

updateWhere :: forall (m :: Type -> Type) record. (MonadIO m, PersistRecordBackend record backend) => [Filter record] -> [Update record] -> ReaderT backend m () #

Update individual fields on any record matching the given criterion.

deleteWhere :: forall (m :: Type -> Type) record. (MonadIO m, PersistRecordBackend record backend) => [Filter record] -> ReaderT backend m () #

Delete all records matching the given criterion.

#### Instances

Instances details

PersistQueryWrite SqlWriteBackend # |
Instance details Defined in Database.Persist.Sql.Orphan.PersistQuery Methods updateWhere :: forall (m :: Type -> Type) record. (MonadIO m, PersistRecordBackend record SqlWriteBackend) => [Filter record] -> [Update record] -> ReaderT SqlWriteBackend m () # deleteWhere :: forall (m :: Type -> Type) record. (MonadIO m, PersistRecordBackend record SqlWriteBackend) => [Filter record] -> ReaderT SqlWriteBackend m () #
PersistQueryWrite SqlBackend # |
Instance details Defined in Database.Persist.Sql.Orphan.PersistQuery Methods updateWhere :: forall (m :: Type -> Type) record. (MonadIO m, PersistRecordBackend record SqlBackend) => [Filter record] -> [Update record] -> ReaderT SqlBackend m () # deleteWhere :: forall (m :: Type -> Type) record. (MonadIO m, PersistRecordBackend record SqlBackend) => [Filter record] -> ReaderT SqlBackend m () #
(HasPersistBackend b, BackendCompatible b s, PersistQueryWrite b) => PersistQueryWrite (Compatible b s) # |
Instance details Defined in Database.Persist.Compatible.Types Methods updateWhere :: forall (m :: Type -> Type) record. (MonadIO m, PersistRecordBackend record (Compatible b s)) => [Filter record] -> [Update record] -> ReaderT (Compatible b s) m () # deleteWhere :: forall (m :: Type -> Type) record. (MonadIO m, PersistRecordBackend record (Compatible b s)) => [Filter record] -> ReaderT (Compatible b s) m () #

selectSource :: forall record backend (m :: Type -> Type). (PersistQueryRead backend, MonadResource m, PersistRecordBackend record backend, MonadReader backend m) => [Filter record] -> [SelectOpt record] -> ConduitM () (Entity record) m () #

Get all records matching the given criterion in the specified order. Returns also the identifiers.

WARNING: This function returns a `ConduitM`, which suggests that it streams the results. It does not stream results on most backends. If you need streaming, see `persistent-pagination` for a means of chunking results based on indexed ranges.

selectKeysList :: forall record backend (m :: Type -> Type). (MonadIO m, PersistQueryRead backend, PersistRecordBackend record backend) => [Filter record] -> [SelectOpt record] -> ReaderT backend m [Key record] #

Call `selectKeys` but return the result as a list.

# PersistEntity

class (PersistField (Key record), ToJSON (Key record), FromJSON (Key record), Show (Key record), Read (Key record), Eq (Key record), Ord (Key record)) => PersistEntity record where #

Persistent serialized Haskell records to the database. A Database `Entity` (A row in SQL, a document in MongoDB, etc) corresponds to a `Key` plus a Haskell record.

For every Haskell record type stored in the database there is a corresponding `PersistEntity` instance. An instance of PersistEntity contains meta-data for the record. PersistEntity also helps abstract over different record types. That way the same query interface can return a `PersistEntity`, with each query returning different types of Haskell records.

Some advanced type system capabilities are used to make this process type-safe. Persistent users usually don't need to understand the class associated data and functions.

Minimal complete definition

keyToValues, keyFromValues, persistIdField, entityDef, persistFieldDef, toPersistFields, fromPersistValues, tabulateEntityA, persistUniqueKeys, persistUniqueToFieldNames, persistUniqueToValues, fieldLens

Associated Types

type PersistEntityBackend record #

Persistent allows multiple different backends (databases).

data Key record #

By default, a backend will automatically generate the key Instead you can specify a Primary key made up of unique values.

data EntityField record :: Type -> Type #

An `EntityField` is parameterised by the Haskell record it belongs to and the additional type of that field.

As of `persistent-2.11.0.0`, it's possible to use the `OverloadedLabels` language extension to refer to `EntityField` values polymorphically. See the documentation on `SymbolToField` for more information.

data Unique record #

Unique keys besides the `Key`.

Methods

keyToValues :: Key record -> [PersistValue] #

A lower-level key operation.

keyFromValues :: [PersistValue] -> Either Text (Key record) #

A lower-level key operation.

persistIdField :: EntityField record (Key record) #

A meta-operation to retrieve the `Key` `EntityField`.

entityDef :: proxy record -> EntityDef #

Retrieve the `EntityDef` meta-data for the record.

persistFieldDef :: EntityField record typ -> FieldDef #

Return meta-data for a given `EntityField`.

toPersistFields :: record -> [PersistValue] #

A meta-operation to get the database fields of a record.

fromPersistValues :: [PersistValue] -> Either Text record #

A lower-level operation to convert from database values to a Haskell record.

tabulateEntityA #

Arguments

:: Applicative f |
=> (forall a. EntityField record a -> f a) | A function that builds a fragment of a record in an `Applicative` context.
-> f (Entity record) |

This function allows you to build an ``Entity` a` by specifying an action that returns a value for the field in the callback function. Let's look at an example.

    parseFromEnvironmentVariables :: IO (Entity User)
    parseFromEnvironmentVariables =
        tabulateEntityA $ \userField ->
            case userField of
                UserName ->
                    getEnv USER_NAME
                UserAge -> do
                    ageVar <- getEnv USER_AGE
                    case readMaybe ageVar of
                        Just age ->
                            pure age
                        Nothing ->
                            error $ "Failed to parse Age from: " <> ageVar
                UserAddressId -> do
                    addressVar <- getEnv USER_ADDRESS_ID
                    pure $ AddressKey addressVar

Since: 2.14.0.0

persistUniqueKeys :: record -> [Unique record] #

A meta operation to retrieve all the `Unique` keys.

persistUniqueToFieldNames :: Unique record -> NonEmpty (FieldNameHS, FieldNameDB) #

A lower level operation.

persistUniqueToValues :: Unique record -> [PersistValue] #

A lower level operation.

fieldLens :: EntityField record field -> forall (f :: Type -> Type). Functor f => (field -> f field) -> Entity record -> f (Entity record) #

Use a `PersistField` as a lens.

keyFromRecordM :: Maybe (record -> Key record) #

Extract a ``Key` record` from a `record` value. Currently, this is only defined for entities using the `Primary` syntax for natural/composite keys. In a future version of `persistent` which incorporates the ID directly into the entity, this will always be Just.

Since: 2.11.0.0

tabulateEntity :: PersistEntity record => (forall a. EntityField record a -> a) -> Entity record #

Construct an ``Entity` record` by providing a value for each of the record's fields.

These constructions are equivalent:

    entityMattConstructor, entityMattTabulate :: Entity User
    entityMattConstructor =
        Entity
            { entityKey = toSqlKey 123
            , entityVal =
                User
                    { userName = Matt
                    , userAge = 33
                    }
            }

    entityMattTabulate =
        tabulateEntity $ \case
            UserId ->
                toSqlKey 123
            UserName ->
                Matt
            UserAge ->
                33

This is a specialization of `tabulateEntityA`, which allows you to construct an `Entity` by providing an `Applicative` action for each field instead of a regular function.

Since: 2.14.0.0

class SymbolToField (sym :: Symbol) rec typ | sym rec -> typ where #

This type class is used with the `OverloadedLabels` extension to provide a more convenient means of using the `EntityField` type. `EntityField` definitions are prefixed with the type name to avoid ambiguity, but this ambiguity can result in verbose code.

If you have a table `User` with a `name Text` field, then the corresponding `EntityField` is `UserName`. With this, we can write `#name :: `EntityField` User Text`.

What's more fun is that the type is more general: it's actually `#name :: (`SymbolToField` "name" rec typ) => EntityField rec typ`

Which means it is *polymorphic* over the actual record. This allows you to write code that can be generic over the tables, provided they have the right fields.

Since: 2.11.0.0

Methods

symbolToField :: EntityField rec typ #

# PersistField

class PersistField a where #

This class teaches Persistent how to take a custom type and marshal it to and from a `PersistValue`, allowing it to be stored in a database.

#### Examples

Expand

##### Simple Newtype

You can use `newtype` to add more type safety/readability to a basis type like `ByteString`. In these cases, just derive `PersistField` and `PersistFieldSql`:

    {-# LANGUAGE GeneralizedNewtypeDeriving #-}

    newtype HashedPassword = HashedPassword ByteString
      deriving (Eq, Show, PersistField, PersistFieldSql)

##### Smart Constructor Newtype

In this example, we create a `PersistField` instance for a newtype following the "Smart Constructor" pattern.

    {-# LANGUAGE GeneralizedNewtypeDeriving #-}
    import qualified Data.Text as T
    import qualified Data.Char as C

    -- | An American Social Security Number
    newtype SSN = SSN Text
     deriving (Eq, Show, PersistFieldSql)

    mkSSN :: Text -> Either Text SSN
    mkSSN t = if (T.length t == 9) && (T.all C.isDigit t)
     then Right $ SSN t
     else Left $ "Invalid SSN: " <> t

    instance PersistField SSN where
      toPersistValue (SSN t) = PersistText t
      fromPersistValue (PersistText t) = mkSSN t
      -- Handle cases where the database does not give us PersistText
      fromPersistValue x = Left $ "File.hs: When trying to deserialize an SSN: expected PersistText, received: " <> T.pack (show x)

Tips:

- This file contain dozens of `PersistField` instances you can look at for examples.
- Typically custom `PersistField` instances will only accept a single `PersistValue` constructor in `fromPersistValue`.
- Internal `PersistField` instances accept a wide variety of `PersistValue`s to accomodate e.g. storing booleans as integers, booleans or strings.
- If you're making a custom instance and using a SQL database, you'll also need `PersistFieldSql` to specify the type of the database column.

Methods

toPersistValue :: a -> PersistValue #

fromPersistValue :: PersistValue -> Either Text a #

#### Instances

Instances details

PersistField Html # |
Instance details Defined in Database.Persist.Class.PersistField Methods toPersistValue :: Html -> PersistValue # fromPersistValue :: PersistValue -> Either Text Html #
PersistField ByteString # |
Instance details Defined in Database.Persist.Class.PersistField Methods toPersistValue :: ByteString -> PersistValue # fromPersistValue :: PersistValue -> Either Text ByteString #
PersistField Int16 # |
Instance details Defined in Database.Persist.Class.PersistField Methods toPersistValue :: Int16 -> PersistValue # fromPersistValue :: PersistValue -> Either Text Int16 #
PersistField Int32 # |
Instance details Defined in Database.Persist.Class.PersistField Methods toPersistValue :: Int32 -> PersistValue # fromPersistValue :: PersistValue -> Either Text Int32 #
PersistField Int64 # |
Instance details Defined in Database.Persist.Class.PersistField Methods toPersistValue :: Int64 -> PersistValue # fromPersistValue :: PersistValue -> Either Text Int64 #
PersistField Int8 # |
Instance details Defined in Database.Persist.Class.PersistField Methods toPersistValue :: Int8 -> PersistValue # fromPersistValue :: PersistValue -> Either Text Int8 #
PersistField Rational # |
Instance details Defined in Database.Persist.Class.PersistField Methods toPersistValue :: Rational -> PersistValue # fromPersistValue :: PersistValue -> Either Text Rational #
PersistField Word16 # |
Instance details Defined in Database.Persist.Class.PersistField Methods toPersistValue :: Word16 -> PersistValue # fromPersistValue :: PersistValue -> Either Text Word16 #
PersistField Word32 # |
Instance details Defined in Database.Persist.Class.PersistField Methods toPersistValue :: Word32 -> PersistValue # fromPersistValue :: PersistValue -> Either Text Word32 #
PersistField Word64 # |
Instance details Defined in Database.Persist.Class.PersistField Methods toPersistValue :: Word64 -> PersistValue # fromPersistValue :: PersistValue -> Either Text Word64 #
PersistField Word8 # |
Instance details Defined in Database.Persist.Class.PersistField Methods toPersistValue :: Word8 -> PersistValue # fromPersistValue :: PersistValue -> Either Text Word8 #
PersistField OverflowNatural # |
Instance details Defined in Database.Persist.Class.PersistField Methods toPersistValue :: OverflowNatural -> PersistValue # fromPersistValue :: PersistValue -> Either Text OverflowNatural #
PersistField PersistValue # |
Instance details Defined in Database.Persist.Class.PersistField Methods toPersistValue :: PersistValue -> PersistValue # fromPersistValue :: PersistValue -> Either Text PersistValue #
PersistField Checkmark # |
Instance details Defined in Database.Persist.Class.PersistField Methods toPersistValue :: Checkmark -> PersistValue # fromPersistValue :: PersistValue -> Either Text Checkmark #
PersistField Text # |
Instance details Defined in Database.Persist.Class.PersistField Methods toPersistValue :: Text -> PersistValue # fromPersistValue :: PersistValue -> Either Text Text #
PersistField Text # |
Instance details Defined in Database.Persist.Class.PersistField Methods toPersistValue :: Text -> PersistValue # fromPersistValue :: PersistValue -> Either Text Text #
PersistField Day # |
Instance details Defined in Database.Persist.Class.PersistField Methods toPersistValue :: Day -> PersistValue # fromPersistValue :: PersistValue -> Either Text Day #
PersistField UTCTime # |
Instance details Defined in Database.Persist.Class.PersistField Methods toPersistValue :: UTCTime -> PersistValue # fromPersistValue :: PersistValue -> Either Text UTCTime #
PersistField TimeOfDay # |
Instance details Defined in Database.Persist.Class.PersistField Methods toPersistValue :: TimeOfDay -> PersistValue # fromPersistValue :: PersistValue -> Either Text TimeOfDay #
(TypeError ((((('Text "The instance of PersistField for the Natural type was removed." ':$$: 'Text "Please see the documentation for OverflowNatural if you want to ") ':$$: 'Text "continue using the old behavior or want to see documentation on ") ':$$: 'Text "why the instance was removed.") ':$$: 'Text "") ':$$: 'Text "This error instance will be removed in a future release.") :: Constraint) => PersistField Natural # |
Instance details Defined in Database.Persist.Class.PersistField Methods toPersistValue :: Natural -> PersistValue # fromPersistValue :: PersistValue -> Either Text Natural #
PersistField Bool # |
Instance details Defined in Database.Persist.Class.PersistField Methods toPersistValue :: Bool -> PersistValue # fromPersistValue :: PersistValue -> Either Text Bool #
PersistField Double # |
Instance details Defined in Database.Persist.Class.PersistField Methods toPersistValue :: Double -> PersistValue # fromPersistValue :: PersistValue -> Either Text Double #
PersistField Int # |
Instance details Defined in Database.Persist.Class.PersistField Methods toPersistValue :: Int -> PersistValue # fromPersistValue :: PersistValue -> Either Text Int #
PersistField Word # |
Instance details Defined in Database.Persist.Class.PersistField Methods toPersistValue :: Word -> PersistValue # fromPersistValue :: PersistValue -> Either Text Word #
PersistField v => PersistField (IntMap v) # |
Instance details Defined in Database.Persist.Class.PersistField Methods toPersistValue :: IntMap v -> PersistValue # fromPersistValue :: PersistValue -> Either Text (IntMap v) #
(Ord a, PersistField a) => PersistField (Set a) # |
Instance details Defined in Database.Persist.Class.PersistField Methods toPersistValue :: Set a -> PersistValue # fromPersistValue :: PersistValue -> Either Text (Set a) #
(PersistEntity record, PersistField record, PersistField (Key record)) => PersistField (Entity record) # |
Instance details Defined in Database.Persist.Class.PersistEntity Methods toPersistValue :: Entity record -> PersistValue # fromPersistValue :: PersistValue -> Either Text (Entity record) #
(BackendCompatible b s, PersistField (BackendKey b)) => PersistField (BackendKey (Compatible b s)) # |
Instance details Defined in Database.Persist.Compatible.Types Methods toPersistValue :: BackendKey (Compatible b s) -> PersistValue # fromPersistValue :: PersistValue -> Either Text (BackendKey (Compatible b s)) #
PersistField (BackendKey SqlReadBackend) # |
Instance details Defined in Database.Persist.Sql.Orphan.PersistStore Methods toPersistValue :: BackendKey SqlReadBackend -> PersistValue # fromPersistValue :: PersistValue -> Either Text (BackendKey SqlReadBackend) #
PersistField (BackendKey SqlWriteBackend) # |
Instance details Defined in Database.Persist.Sql.Orphan.PersistStore Methods toPersistValue :: BackendKey SqlWriteBackend -> PersistValue # fromPersistValue :: PersistValue -> Either Text (BackendKey SqlWriteBackend) #
PersistField (BackendKey SqlBackend) # |
Instance details Defined in Database.Persist.Sql.Orphan.PersistStore Methods toPersistValue :: BackendKey SqlBackend -> PersistValue # fromPersistValue :: PersistValue -> Either Text (BackendKey SqlBackend) #
PersistField a => PersistField (Vector a) # |
Instance details Defined in Database.Persist.Class.PersistField Methods toPersistValue :: Vector a -> PersistValue # fromPersistValue :: PersistValue -> Either Text (Vector a) #
PersistField a => PersistField (Maybe a) # |
Instance details Defined in Database.Persist.Class.PersistField Methods toPersistValue :: Maybe a -> PersistValue # fromPersistValue :: PersistValue -> Either Text (Maybe a) #
PersistField [Char] # |
Instance details Defined in Database.Persist.Class.PersistField Methods toPersistValue :: [Char] -> PersistValue # fromPersistValue :: PersistValue -> Either Text [Char] #
PersistField a => PersistField [a] # |
Instance details Defined in Database.Persist.Class.PersistField Methods toPersistValue :: [a] -> PersistValue # fromPersistValue :: PersistValue -> Either Text [a] #
HasResolution a => PersistField (Fixed a) # |
Instance details Defined in Database.Persist.Class.PersistField Methods toPersistValue :: Fixed a -> PersistValue # fromPersistValue :: PersistValue -> Either Text (Fixed a) #
PersistField v => PersistField (Map Text v) # |
Instance details Defined in Database.Persist.Class.PersistField Methods toPersistValue :: Map Text v -> PersistValue # fromPersistValue :: PersistValue -> Either Text (Map Text v) #
(PersistField a, PersistField b) => PersistField (a, b) # |
Instance details Defined in Database.Persist.Class.PersistField Methods toPersistValue :: (a, b) -> PersistValue # fromPersistValue :: PersistValue -> Either Text (a, b) #

# PersistConfig

class PersistConfig c where #

Represents a value containing all the configuration options for a specific backend. This abstraction makes it easier to write code that can easily swap backends.

Minimal complete definition

loadConfig, createPoolConfig, runPool

Associated Types

type PersistConfigBackend c :: (Type -> Type) -> Type -> Type #

type PersistConfigPool c #

Methods

loadConfig :: Value -> Parser c #

Load the config settings from a `Value`, most likely taken from a YAML config file.

applyEnv :: c -> IO c #

Modify the config settings based on environment variables.

createPoolConfig :: c -> IO (PersistConfigPool c) #

Create a new connection pool based on the given config settings.

runPool :: MonadUnliftIO m => c -> PersistConfigBackend c m a -> PersistConfigPool c -> m a #

Run a database action by taking a connection from the pool.

#### Instances

Instances details

(PersistConfig c1, PersistConfig c2, PersistConfigPool c1 ~ PersistConfigPool c2, PersistConfigBackend c1 ~ PersistConfigBackend c2) => PersistConfig (Either c1 c2) # |
Instance details Defined in Database.Persist.Class.PersistConfig Associated Types
type PersistConfigBackend (Either c1 c2) |
Instance details Defined in Database.Persist.Class.PersistConfig type PersistConfigBackend (Either c1 c2) = PersistConfigBackend c1
type PersistConfigPool (Either c1 c2) |
Instance details Defined in Database.Persist.Class.PersistConfig type PersistConfigPool (Either c1 c2) = PersistConfigPool c1
Methods loadConfig :: Value -> Parser (Either c1 c2) # applyEnv :: Either c1 c2 -> IO (Either c1 c2) # createPoolConfig :: Either c1 c2 -> IO (PersistConfigPool (Either c1 c2)) # runPool :: MonadUnliftIO m => Either c1 c2 -> PersistConfigBackend (Either c1 c2) m a -> PersistConfigPool (Either c1 c2) -> m a #

entityValues :: PersistEntity record => Entity record -> [PersistValue] #

Get list of values corresponding to given entity.

# Lifting

class HasPersistBackend backend where #

Class which allows the plucking of a `BaseBackend backend` from some larger type. For example, `instance HasPersistBackend (SqlReadBackend, Int) where type BaseBackend (SqlReadBackend, Int) = SqlBackend persistBackend = unSqlReadBackend . fst`

Associated Types

type BaseBackend backend #

Methods

persistBackend :: backend -> BaseBackend backend #

#### Instances

Instances details

HasPersistBackend SqlReadBackend # |
Instance details Defined in Database.Persist.Sql.Types.Internal Associated Types
type BaseBackend SqlReadBackend |
Instance details Defined in Database.Persist.Sql.Types.Internal type BaseBackend SqlReadBackend = SqlBackend
Methods persistBackend :: SqlReadBackend -> BaseBackend SqlReadBackend #
HasPersistBackend SqlWriteBackend # |
Instance details Defined in Database.Persist.Sql.Types.Internal Associated Types
type BaseBackend SqlWriteBackend |
Instance details Defined in Database.Persist.Sql.Types.Internal type BaseBackend SqlWriteBackend = SqlBackend
Methods persistBackend :: SqlWriteBackend -> BaseBackend SqlWriteBackend #
HasPersistBackend SqlBackend # |
Instance details Defined in Database.Persist.SqlBackend.Internal Associated Types
type BaseBackend SqlBackend |
Instance details Defined in Database.Persist.SqlBackend.Internal type BaseBackend SqlBackend = SqlBackend
Methods persistBackend :: SqlBackend -> BaseBackend SqlBackend #
(BackendCompatible b s, HasPersistBackend b) => HasPersistBackend (Compatible b s) # |
Instance details Defined in Database.Persist.Compatible.Types Associated Types
type BaseBackend (Compatible b s) |
Instance details Defined in Database.Persist.Compatible.Types type BaseBackend (Compatible b s) = BaseBackend b
Methods persistBackend :: Compatible b s -> BaseBackend (Compatible b s) #

withBaseBackend :: forall backend (m :: Type -> Type) a. HasPersistBackend backend => ReaderT (BaseBackend backend) m a -> ReaderT backend m a #

Run a query against a larger backend by plucking out `BaseBackend backend`

This is a helper for reusing existing queries when expanding the backend type.

Since: 2.12.0

class HasPersistBackend backend => IsPersistBackend backend #

Class which witnesses that `backend` is essentially the same as `BaseBackend backend`. That is, they're isomorphic and `backend` is just some wrapper over `BaseBackend backend`.

Minimal complete definition

mkPersistBackend

#### Instances

Instances details

IsPersistBackend SqlReadBackend # |
Instance details Defined in Database.Persist.Sql.Types.Internal Methods mkPersistBackend :: BaseBackend SqlReadBackend -> SqlReadBackend #
IsPersistBackend SqlWriteBackend # |
Instance details Defined in Database.Persist.Sql.Types.Internal Methods mkPersistBackend :: BaseBackend SqlWriteBackend -> SqlWriteBackend #
IsPersistBackend SqlBackend # |
Instance details Defined in Database.Persist.SqlBackend.Internal Methods mkPersistBackend :: BaseBackend SqlBackend -> SqlBackend #

liftPersist :: (MonadIO m, MonadReader backend m) => ReaderT backend IO b -> m b #

class BackendCompatible sup sub where #

This class witnesses that two backend are compatible, and that you can convert from the `sub` backend into the `sup` backend. This is similar to the `HasPersistBackend` and `IsPersistBackend` classes, but where you don't want to fix the type associated with the `PersistEntityBackend` of a record.

Generally speaking, where you might have:

    foo ::
      ( PersistEntity record
      , PersistEntityBackend record ~ BaseBackend backend
      , IsSqlBackend backend
      )

this can be replaced with:

    foo ::
      ( PersistEntity record,
      , PersistEntityBackend record ~ backend
      , BackendCompatible SqlBackend backend
      )

This works for `SqlReadBackend` because of the `instance `BackendCompatible` `SqlBackend` `SqlReadBackend``, without needing to go through the `BaseBackend` type family.

Likewise, functions that are currently hardcoded to use `SqlBackend` can be generalized:

    -- before:
    asdf :: ReaderT SqlBackend m ()
    asdf = pure ()

    -- after:
    asdf' :: BackendCompatible SqlBackend backend => ReaderT backend m ()
    asdf' = withCompatibleBackend asdf

Since: 2.7.1

Methods

projectBackend :: sub -> sup #

#### Instances

Instances details

BackendCompatible SqlBackend SqlReadBackend # |
Instance details Defined in Database.Persist.Sql.Orphan.PersistStore Methods projectBackend :: SqlReadBackend -> SqlBackend #
BackendCompatible SqlBackend SqlWriteBackend # |
Instance details Defined in Database.Persist.Sql.Orphan.PersistStore Methods projectBackend :: SqlWriteBackend -> SqlBackend #
BackendCompatible SqlBackend SqlBackend # |
Instance details Defined in Database.Persist.Sql.Orphan.PersistStore Methods projectBackend :: SqlBackend -> SqlBackend #

withCompatibleBackend :: forall sup sub (m :: Type -> Type) a. BackendCompatible sup sub => ReaderT sup m a -> ReaderT sub m a #

Run a query against a compatible backend, by projecting the backend

This is a helper for using queries which run against a specific backend type that your backend is compatible with.

Since: 2.12.0

# PersistCore

`PersistCore` is a type class that defines a default database `BackendKey` type. For SQL databases, this is currently an auto-incrementing inteer primary key. For MongoDB, it is the default ObjectID.

class PersistCore backend #

Associated Types

data BackendKey backend #

#### Instances

Instances details

PersistCore SqlReadBackend # |
Instance details Defined in Database.Persist.Sql.Orphan.PersistStore Associated Types
newtype BackendKey SqlReadBackend |
Instance details Defined in Database.Persist.Sql.Orphan.PersistStore newtype BackendKey SqlReadBackend = SqlReadBackendKey { unSqlReadBackendKey :: Int64 }
PersistCore SqlWriteBackend # |
Instance details Defined in Database.Persist.Sql.Orphan.PersistStore Associated Types
newtype BackendKey SqlWriteBackend |
Instance details Defined in Database.Persist.Sql.Orphan.PersistStore newtype BackendKey SqlWriteBackend = SqlWriteBackendKey { unSqlWriteBackendKey :: Int64 }
PersistCore SqlBackend # |
Instance details Defined in Database.Persist.Sql.Orphan.PersistStore Associated Types
newtype BackendKey SqlBackend |
Instance details Defined in Database.Persist.Sql.Orphan.PersistStore newtype BackendKey SqlBackend = SqlBackendKey { unSqlBackendKey :: Int64 }
(BackendCompatible b s, PersistCore b) => PersistCore (Compatible b s) # |
Instance details Defined in Database.Persist.Compatible.Types Associated Types
newtype BackendKey (Compatible b s) |
Instance details Defined in Database.Persist.Compatible.Types newtype BackendKey (Compatible b s) = CompatibleKey { unCompatibleKey :: BackendKey b }

class (PersistEntity record, PersistEntityBackend record ~ backend, PersistCore backend) => ToBackendKey backend record where #

`ToBackendKey` converts a `PersistEntity` `Key` into a `BackendKey` This can be used by each backend to convert between a `Key` and a plain Haskell type. For Sql, that is done with `toSqlKey` and `fromSqlKey`.

By default, a `PersistEntity` uses the default `BackendKey` for its Key and is an instance of ToBackendKey

A `Key` that instead uses a custom type will not be an instance of `ToBackendKey`.

Methods

toBackendKey :: Key record -> BackendKey backend #

fromBackendKey :: BackendKey backend -> Key record #

# JSON utilities

keyValueEntityToJSON :: (PersistEntity record, ToJSON record) => Entity record -> Value #

Predefined `toJSON`. The resulting JSON looks like `{"key": 1, "value": {"name": ...}}`.

The typical usage is:

    instance ToJSON (Entity User) where
        toJSON = keyValueEntityToJSON

keyValueEntityFromJSON :: (PersistEntity record, FromJSON record) => Value -> Parser (Entity record) #

Predefined `parseJSON`. The input JSON looks like `{"key": 1, "value": {"name": ...}}`.

The typical usage is:

    instance FromJSON (Entity User) where
        parseJSON = keyValueEntityFromJSON

entityIdToJSON :: (PersistEntity record, ToJSON record) => Entity record -> Value #

Predefined `toJSON`. The resulting JSON looks like `{"id": 1, "name": ...}`.

The typical usage is:

    instance ToJSON (Entity User) where
        toJSON = entityIdToJSON

entityIdFromJSON :: (PersistEntity record, FromJSON record) => Value -> Parser (Entity record) #

Predefined `parseJSON`. The input JSON looks like `{"id": 1, "name": ...}`.

The typical usage is:

    instance FromJSON (Entity User) where
        parseJSON = entityIdFromJSON

toPersistValueJSON :: ToJSON a => a -> PersistValue #

Convenience function for getting a free `PersistField` instance from a type with JSON instances.

Example usage in combination with `fromPersistValueJSON`:

    instance PersistField MyData where
      fromPersistValue = fromPersistValueJSON
      toPersistValue = toPersistValueJSON

fromPersistValueJSON :: FromJSON a => PersistValue -> Either Text a #

Convenience function for getting a free `PersistField` instance from a type with JSON instances. The JSON parser used will accept JSON values other that object and arrays. So, if your instance serializes the data to a JSON string, this will still work.

Example usage in combination with `toPersistValueJSON`:

    instance PersistField MyData where
      fromPersistValue = fromPersistValueJSON
      toPersistValue = toPersistValueJSON