persistent
Type-safe, multi-backend data serialization.
http://www.yesodweb.com/book/persistent
| Version on this page: | 2.13.1.1 |
| LTS Haskell 24.16: | 2.17.1.0 |
| Stackage Nightly 2025-10-24: | 2.17.1.0 |
| Latest on Hackage: | 2.17.1.0 |
persistent-2.13.1.1@sha256:c8044134d3001b7a06703c821fece7d071e195979ad0eb02805ffaf099e28a2d,6521Module documentation for 2.13.1.1
- Database
- Database.Persist
- Database.Persist.Class
- Database.Persist.EntityDef
- Database.Persist.FieldDef
- Database.Persist.ImplicitIdDef
- Database.Persist.Names
- Database.Persist.PersistValue
- Database.Persist.Quasi
- Database.Persist.Sql
- Database.Persist.Sql.Types
- Database.Persist.Sql.Util
- Database.Persist.SqlBackend
- Database.Persist.TH
- Database.Persist.Types
- Database.Persist
persistent
Type-safe, data serialization. You must use a specific backend in order to make this useful. For more information, see the chapter in the Yesod book.
Changes
Changelog for persistent
2.13.1.1
- #1294
- Fix an issue where documentation comments on fields are in reverse line order.
2.13.1.0
- #1264
- Support declaring Maybe before the type in model definitions
2.13.0.4
- #1277
- Corrected the documentation of
addMigrationto match the actual behaviour - this will not change the behaviour of your code.
- Corrected the documentation of
2.13.0.3
- #1287
- Fix the duplicate entity check for transitive dependencies.
- Fixes an issue where generating code would refer to the
ModelNamewhen making a reference to another table when the explicit code only refers toModelNameId.
2.13.0.2
- #1265
- Support GHC 9
2.13.0.1
- #1268
- Show
keyFromValueserror
- Show
2.13.0.0
- #1244
- Implement config for customising the FK name
- #1252
mkMigratenow defers tomkEntityDefListandmigrateModelsinstead of fixing the foreign key references itself.mkSavewas deprecated - the function did not fix foreign key references. Please usemkEntityDefListinstead.EntityDefwill now include fields markedMigrationOnlyandSafeToRemove. Beforehand, those were filtered out, andmkMigrateapplied. The functiongetEntityFieldswill only return fields defined on the Haskell type - for all columns, seegetEntityFieldsDatabase.
- #1225
-
The fields and constructor for
SqlBackendare no longer exported by default. They are available from an internal module,Database.Persist.Sql.Types.Internal. Breaking changes fromInternalmodules are not reflected in the major version. This will allow us to release new functionality without breaking your code. It’s recommended to switch to using the smart constructor functions and setter functions that are now exported fromDatabase.Persist.Sqlinstead. -
A new API is available for constructing and using a
SqlBackend, provided inDatabase.Persist.SqlBackend. Instead of using theSqlBackenddirectly, usemkSqlBackendand the datatypeMkSqlBackendArgs. TheMkSqlBackendArgsrecord has the same field names as theSqlBackend, so the translation is easy:- SqlBackend + mkSqlBackend MkSqlBackendArgs { connInsertSql = ... , connCommit = ... , connEscapeFieldName = ... , connEscapeTableName = ... , etc }Some fields were omitted in
MkSqlBackendArgs. These fields are optional - they provide enhanced or backend-specific functionality. For these, use the setter functions likesetConnUpsertSql. -
Previously hidden modules are now exposed under the
Internalnamespace. -
The
connLimitOffsetfunction used to have aBoolparameter. This parameter is unused and has been removed.
-
- #1234
- You can now customize the default implied ID column. See the documentation
in
Database.Persist.ImplicitIdDeffor more details. - Moved the various
Nametypes intoDatabase.Persist.Names - Removed the
hasCompositeKeyfunction. SeehasCompositePrimaryKeyandhasNaturalKeyas replacements. - The
EntityDefconstructor and field labels are not exported by default. Get those fromDatabase.Persist.EntityDef.Internal, but you should migrate to the getters/setters inDatabase.Persist.EntityDefas you can. - Added the
Database.Persist.FieldDefandDatabase.Persist.FieldDef.Internalmodules. - The
PersistSettingstype was made abstract. Please migrate to the getters/setters defined in thatDatabase.Persist.Quasi, or useDatabase.Persist.Quasi.Internalif you don’t mind the possibility of breaking changes. - Add the
runSqlCommandfunction for running arbitrary SQL during migrations. - Add
migrateModelsfunction for a TH-free migration facility.
- You can now customize the default implied ID column. See the documentation
in
- #1253
- Add
discoverEntitiesto discover instances of the class and return their entity definitions.
- Add
- #1250
- The
mpsGenericfunction has been deprecated. If you need this functionality, please comment with your needs on the GitHub issue tracker. We may un-deprecate it, or we may provide a new and better means of facilitating a solution to your problem.
- The
- #1255
mkPersistnow checks to see if an instance already exists forPersistEntityfor the inputs.
- #1256
- The QuasiQuoter has been refactored and improved.
- You can now use
mkPersistWithto pass in a list of pre-existingEntityDefto improve foreign key detection and splitting up models across multiple modules. - The
entityIdfield now returns anEntityIdDef, which specifies what the ID field actually is. This is a move to better support natural keys. - Several types that had lists have been refactored to use nonempty lists to better capture the semantics.
mkDeleteCascadeis deprecated. Please use the Cascade behavior directly on fields.- You can use
Key FooandFooIdinterchangeably in fields. - Support for GHC < 8.4 dropped.
2.12.1.2
- #1258
- Support promoted types in Quasi Quoter
- #1243
- Assorted cleanup of TH module
- #1242
- Refactor setEmbedField to use do notation
- #1237
- Remove nonEmptyOrFail function from recent tests
2.12.1.1
- #1231
- Simplify Line type in Quasi module, always use NonEmpty
- #1229
- The
#idlabels are now generated for entities.
- The
2.12.1.0
- #1218
- Refactoring name generating functions in TH
- #1226
- Expose the
filterClauseandfilterClauseWithValuesfunctions to support theupsertWherefunctionality inpersistent-postgresql.
- Expose the
2.12.0.2
- #1123
- Fix JSON encoding for
PersistValue
- Fix JSON encoding for
2.12.0.1
- Refactoring token parsing in quasi module #1206
- Removing duplication from TH output #1202
- Refactor [] to NonEmpty in Quasi module #1193
- #1162
- Replace
askLogFuncwithaskLoggerIO
- Replace
- Decomposed
HaskellNameintoConstraintNameHS,EntityNameHS,FieldNameHS. DecomposedDBNameintoConstraintNameDB,EntityNameDB,FieldNameDBrespectively. #1174 - Use
resourcet-poolto break out someData.Poollogic #1163 - #1178
- Added ‘withBaseBackend’, ‘withCompatible’ to ease use of base/compatible backend queries in external code.
- Added GHC 8.2.2 and GHC 8.4.4 back into the CI and
persistentbuilds on 8.2.2 again #1181 - #1179
- Added
Compatible, a newtype for marking a backend as compatible with another. Use it withDerivingViato derive simple instances based on backend compatibility. - Added
makeCompatibleInstancesandmakeCompatibleKeyInstances, TemplateHaskell invocations for auto-generating standalone derivations usingCompatibleandDerivingVia.
- Added
- #1207
- @codygman discovered a bug in issue #1199 where postgres connections were being returned to the
Pool SqlBackendin an inconsistent state. @parsonsmatt debugged the issue and determined that it had something to do with asynchronous exceptions. Declaring it to be “out of his pay grade,” he ripped thepoolToAcquirefunction out and replaced it withData.Pool.withResource, which doesn’t exhibit the bug. Fortunately, this doesn’t affect the public API, and can be a mere bug release. - Removed the functions
unsafeAcquireSqlConnFromPool,acquireASqlConnFromPool, andacquireSqlConnFromPoolWithIsolation. For a replacement, seerunSqlPoolNoTransactionandrunSqlPoolWithHooks.
- @codygman discovered a bug in issue #1199 where postgres connections were being returned to the
- Renaming values in persistent-template #1203
- #1214:
- Absorbed the
persistent-templatepackage.persistent-templatewill receive a 2.12 release with a warning and a deprecation notice. - Remove the
nooverlapflag. It wasn’t being used anymore.
- Absorbed the
- #1205
- Introduce the
PersistLiteral_constructor, replacing thePersistLiteral,PersistLiteralEscaped, andPersistDbSpecific. - The old constructors are now pattern synonyms. They don’t actually differentiate between the various escaping strategies when consuming them! If you pattern match on multiple of
PersistDbSpecific,PersistLiteral, orPersistLiteralEscaped, then you should use thePersistLiteral_constructor to differentiate between them.
- Introduce the
2.11.0.2
- Fix a bug where an empty entity definition would break parsing of
EntityDefs. #1176
2.11.0.1
- Docs/Bugs fixes #1153
- Fix documentation on
FieldDef.fieldAttrs. - Postgresql backend: Add a space in cascade clause of generated SQL.
- Fix documentation on
2.11.0.0
-
Foreign Key improvements #1121
- It is now supported to refer to a table with an auto generated Primary Kay
- It is now supported to refer to non-primary fields, using the keyword
References - It is now supported to have cascade options for simple/single-field Foreign Keys
-
Introduces a breaking change to the internal function
mkColumns, which can now be passed a record of functions to override its default behavior. #996 -
Added explicit
forallnotation to make most API functions play nice when usingTypeApplications. (e.g. instead ofselectList @_ @_ @User [] [], you can now writeselectList @User [] []) #1006 -
- The QuasiQuoter now supports
OnDeleteandOnUpdatecascade options.
- The QuasiQuoter now supports
-
- Field and constraint labels generated by TH can now be customized.
- mpsPrefixFields is deprecated in favor of using these customisation functions.
-
- Instance for
Naturalis removed. SeeOverflowNaturalfor a replacement and rationale on why.
- Instance for
-
- A new class member
keyFromRecordMallows you to construct aKey recordfrom arecordif it was defined withPrimary.
- A new class member
-
- The method
entityIdFromJSONthat is used to parse entities now correctly works for entities that define a customPrimarykey.
- The method
-
- Modify
upsertByto use backend-specific implementation (if any).
- Modify
-
- You can set a column’s
sql=idfor a nonIdcolumn.
- You can set a column’s
-
Fix a bug where unsafe migration error messages were being shown using
Showprior to printing, resulting in less helpful output. #1080 -
RawSqlnow has tuple instances up to GHC’s max tuple size (62)
-
Locis now imported frommonad-loggeras opposed totemplate-haskell. Removestemplate-haskellas an explicit dependency.
-
- Remove unnecessary deriving of
Typeable.
- Remove unnecessary deriving of
-
- Remove
Monadconstraint onentityDef
- Remove
-
-
Remove deriving of
Showfor uniques. Users that need aShowinstance can put a standalone deriving instance:deriving stock instance Show (Unique User)
-
-
- Add an
existsfunction to thePersistQueryReadtype class.
- Add an
-
- Allow parsing UTCTimes from sqlite with the format “%F %T%Q” as well, instead of only “%FT%T%Q”.
-
- A new function
checkUniqueUpdateableallows you to check uniqueness constraints on an entity update without having to update it.
- A new function
-
- Deprecate
hasCompositeKeyin favor ofhasCustomPrimaryKeyandhasCompositePrimaryKeyfunctions.
- Deprecate
-
- Add support for configuring the number of stripes and idle timeout for connection pools
- For functions that do not specify an idle timeout, the default has been bumped to 600 seconds.
- This change is based off the experience of two production codebases. See #775
- Add a new type
ConnectionPoolConfigto configure the number of connections in a pool, their idle timeout, and stripe size. - Add
defaultConnectionPoolConfigto create aConnectionPoolConfig - Add
createSqlPoolWithConfigandwithSqlPoolWithConfig, which take this new data type
- For functions that do not specify an idle timeout, the default has been bumped to 600 seconds.
- Add support for configuring the number of stripes and idle timeout for connection pools
-
-
Adds a new constructor,
PersistLiteral ByteStringtoPersistValueto support unescaped SQL literals.- Obviously, this is highly unsafe, and you should never use it with user input.
-
Adds a new field,
cGenerated :: Maybe TexttoColumnfor backend-specific support of generated columns.- Express generated fields in the Persistent DSL
GeneratedColumnExample fieldOne Text Maybe fieldTwo Text Maybe fieldThree Text Maybe generated=COALESCE(field_one,field_two)- Support for MySQL >= 5.7. (No version checking is performed! Using this feature with older versions of MySQL will cause runtime SQL exceptions!)
- Support for Postgresql >= 12. (No version checking is performed! Using this feature with older versions of Postgresql will cause runtime SQL exceptions!)
- Support for SQLite >= 3.31 (same caveat applies; support added in #1152 )
-
-
- Allow
OverloadedLabelsto be used with theEntityFieldtype.
- Allow
2.10.5.2
- #1041
- Explicit foreign keys can now reference tables with custom sql name
- Add qualified names to the stock classes list.
2.10.5.1
- #1024
- Add the ability to do documentation comments in entity definition syntax. Unfortunately, TemplateHaskell cannot add documentation comments, so this can’t be used to add Haddocks to entities.
- Add Haddock explainers for some of the supported entity syntax in
Database.Persist.Quasi
2.10.5
- Add the
EntityWithPrefixtype to allow users to specify a custom prefix for raw SQL queries. #1018 - Added Acquire based API to
Database.Persist.Sqlfor working with connections/pools in monads which aren’t MonadUnliftIO. #984
2.10.4
- Log exceptions when closing a connection fails. See point 1 in yesod #1635. #978
2.10.3
- Added support for GHC 8.8 about MonadFail changes #976
2.10.2
- Added
runMigrationQuietandrunMigrationUnsafeQuiettoDatabase.Persist.Sql.Migrationas safer alternatives torunMigrationSilent. #971 This functions as workaround/fix for: #966, #948, #640, and #474 - Added RawSql instances for 9, 10, 11 and 12-column results. #961
2.10.1
- Added
constraint=attribute to allow users to specify foreign reference constraint names.
2.10.0
- Added two type classes
OnlyOneUniqueKeyandAtLeastOneUniqueKey. These classes are used as constraints on functions that expect a certain amount of unique keys. They are defined automatically as part of thepersistent-template’s generation. #885 - Add the
entityCommentsfield to theEntityDefdatatype, andfieldCommentsfields to theFieldDefdatatype. The QuasiQuoter does not currently know how to add documentation comments to these types, but it can be expanded later. #865 - Expose the
SqlReadTandSqlWriteTconstructors. #887 - Remove deprecated
Connectiontype synonym. Please useSqlBackendinstead. #894 - Remove deprecated
SqlPersisttype synonym. Please useSqlPersistTinstead. #894 - Alter the type of
connUpsertSqlto take a list of unique definitions. This paves the way for more efficient upsert implementations. #895
2.9.2
- Add documentation for the
Migrationtype and some helpers. #860
2.9.1
- Fix #847: SQL error with
putManyon Sqlite when Entity has no unique index.
2.9.0
- Added support for SQL isolation levels to via SqlBackend. [#812]
- Move
Database.Persist.Sql.Raw.QQto a separatepersistent-qqpackage #827 - Fix 832:
repsertManynow matchesmapM_ (uncurry repsert)and is atomic for supported sql back-ends.
2.8.2
- Added support for
sql=to the unique constraints quasi-quoter so that users can specify the database names of the constraints.
2.8.1
- DRY-ed up and exposed several util functions in
Database.Persist.Sql.Util.- Upstream-ed
updatePersistValue,mkUpdateText, andcommaSeparatedfromDatabase.Persist.MySQL. - De-duplicated
updatePersistValuefrom variousDatabase.Persist.Sql.Orphan.*modules.
- Upstream-ed
- Batching enhancements to reduce db round-trips.
- Added
getManyandrepsertManyfor batchedgetandrepsert. - Added
putManywith a default/slow implementation. SqlBackend’s that support native UPSERT should override this for batching enhancements. - Updated
insertEntityManyto replace slow looped usage with batched execution.
- Added
- See #770
2.8.0
- Switch from
MonadBaseControltoMonadUnliftIO - Reapplies #723, which was reverted in version 2.7.3.
2.7.3.1
- Improve error messages when failing to parse database results into Persistent records. #741
- A handful of
fromPersistFieldimplementations callederrorinstead of returning aLeft Text. All of the implementations were changed to returnLeft. #741 - Improve error message when a SQL insert fails with a custom primary key #757
2.7.3
- Reverts #723, which generalized functions using the
BackendCompatibleclass. These changes were an accidental breaking change. - Recommend the
PersistDbSpecificdocs if someone gets an error about converting fromPersistDbSpecific
2.7.2 [DEPRECATED ON HACKAGE]
- Many of the functions have been generalized using the
BackendCompatibleclass. #723- This change was an accidental breaking change and was reverted in 2.7.3.
- These change will be released in a future version of Persistent with a major version bump.
- Add raw sql quasi quoters #717
2.7.1
2.7.0
- Fix upsert behavior #613
- Atomic upsert query fixed for arithmatic operations #662
- Haddock and test coverage improved for upsert
2.6.1
- Fix edge case for
\<-. [Nothing] - Introduce
connMaxParams - Add ‘getJustEntity’ and ‘insertRecord’ convenience function
- Minor Haddock improvment
2.6
- Add
connUpsertSqltype for providing backend-specific upsert sql support.
2.5
- read/write typeclass split
- add insertOrGet convenience function to PersistUnique
2.2.4.1
- Documentation updates #515
2.2.4
- Workaround for side-exiting transformers in
runSqlConn#516
2.2.3
- PersistField instance for Natural
- better oracle support in odbc
2.2.2
- Add liftSqlPersistMPool function
- support http-api-data for url serialization
2.2.1
- Migration failure message with context
- Fix insertKey for composite keys
2.2
- Add a
RawSqlinstance forKey. This allows selecting primary keys using functions likerawSql. #407 - SqlBackend support for an optimized
insertMany
2.1.6
Important! If persistent-template is not upgraded to 2.1.3.3
you might need to make sure Int64 is in scope for your model declarations.
- add showMigration function
- explicitly use Int64 for foreign key references
2.1.5
Add dbIdColumnsEsc to Sql.Utils.
Used in persistent-postgresql 2.1.5.2
2.1.4
- Fix getBy with a primary key. #342
2.1.3
- Break self-referencing cycles in the entity declarations
2.1.2
- Error with
Doubles without a decimal part #378 runSqlPooldoes not perform timeout checks.
2.1.1.6
- One extra feature for #939: use
logDebugNinstead
2.1.1.5
- Better SQL logging Yesod issue #939
2.1.1.3
Parse UTCTime in 8601 format #339
2.1.1.1
Support for monad-control 1.0