h$6      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~                                                                                          +None ?  persistentRepresents a value containing all the configuration options for a specific backend. This abstraction makes it easier to write code that can easily swap backends. persistent Load the config settings from a -, most likely taken from a YAML config file. persistent:Modify the config settings based on environment variables. persistentCreate a new connection pool based on the given config settings. persistent;Run a database action by taking a connection from the pool.None  ;?|   persistentAn ' represents the Haskell-side name that  persistent will use for a constraint.   persistentA  ) represents the datastore-side name that  persistent will use for a constraint.  persistentAn ) represents the datastore-side name that  persistent will use for an entity.  persistentAn ' represents the Haskell-side name that  persistent will use for an entity.  persistentA ' represents the Haskell-side name that  persistent will use for a field.  persistentAn ) represents the datastore-side name that  persistent will use for an entity.  persistent8Convenience operations for working with '-NameDB' types.  persistent  persistent   None  ? =  persistent?A type that determines how a backend should handle the literal.>  persistentThe accompanying value will be escaped before inserting into the database. This is the correct default choice to use.?  persistentThe accompanying value will not be escaped when inserting into the database. This is potentially dangerous - use this with care.@  persistentThe @( constructor corresponds to the legacy S constructor. We need to keep this around because old databases may have serialized JSON representations that reference this. We don't want to break the ability of a database to load rows.A persistentA raw value which can be stored in any backend and can be marshalled to and from a  PersistField.N persistent'Intended especially for MongoDB backendO persistent:Intended especially for PostgreSQL backend for text arraysP  persistentThis constructor is used to specify some raw literal value for the backend. The = value specifies how the value should be escaped. This can be used to make special, custom types avaialable in the back end.Q  persistent6This pattern synonym used to be a data constructor on A, but was changed into a catch-all pattern synonym to allow backwards compatiblity with database types. See the documentation on S for more details.R  persistent6This pattern synonym used to be a data constructor on A, but was changed into a catch-all pattern synonym to allow backwards compatiblity with database types. See the documentation on S for more details.S  persistent?AQRSBCDEFGHIJKLMNOPQRST.=@>?APONMLKJIHGFEDBCQRSTAQRSBCDEFGHIJKLMNOPQRS Safe-Inferred ? ,b persistentPlease refer to the documentation for the database in question for a full overview of the semantics of the varying isloation levelsbfedcgbfedcg None .;?Pm persistentA m represents the inormation that  persistent knows about a field of a datatype. This includes information used to parse the field out of the database and what the field corresponds to.o persistentThe name of the field. Note that this does not corresponds to the record labels generated for the particular entity - record labels are generated with the type name prefixed to the field, so a m that contains a  "name" for a type User will have a record field userName.p persistentThe name of the field in the database. For SQL databases, this corresponds to the column name.q persistent!The type of the field in Haskell.r persistent(The type of the field in a SQL database.s persistent:User annotations for a field. These are provided with the ! operator.t persistent If this is , then the Haskell datatype will have a strict record field. The default value for this is .v  persistentDefines how operations on the field cascade on to the referenced tables. This doesn't have any meaning if the u is set to  or . The cascade option here should be the same as the one obtained in the u.w  persistentOptional comments for a Field. There is not currently a way to attach comments to a field in the quasiquoter.x  persistentWhether or not the field is a  GENERATED column, and additionally the expression to use for generation.y  persistent( if the field is an implicit ID column.  otherwise. persistentA SQL data type. Naming attempts to reflect the underlying Haskell datatypes, eg SqlString instead of SqlVarchar. Different SQL databases may have different translations for these types. persistentAlways uses UTC timezone persistenta backend-specific name persistentGeneric Exception  persistentAn action that might happen on a deletion or update on a foreign key change.  persistentThis datatype describes how a foreign reference field cascades deletes or updates.This type is used in both parsing the model definitions and performing migrations. A  in either of the field values means that the user has not specified a . An unspecified  is defaulted to  when doing migrations.  persistent>Determine how the field will cascade on updates and deletions.  persistentUsed instead of FieldDef to generate a smaller amount of code persistentType for storing the Uniqueness constraint in the Schema. Assume you have the following schema with a uniqueness constraint: /Person name String age Int UniqueAge age This will be represented as: :UniqueDef { uniqueHaskell = ConstraintNameHS (packPTH  UniqueAge) , uniqueDBName = ConstraintNameDB (packPTH "unique_age") , uniqueFields = [(FieldNameHS (packPTH "age"), FieldNameDB (packPTH "age"))] , uniqueAttrs = [] }  persistentAn EmbedFieldDef is the same as a FieldDef But it is only used for embeddedFields so it only has data needed for embedding persistentAn EmbedEntityDef is the same as an EntityDef But it is only used for fieldReference so it only has data needed for embedding persistentThere are 3 kinds of references 1) composite (to fields that exist in the record) 2) single field 3) embedded persistentA ForeignRef has a late binding to the EntityDef it references via name and has the Haskell type of the foreign key in the form of FieldType persistentA SelfReference stops an immediate cycle which causes non-termination at compile-time (issue #311). persistentA  describes a field parsed from the QuasiQuoter and is used to determine the Haskell type in the generated code. name Text parses into FTTypeCon Nothing Text name T.Text parses into FTTypeCon (Just T Text)name (Jsonb User) parses into: FTApp (FTTypeCon Nothing Jsonb) (FTTypeCon Nothing User)  persistentOptional module and name.  persistentAttributes that may be attached to fields that can affect migrations and serialization in backend-specific ways.While we endeavor to, we can't forsee all use cases for all backends, and so ' is extensible through its constructor . persistentThe  keyword goes after the type. This indicates that the column is nullable, and the generated Haskell code will have a  type for it.Example: User name Text Maybe  persistentThis indicates that the column is nullable, but should not have a : type. For this to work out, you need to ensure that the  PersistField2 instance for the type in question can support a K value. data What = NoWhat | Hello Text instance PersistField What where fromPersistValue PersistNull = pure NoWhat fromPersistValue pv = Hello  $ fromPersistValue pv instance PersistFieldSql What where sqlType _ = SqlString User what What nullable  persistentThis tag means that the column will not be present on the Haskell code, but will not be removed from the database. Useful to deprecate fields in phases.You should set the column to be nullable in the database. Otherwise, inserts won't have values. 5User oldName Text MigrationOnly newName Text  persistentA  SafeToRemove attribute is not present on the Haskell datatype, and the backend migrations should attempt to drop the column without triggering any unsafe migration warnings.Useful after you've used  MigrationOnly1 to remove a column from the database in phases. 4User oldName Text SafeToRemove newName Text  persistentThis attribute indicates that we should create a foreign key reference from a column. By default,  persistent will try and create a foreign key reference for a column if it can determine that the type of the column is a Key entity or an EntityId and the Entity's name was present in  mkPersist.This is useful if you want to use the explicit foreign key syntax. Post title Text Comment postId PostId noreference Foreign Post fk_comment_post postId  persistentThis is set to specify precisely the database table the column refers to. Post title Text Comment postId PostId references="post" You should not need this -  persistent should be capable of correctly determining the target table's name. If you do need this, please file an issue describing why. persistentSpecify a name for the constraint on the foreign key reference for this table. Post title Text Comment postId PostId constraint="my_cool_constraint_name"  persistent'Specify the default value for a column. 2User createdAt UTCTime default="NOW()"  Note that a default= attribute does not mean you can omit the value while inserting. persistentSpecify a custom SQL type for the column. Generally, you should define a custom datatype with a custom PersistFieldSql! instance instead of using this. "User uuid Text sqltype=UUID  persistentSet a maximum length for a column. Useful for VARCHAR and indexes. :User name Text maxlen=200 UniqueName name  persistent(Specify the database name of the column. 4User blarghle Int sql="b_l_a_r_g_h_l_e" Useful for performing phased migrations, where one column is renamed to another column over time. persistentA grab bag of random attributes that were unrecognized by the parser.  persistent/The definition for the entity's primary key ID.  persistentThe entity has a single key column, and it is a surrogate key - that is, you can't go from rec -> Key rec.  persistent7The entity has a natural key. This means you can write rec -> Key rec9 because all the key fields are present on the datatype.+A natural key can have one or more columns. persistentAn ! represents the information that  persistent knows about an Entity. It uses this information to generate the Haskell datatype, the SQL migrations, and other relevant conversions. persistent1The name of the entity as Haskell understands it. persistent;The name of the database table corresponding to the entity. persistent'The entity's primary key or identifier. persistentThe  persistent+ entity syntax allows you to add arbitrary s to an entity using the !5 operator. Those attributes are stored in this list. persistentThe fields for this entity. Note that the ID field will not be present in this list. To get all of the fields for an entity, use . persistent+The Uniqueness constraints for this entity. persistentThe foreign key relationships that this entity has to other entities. persistent>A list of type classes that have been derived for this entity. persistentWhether or not this entity represents a sum type in the database.  persistent Optional comments on the entity. persistentThe reason why a field is nullable< is very important. A field that is nullable because of a Maybe& tag will have its type changed from A to Maybe A0. OTOH, a field that is nullable because of a nullable% tag will remain with the same type. persistentA  should be used as a field type whenever a uniqueness constraint should guarantee that a certain kind of record may appear at most once, but other kinds of records may appear any number of times.NOTE: You need to mark any  Checkmark fields as nullable (see the following example).For example, suppose there's a Location0 entity that represents where a user has lived: Location user UserId name Text current Checkmark nullable UniqueLocation user current The UniqueLocation" constraint allows any number of  Locations to be current&. However, there may be at most one current Location/ per user (i.e., either zero or one per user).9This data type works because of the way that SQL treats NULLable fields within uniqueness constraints. The SQL standard says that NULL9 values should be considered different, so we represent  as SQL NULL, thus allowing any number of , records. On the other hand, we represent  as TRUE<, so the uniqueness constraint will disallow more than one  record.Note: There may be DBMSs that do not respect the SQL standard's treatment of NULL values on uniqueness constraints, please check if this data type works before relying on it.The SQL BOOLEAN type is used because it's the smallest data type available. Note that we never use FALSE, just TRUE and NULL. Provides the same behavior Maybe () would if () was a valid  PersistField. persistentWhen used on a uniqueness constraint, there may be at most one  record. persistentWhen used on a uniqueness constraint, there may be any number of  records. persistent Return the [m] for the entity keys. persistent Returns a  list of m. that correspond with the key columns for an .  persistentParse raw field attributes into structured form. Any unrecognized attributes will be preserved, identically as they are encountered, as  values.  persistentReturns  if the m does not have a  MigrationOnly or  SafeToRemove flag from the QuasiQuoter.  persistentA  that does nothing.  persistent Renders a 3 value such that it can be used in SQL migrations.  persistent Render a  to , such that it can be used in a SQL command.=>?@AQRSBCDEFGHIJKLMNOPTmnywvtrqusxpoz~}|{ None  ?Rk persistentA  is a representation of a database query that has been prepared and stored on the server side. None ?R None  ?[u  persistent5This type shares many of the same field names as the  SqlBackend type. It's useful for library authors to use this when migrating from using the  SqlBackend constructor directly to the  mkSqlBackend function.?This type will only contain required fields for constructing a  SqlBackend. For fields that aren't present on this record, you'll want to use the various set functions or persistentThis function should prepare a  in the target database, which should allow for efficient query reuse. persistentThis function generates the SQL and values necessary for performing an insert against the database. persistent(A reference to the cache of statements. s are keyed by the  queries that generated them. persistent Close the underlying connection. persistent>This function returns the migrations required to include the  parameter in the [] database. This might include creating a new table if the entity is not present, or altering an existing table if it is. persistent>A function to begin a transaction for the underlying database. persistent>A function to commit a transaction to the underlying database. persistentA function to roll back a transaction on the underlying database.  persistentA function to extract and escape the name of the column corresponding to the provided field.  persistentA function to extract and escape the name of the table corresponding to the provided entity. PostgreSQL uses this to support schemas.  persistentA function to escape raw DB identifiers. MySQL uses backticks, while PostgreSQL uses quotes, and so on. persistent#A tag displaying what database the  SqlBackend is for. Can be used to differentiate features in downstream libraries for different database backends. persistentAttach a 'LIMIT/OFFSET' clause to a SQL query. Note that LIMIT/OFFSET is problematic for performance, and indexed range queries are the superior way to offer pagination. persistentA log function for the  SqlBackend to use.None ?[mnpoxsuqrtvwymnpoxsuqrtvwyNone ?]&  persistent Replace the m  with the new list.  persistent$Modify the list of field attributes.  persistent1Add an attribute to the list of field attributes.mmNone ?] None ?d5  persistentRetrieve the list of  from an %. This currently does not include a Primary. key, if one is defined. A future version of  persistent will include a Primary key among the Unique constructors for the Entity.  persistent.Retrieve the Haskell name of the given entity.  persistent.Return the database name for the given entity.  persistent  persistent  persistentRetrieve the list of m( that makes up the fields of the entity.'This does not return the fields for an Id column or an implicit id2. It will return the key columns if you used the Primary& syntax for defining the primary key.,This does not return fields that are marked  SafeToRemove or  MigrationOnly - so it only returns fields that are represented in the Haskell type. If you need those fields, use .  persistentThis returns all of the m defined for the -, including those fields that are marked as  MigrationOnly2 (and therefore only present in the database) or  SafeToRemove (and a migration will drop the column if it exists in the database).>For all the fields that are present on the Haskell-type, see .  persistent  persistent  persistent  persistentSet an  to be the given m.  persistent  persistent  persistentPerform a mapping function over all of the entity fields, as determined by . None '(/>?nj  persistent Prior to persistent-2.11.0, we provided an instance of  for the # type. This was in error, because  represents an infinite value, and databases don't have reasonable types for this.The instance for  used the  underlying type, which will cause underflow and overflow errors. This type has the exact same code in the instances, and will work seamlessly.(A more appropriate type for this is the  series of types from  Data.Word. These have a bounded size, are guaranteed to be non-negative, and are quite efficient for the database to store. persistentThis class teaches Persistent how to take a custom type and marshal it to and from a A), allowing it to be stored in a database.ExamplesSimple Newtype You can use newtype: to add more type safety/readability to a basis type like . In these cases, just derive  and PersistFieldSql: {-# LANGUAGE GeneralizedNewtypeDeriving #-} newtype HashedPassword = HashedPassword  deriving (Eq, Show, , PersistFieldSql) Smart Constructor NewtypeIn this example, we create a  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 1 deriving (Eq, Show, PersistFieldSql) mkSSN ::  ->   SSN mkSSN t = if (T.length t == 9) && (T.all C.isDigit t) then  $ SSN t else " $ "Invalid SSN: " <> t instance  SSN where  (SSN t) = B t  (B t) = mkSSN t -- Handle cases where the database does not give us PersistText  x =  $ "File.hs: When trying to deserialize an SSN: expected PersistText, received: " <> T.pack (show x) Tips:This file contain dozens of ( instances you can look at for examples.Typically custom % instances will only accept a single A constructor in . Internal $ instances accept a wide variety of As 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. persistent FIXME Add documentation to that.  None '(/28>?A#  persistent!This type class is used with the OverloadedLabels< extension to provide a more convenient means of using the  type.  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  is UserName. With this, we can write  #name ::  User Text.What's more fun is that the type is more general: it's actually  #name :: (. "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. persistent2Datatype that represents an entity, with both its ( and its Haskell record representation.When using a SQL-based backend (such as SQLite or PostgreSQL), an  may take any number of columns depending on how many fields it has. In order to reconstruct your entity on the Haskell side,  persistent needs all of your entity columns and in the right order. Note that you don't need to worry about this when using  persistent's API since everything is handled correctly behind the scenes.However, if you want to issue a raw SQL command that returns an , then you have to be careful with the column order. While you could use SELECT Entity.* WHERE ... and that would work most of the time, there are times when the order of the columns on your database is different from the order that  persistent expects (for example, if you add a new field in the middle of you entity definition and then use the migration code --  persistent will expect the column to be in the middle, but your DBMS will put it as the last column). So, instead of using a query like the one above, you may use !" (from the Database.Persist.GenericSql module) with its /entity selection placeholder/ (a double question mark ?? ). Using rawSql$ the query above must be written as SELECT ?? WHERE ... Then rawSql will replace ?? with the list of all columns that we need from your entity in the right order. If your query returns two entities (i.e. %(Entity backend a, Entity backend b)), then you must you use SELECT ??, ?? WHERE ... , and so on.  persistentValue to filter with. Highly dependant on the type of filter used. persistent Filters which are available for select,  updateWhere and  deleteWhere. Each filter constructor specifies the field being filtered on, the type of comparison applied (equals, not equals, etc) and the argument for the comparison.1Persistent users use combinators to create these.1Note that it's important to be careful about the  that you are using, if you use this directly. For example, using the  2 requires that you have an array- or list-shaped . It is possible to construct values using this that will create malformed runtime values. persistent3convenient for internal use, not needed for the API persistentQuery options.$Persistent users use these directly. persistentUpdating a database entity.1Persistent users use combinators to create these. persistentPersistent serialized Haskell records to the database. A Database > (A row in SQL, a document in MongoDB, etc) corresponds to a  plus a Haskell record.For every Haskell record type stored in the database there is a corresponding  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 , 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. persistent:Persistent allows multiple different backends (databases). persistentBy default, a backend will automatically generate the key Instead you can specify a Primary key made up of unique values. persistentAn  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 3 values polymorphically. See the documentation on  for more information. persistentUnique keys besides the . persistentA lower-level key operation. persistentA lower-level key operation. persistent!A meta-operation to retrieve the  . persistent Retrieve the  meta-data for the record. persistentReturn meta-data for a given . persistent8A meta-operation to get the database fields of a record. persistentA lower-level operation to convert from database values to a Haskell record. persistent%A meta operation to retrieve all the  keys. persistentA lower level operation. persistentA lower level operation. persistentUse a  as a lens.  persistent Extract a  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. persistent$Textual representation of the record persistent1Get list of values corresponding to given entity. persistent Predefined toJSON!. The resulting JSON looks like "{"key": 1, "value": {"name": ...}}.The typical usage is: instance ToJSON (Entity User) where toJSON = keyValueEntityToJSON  persistent Predefined  parseJSON. The input JSON looks like "{"key": 1, "value": {"name": ...}}.The typical usage is: instance FromJSON (Entity User) where parseJSON = keyValueEntityFromJSON  persistent Predefined toJSON!. The resulting JSON looks like {"id": 1, "name": ...}.The typical usage is: instance ToJSON (Entity User) where toJSON = entityIdToJSON  persistent Predefined  parseJSON. The input JSON looks like {"id": 1, "name": ...}.The typical usage is: instance FromJSON (Entity User) where parseJSON = entityIdFromJSON  persistent(Convenience function for getting a free + instance from a type with JSON instances."Example usage in combination with : instance PersistField MyData where fromPersistValue = fromPersistValueJSON toPersistValue = toPersistValueJSON  persistent(Convenience function for getting a free  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 : instance PersistField MyData where fromPersistValue = fromPersistValueJSON toPersistValue = toPersistValueJSON  persistent(Convenience function for getting a free  instance from a type with an  instance. The function derivePersistField from the persistent-template package should generally be preferred. However, if you want to ensure that an ORDER BY clause that uses your field will order rows by the data constructor order, this is a better choice."Example usage in combination with : data SeverityLevel = Low | Medium | Critical | High deriving (Enum, Bounded) instance PersistField SeverityLevel where fromPersistValue = fromPersistValueEnum toPersistValue = toPersistValueEnum  persistent(Convenience function for getting a free  instance from a type with an * instance. This function also requires a - instance to improve the reporting of errors."Example usage in combination with : data SeverityLevel = Low | Medium | Critical | High deriving (Enum, Bounded) instance PersistField SeverityLevel where fromPersistValue = fromPersistValueEnum toPersistValue = toPersistValueEnum   persistentThis instance delegates to  to provide OverloadedLabels support to the  type.::None ?R =@>?APONMLKJIHGFEDCBSQRTmnywvtrqusxpoz~}|{=@>?APONMLKJIHGFEDCBSQRSQRmnywvtrqusxpoz~}|{None #$&2;?0  persistentA pairing of the  for the source table to the  for the target table.  persistentThe column on the source table.  persistentThe column on the target table. persistent2A list of fields present on the foreign reference.  persistentIf no  References keyword is supplied, then it is assumed that you are referring to the Primary key or Id of the target entity.  persistentYou can specify the exact columns you're referring to here, if they aren't part of a primary key. Most databases expect a unique index on the columns you refer to, but Persistent doesnt' check that. User Id UUID default="uuid_generate_v1mc()" name Text UniqueName name Dog ownerName Text Foreign User fk_dog_user ownerName References name   persistent)Define an explicit foreign key reference. User name Text email Text Primary name email Dog ownerName Text ownerEmail Text Foreign User fk_dog_user ownerName ownerEmail   persistentFields in the source entity.  persistentThe # which needs information filled in.This value is unreliable. See the parsing code to see what data is filled in here. persistent)A definition for a composite primary key.@since.2.13.0.0  persistent$The field names for the primary key.  persistentA list of attributes defined on the primary key. This is anything that occurs after a ! character.  persistentThis type represents an Id' declaration in the QuasiQuoted syntax. IdThis uses the implied settings, and is equivalent to omitting the Id statement entirely. Id Text-This will set the field type of the ID to be . Id Text sql=foo_id-This will set the field type of the Id to be  and the SQL DB name to be foo_id. Id FooId+This results in a shared primary key - the FooId refers to a Foo table. Id FooId OnDelete Cascade/You can set a cascade behavior on an ID column.  persistentThe specification for how an entity's primary key should be formed.Persistent requires that every table have a primary key. By default, an implied ID is assigned, based on the mpsImplicitIdDef field on MkPersistSettings. Because we can't access that type at parse-time, we defer that decision until later.  persistentA  contains columns that are defined on the datatype itself. This is defined using the Primary0 keyword and given a non-empty list of columns. ?User name Text email Text Primary name email A natural key may also contain only a single column. A natural key with multiple columns is called a 'composite key'.  persistentA surrogate key is not part of the domain model for a database table. You can specify a custom surro1You can specify a custom surrogate key using the Id syntax. #User Id Text name Text Note that you must provide a default=- expression when using this in order to use insert or related functions. The  insertKey function can be used instead, as it allows you to specify a key directly. Fixing this issue is tracked in #1247 on GitHub.  persistent6The default key for the entity using the settings in MkPersistSettings.&This is implicit - a table without an Id or Primary declaration will have a .  persistentA representation of a database column, with everything that can be known at parse time.  persistentThe Haskell name of the field. This is parsed directly from the definition, and is used to generate the Haskell record field and the  EntityField definition.  persistentThe database name of the field. By default, this is determined by the 6 record at parse time. You can customize this with a sql= attribute:  name Text sql=foo_name   persistentThe attributes present on the field. For rules on parsing and utility, see the comments on the datatype.  persistentWhether or not the field should be strict in the generated Haskell code.  persistent8The type of the field, as far as is known at parse time.,The TemplateHaskell code will reconstruct a Type4 out of this, but the names will be imported as-is.  persistentWe parse if there's a  on the field. If the field is not a reference, this information is ignored. $Post user UserId OnDeleteCascade   persistentContains an expression to generate the column. If this is present, then the column will not be written to the database, but generated by the expression every time. Item subtotal Int taxRate Rational total Int generated="subtotal * tax_rate"   persistentAny comments present on the field. Documentation comments use a Haskell-like syntax, and must be present before the field in question. Post -- | This is the blog post title. title Text -- | You can have multi-line comments. -- | But each line must have the pipe character. author UserId   persistentAn  produced by the QuasiQuoter. It contains information that the QuasiQuoter is capable of knowing about the entities. It is inherently unfinished, though - there are many other Unbound2 datatypes that also contain partial information.The  is not complete or reliable - to know which fields are safe to use, consult the parsing code.This type was completely internal until 2.13.0.0, when it was exposed as part of the Database.Persist.Quasi.Internal module.6TODO: refactor this so we can expose it for consumers.  persistent3A list of foreign definitions on the parsed entity.  persistent>> mkKeyConType (EntityNameHS "Hello) FTTypeCon Nothing HelloId   persistentCreates a default ID field.  persistentReturns  if the  does not have a  MigrationOnly or  SafeToRemove flag from the QuasiQuoter.  persistent Return the  for an .None  2?/  persistentRetrieve the function in the . that modifies the names into database names.  persistentSet the name modification function that translates the QuasiQuoted names for use in the database.  persistentSet a custom function used to create the constraint name for a foreign key.  persistentA preset configuration function that puts an underscore between the entity name and the constraint name when creating a foreign key constraint name  persistentRetrieve whether or not the ( will generate code with strict fields.  persistentSet whether or not the  will make fields strict.  persistent"Retrievce the default name of the id column.  persistentSet the default name of the id column.  None  -? persistentCreate a new record in the database, returning an automatically created key (in SQL an auto-increment id). Example usageUsing  #schema-persist-store-1schema-1 and  #dataset-persist-store-1 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-persist-store-1 dataset-1, will produce this: +-----+------+-----+ |id |name |age | +-----+------+-----+ |1 |SPJ |40 | +-----+------+-----+ |2 |Simon |41 | +-----+------+-----+ |3 |John |30 | +-----+------+-----+ persistentSame as , but doesn't return a Key. Example usagewith  #schema-persist-store-1schema-1 and  #dataset-persist-store-1 dataset-1, insertJohn :: MonadIO m => ReaderT SqlBackend m (Key User) insertJohn = insert_ $ User "John" 30 The above query when applied on  #dataset-persist-store-1 dataset-1, will produce this: +-----+------+-----+ |id |name |age | +-----+------+-----+ |1 |SPJ |40 | +-----+------+-----+ |2 |Simon |41 | +-----+------+-----+ |3 |John |30 | +-----+------+-----+ persistent9Create multiple records in the database and return their s.If you don't need the inserted s, use .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 usagewith  #schema-persist-store-1schema-1 and  #dataset-persist-store-1 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-persist-store-1 dataset-1, will produce this: +-----+------+-----+ |id |name |age | +-----+------+-----+ |1 |SPJ |40 | +-----+------+-----+ |2 |Simon |41 | +-----+------+-----+ |3 |John |30 | +-----+------+-----+ |4 |Nick |32 | +-----+------+-----+ |5 |Jane |20 | +-----+------+-----+ persistentSame as , but doesn't return any s.The MongoDB, PostgreSQL, SQLite and MySQL backends insert all records in one database query. Example usageWith  #schema-persist-store-1schema-1 and  #dataset-persist-store-1 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-persist-store-1 dataset-1, will produce this: +-----+------+-----+ |id |name |age | +-----+------+-----+ |1 |SPJ |40 | +-----+------+-----+ |2 |Simon |41 | +-----+------+-----+ |3 |John |30 | +-----+------+-----+ |4 |Nick |32 | +-----+------+-----+ |5 |Jane |20 | +-----+------+-----+ persistentSame as , but takes an  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 usageWith  #schema-persist-store-1schema-1 and  #dataset-persist-store-1 dataset-1, insertUserEntityMany :: MonadIO m => ReaderT SqlBackend m () insertUserEntityMany = insertEntityMany [SnakeEntity, EvaEntity] The above query when applied on  #dataset-persist-store-1 dataset-1, will produce this: +-----+------+-----+ |id |name |age | +-----+------+-----+ |1 |SPJ |40 | +-----+------+-----+ |2 |Simon |41 | +-----+------+-----+ |3 |Snake |38 | +-----+------+-----+ |4 |Eva |38 | +-----+------+-----+ persistent8Create a new record in the database using the given key. Example usageWith  #schema-persist-store-1schema-1 and  #dataset-persist-store-1 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-persist-store-1 dataset-1, will produce this: +-----+------+-----+ |id |name |age | +-----+------+-----+ |1 |SPJ |40 | +-----+------+-----+ |2 |Simon |41 | +-----+------+-----+ |3 |Alice |20 | +-----+------+-----+ persistent;Put the record in the database with the given key. Unlike , if a record with the given key does not exist then a new record will be inserted. Example usageWe try to explain upsertBy using  #schema-persist-store-1schema-1 and  #dataset-persist-store-1 dataset-1.First, we insert Philip to  #dataset-persist-store-1 dataset-1. insertPhilip :: MonadIO m => ReaderT SqlBackend m (Key User) insertPhilip = insert $ User "Philip" 42 philipId <- insertPhilipThis 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| +-----+-----------------+--------+3 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-persist-store-1 dataset-1 will produce this: +-----+------+-----+ |id |name |age | +-----+------+-----+ |1 |SPJ |40 | +-----+------+-----+ |2 |Simon |41 | +-----+------+-----+ |3 |X |999 | +-----+------+-----+ persistent$Put many entities into the database.Batch version of  for SQL backends.Useful when migrating data from one entity to another and want to preserve ids. Example usageWith  #schema-persist-store-1schema-1 and  #dataset-persist-store-1 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-persist-store-1 dataset-1, will produce this: +-----+----------------+---------+ |id |name |age | +-----+----------------+---------+ |1 |SPJ |40 | +-----+----------------+---------+ |2 |Simon -> Philip |41 -> 20 | +-----+----------------+---------+ |999 |Mr. X |999 | +-----+----------------+---------+ persistentReplace 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  or  in these cases. Example usageWith  #schema-persist-store-1schema-1 schama-1 and  #dataset-persist-store-1 dataset-1, replaceSpj :: MonadIO m => User -> ReaderT SqlBackend m () replaceSpj record = replace spjId record The above query when applied on  #dataset-persist-store-1 dataset-1, will produce this: +-----+------+-----+ |id |name |age | +-----+------+-----+ |1 |Mike |45 | +-----+------+-----+ |2 |Simon |41 | +-----+------+-----+ persistentDelete a specific record by identifier. Does nothing if record does not exist. Example usageWith  #schema-persist-store-1schema-1 and  #dataset-persist-store-1 dataset-1, deleteSpj :: MonadIO m => ReaderT SqlBackend m () deleteSpj = delete spjId The above query when applied on  #dataset-persist-store-1 dataset-1, will produce this: +-----+------+-----+ |id |name |age | +-----+------+-----+ |2 |Simon |41 | +-----+------+-----+ persistent.Update individual fields on a specific record. Example usageWith  #schema-persist-store-1schema-1 and  #dataset-persist-store-1 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-persist-store-1 dataset-1, will produce this: +-----+------+-----+ |id |name |age | +-----+------+-----+ |1 |SPJ |140 | +-----+------+-----+ |2 |Simon |41 | +-----+------+-----+ persistentUpdate 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 usageWith  #schema-persist-store-1schema-1 and  #dataset-persist-store-1 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-persist-store-1 dataset-1, will produce this: +-----+------+-----+ |id |name |age | +-----+------+-----+ |1 |SPJ |140 | +-----+------+-----+ |2 |Simon |41 | +-----+------+-----+ persistent)Get a record by identifier, if available. Example usageWith  #schema-persist-store-1schema-1 and  #dataset-persist-store-1 dataset-1, getSpj :: MonadIO m => ReaderT SqlBackend m (Maybe User) getSpj = get spjId mspj <- getSpj The above query when applied on  #dataset-persist-store-1 dataset-1, will get this: +------+-----+ | name | age | +------+-----+ | SPJ | 40 | +------+-----+ persistent?Get many records by their respective identifiers, if available. Example usageWith  #schema-persist-store-1schema-1 and  #dataset-persist-store-1 dataset-1: getUsers :: MonadIO m => ReaderT SqlBackend m (Map (Key User) User) getUsers = getMany allkeys musers <- getUsers The above query when applied on  #dataset-persist-store-1 dataset-1, will get these records: +----+-------+-----+ | id | name | age | +----+-------+-----+ | 1 | SPJ | 40 | +----+-------+-----+ | 2 | Simon | 41 | +----+-------+-----+ persistent converts a   into a 8 This can be used by each backend to convert between a 7 and a plain Haskell type. For Sql, that is done with toSqlKey and  fromSqlKey.By default, a  uses the default 0 for its Key and is an instance of ToBackendKeyA = that instead uses a custom type will not be an instance of . persistent-A convenient alias for common type signatures persistentThis 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  and  classes, but where you don't want to fix the type associated with the  of a record.)Generally speaking, where you might have:  foo :: (  record , PeristEntityBackend record ~  backend ,  IsSqlBackend backend ) this can be replaced with:  foo :: (  record, ,  record ~ backend ,   SqlBackend backend ) This works for SqlReadBackend because of the  instance   SqlBackend SqlReadBackend$, without needing to go through the  type family.8Likewise, functions that are currently hardcoded to use  SqlBackend can be generalized: -- before: asdf ::   SqlBackend) m () asdf = pure () -- after: asdf' :: 4 SqlBackend backend => ReaderT backend m () asdf' =  asdf  persistentClass 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. persistentThis function is how we actually construct and tag a backend as having read or write capabilities. It should be used carefully and only when actually constructing a backend. Careless use allows us to accidentally run a write query against a read-only database. persistent%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   persistent5Run a query against a larger backend by plucking out BaseBackend backendThis is a helper for reusing existing queries when expanding the backend type.  persistentRun a query against a compatible backend, by projecting the backendThis is a helper for using queries which run against a specific backend type that your backend is compatible with. persistentSame as , but for a non-null (not Maybe) foreign key. Unsafe unless your database is enforcing that the foreign key is valid. Example usageWith  #schema-persist-store-1schema-1 and  #dataset-persist-store-1 dataset-1, getJustSpj :: MonadIO m => ReaderT SqlBackend m User getJustSpj = getJust spjId spj <- getJust spjId The above query when applied on  #dataset-persist-store-1 dataset-1, will get this record: +----+------+-----+ | id | name | age | +----+------+-----+ | 1 | SPJ | 40 | +----+------+-----+ getJustUnknown :: MonadIO m => ReaderT SqlBackend m User getJustUnknown = getJust unknownIdmrx <- getJustUnknownThis just throws an error. persistentSame as , but returns an  instead of just the record. Example usageWith  #schema-persist-store-1schema-1 and  #dataset-persist-store-1 dataset-1, getJustEntitySpj :: MonadIO m => ReaderT SqlBackend m (Entity User) getJustEntitySpj = getJustEntity spjId spjEnt <- getJustEntitySpj The above query when applied on  #dataset-persist-store-1 dataset-1, will get this entity: +----+------+-----+ | id | name | age | +----+------+-----+ | 1 | SPJ | 40 | +----+------+-----+ persistentCurry this to make a convenience function that loads an associated model. foreign = belongsTo foreignId persistentSame as  , but uses getJust# and therefore is similarly unsafe. persistentLike insert, but returns the complete Entity. Example usageWith  #schema-persist-store-1schema-1 and  #dataset-persist-store-1 dataset-1, insertHaskellEntity :: MonadIO m => ReaderT SqlBackend m (Entity User) insertHaskellEntity = insertEntity $ User "Haskell" 81 !haskellEnt <- insertHaskellEntity The above query when applied on  #dataset-persist-store-1 dataset-1, will produce this: +----+---------+-----+ | id | name | age | +----+---------+-----+ | 1 | SPJ | 40 | +----+---------+-----+ | 2 | Simon | 41 | +----+---------+-----+ | 3 | Haskell | 81 | +----+---------+-----+ persistentLike get, but returns the complete Entity. Example usageWith  #schema-persist-store-1schema-1 and  #dataset-persist-store-1 dataset-1, getSpjEntity :: MonadIO m => ReaderT SqlBackend m (Maybe (Entity User)) getSpjEntity = getEntity spjId mSpjEnt <- getSpjEntity The above query when applied on  #dataset-persist-store-1 dataset-1, will get this entity: +----+------+-----+ | id | name | age | +----+------+-----+ | 1 | SPJ | 40 | +----+------+-----+ persistentLike ( but just returns the record instead of . Example usageWith  #schema-persist-store-1schema-1 and  #dataset-persist-store-1 dataset-1, insertDaveRecord :: MonadIO m => ReaderT SqlBackend m User insertDaveRecord = insertRecord $ User "Dave" 50 dave <- insertDaveRecord The above query when applied on  #dataset-persist-store-1 dataset-1, will produce this: +-----+------+-----+ |id |name |age | +-----+------+-----+ |1 |SPJ |40 | +-----+------+-----+ |2 |Simon |41 | +-----+------+-----+ |3 |Dave |50 | +-----+------+-----+''None  #$?  persistentA  represents a handle or connection to a database. It contains functions and values that allow databases to have more optimized implementations, as well as references that benefit performance and sharing.Instead of using the  constructor directly, use the  function.A 5 is *not* thread-safe. You should not assume that a  can be shared among threads and run concurrent queries. This *will* result in problems. Instead, you should create a Pool  , known as a ConnectionPool7, and pass that around in multi-threaded applications.To run actions in the  persistent library, you should use the  runSqlConn function. If you're using a multithreaded application, use the  runSqlPool function. persistentThis function should prepare a  in the target database, which should allow for efficient query reuse. persistentThis function generates the SQL and values necessary for performing an insert against the database. persistentSQL for inserting many rows and returning their primary keys, for backends that support this functionality. If -, rows will be inserted one-at-a-time using . persistentSome databases support performing UPSERT _and_ RETURN entity in a single call.This field when set will be used to generate the UPSERT+RETURN sql given * an entity definition * updates to be run on unique key(s) collision When left as , we find the unique key from entity def before * trying to fetch an entity by said key * perform an update when result found, else issue an insert * return new entity from db persistentSome databases support performing bulk UPSERT, specifically "insert or replace many records" in a single call.This field when set, given * an entity definition * number of records to be inserted should produce a PUT MANY sql with placeholders for records When left as , we default to using defaultPutMany. persistent(A reference to the cache of statements. s are keyed by the  queries that generated them. persistent Close the underlying connection. persistent>This function returns the migrations required to include the  parameter in the [] database. This might include creating a new table if the entity is not present, or altering an existing table if it is. persistent>A function to begin a transaction for the underlying database. persistent>A function to commit a transaction to the underlying database. persistentA function to roll back a transaction on the underlying database.  persistentA function to extract and escape the name of the column corresponding to the provided field.  persistentA function to extract and escape the name of the table corresponding to the provided entity. PostgreSQL uses this to support schemas.  persistentA function to escape raw DB identifiers. MySQL uses backticks, while PostgreSQL uses quotes, and so on. persistent#A tag displaying what database the  is for. Can be used to differentiate features in downstream libraries for different database backends. persistentAttach a 'LIMIT/OFFSET' clause to a SQL query. Note that LIMIT/OFFSET is problematic for performance, and indexed range queries are the superior way to offer pagination. persistentA log function for the  to use. persistentSome databases (probably only Sqlite) have a limit on how many question-mark parameters may be used in a statement  persistentSome databases support performing bulk an atomic+bulk INSERT where constraint conflicting entities can replace existing entities.This field when set, given * an entity definition * number of records to be inserted should produce a INSERT sql with placeholders for primary+record fields When left as , we default to using defaultRepsertMany.  persistent'A function for creating a value of the  type. You should prefer to use this instead of the constructor for , because default values for this will be provided for new fields on the record when new functionality is added.None ?   persistent*This function can be used directly with a  to escape a . let conn :: SqlBackend getEscapedFieldName (FieldNameDB "asdf") conn #Alternatively, you can use it in a   context, like  SqlPersistT: query :: SqlPersistM Text query = do field <- getEscapedFieldName (FieldNameDB "asdf") pure field   persistent*This function can be used directly with a  to escape a raw . let conn :: SqlBackend getEscapedRawName (FieldNameDB "asdf") conn #Alternatively, you can use it in a   context, like  SqlPersistT: query :: SqlPersistM Text query = do field <- getEscapedRawName (FieldNameDB "asdf") pure field   persistent,Return the function for escaping a raw name.  persistent&Decorate the given SQL query with the (LIMIT, OFFSET) specified.  persistentRetrieve the function for generating an upsert statement, if the backend supports it.  persistentSet the maximum parameters that may be issued in a given SQL query. This should be used only if the database backend have this limitation.  persistentSet the  field on the . This should only be set by the database backend library. If this is not set, a slow default will be used.  persistentSet the  field on the . This should only be used by the database backend library to provide an efficient implementation of a bulk insert function. If this is not set, a slow default will be used.  persistentSet the  field on the . This should only be used by the database backend library to provide an efficient implementation of a bulk insert function. If this is not set, a slow default will be used.  persistent%Set the 'connPutManySql field on the . This should only be used by the database backend library to provide an efficient implementation of a bulk insert function. If this is not set, a slow default will be used. persistentThe (LIMIT, OFFSET) to put on the query. persistent?The SQL query that the LIMIT/OFFSET clause will be attached to.None  /?M  persistentThis 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  TypeError0 instances for records that have 0 unique keys.  persistentThis is an error message. It is used when an entity has multiple unique keys, and the function expects a single unique key.  persistentThis is an error message. It is used when writing instances of ' for an entity that has no unique keys.  persistent"This class is used to ensure that / is only called on records that have a single  key. The quasiquoter automatically generates working instances for appropriate records, and generates  TypeError< instances for records that have 0 or multiple unique keys. persistentSome functions in this module (, , and ) first query the unique indexes to check for conflicts. You could instead optimistically attempt to perform the operation (e.g.  instead of  ). 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. persistentDelete a specific record by unique key. Does nothing if no record matches. Example usageWith  #schema-persist-unique-1schema-1 and  #dataset-persist-unique-1 dataset-1, deleteBySpjName :: MonadIO m => ReaderT SqlBackend m () deleteBySpjName = deleteBy UniqueUserName "SPJ" The above query when applied on  #dataset-persist-unique-1 dataset-1, will produce this: +-----+------+-----+ |id |name |age | +-----+------+-----+ |2 |Simon |41 | +-----+------+-----+ persistentLike , but returns  when the record couldn't be inserted because of a uniqueness constraint. Example usageWith  #schema-persist-unique-1schema-1 and  #dataset-persist-unique-1 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-persist-unique-1 dataset-11, while SPJ wasn't because SPJ already exists in  #dataset-persist-unique-1 dataset-1. persistent2Update 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 usageFirst, we try to explain  using  #schema-persist-unique-1schema-1 and  #dataset-persist-unique-1 dataset-1. upsertSpj :: MonadIO m => [Update User] -> ReaderT SqlBackend m (Maybe (Entity User)) upsertSpj updates = upsert (User "SPJ" 999) upadtes %mSpjEnt <- upsertSpj [UserAge +=. 15] The above query when applied on  #dataset-persist-unique-1 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-persist-unique-1 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-persist-unique-2schema-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 " to select the unique key we want. persistent8Update 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 usageWe try to explain  using  #schema-persist-unique-2schema-2 and  #dataset-persist-unique-1 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-persist-unique-1 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-persist-unique-1 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  ReaderT SqlBackend m (Maybe (Entity User)) getBySpjName = getBy $ UniqueUserName "SPJ" mSpjEnt <- getBySpjName The above query when applied on  #dataset-persist-unique-1 dataset-1, will get this entity: +----+------+-----+ | id | name | age | +----+------+-----+ | 1 | SPJ | 40 | +----+------+-----+  persistentGiven a proxy for a  record, this returns the sole  for that entity.  persistent4Given a proxy for a record that has an instance of , this returns a  list of the s for that entity. persistentInsert a value, checking for conflicts with any unique constraints. If a duplicate exists in the database, it is returned as *. Otherwise, the new 'Key is returned as . Example usageWith  #schema-persist-unique-2schema-2 and  #dataset-persist-unique-1 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" 100First three lines return  because there're duplicates in given record's uniqueness constraints. While the last line returns a new key as . persistentLike , but returns  when the record couldn't be inserted because of a uniqueness constraint. Example usageWe use  #schema-persist-unique-2schema-2 and  #dataset-persist-unique-1 dataset-1 here. insertUniqueSpjEntity :: MonadIO m => ReaderT SqlBackend m (Maybe (Entity User)) insertUniqueSpjEntity = insertUniqueEntity $ User "SPJ" 50  mSpjEnt <- insertUniqueSpjEntityThe above query results  as SPJ already exists. insertUniqueAlexaEntity :: MonadIO m => ReaderT SqlBackend m (Maybe (Entity User)) insertUniqueAlexaEntity = insertUniqueEntity $ User "Alexa" 3 "mAlexaEnt <- insertUniqueSpjEntityBecause there's no such unique keywords of the given record, the above query when applied on  #dataset-persist-unique-1 dataset-1, will produce this: +----+-------+-----+ | id | name | age | +----+-------+-----+ | 1 | SPJ | 40 | +----+-------+-----+ | 2 | Simon | 41 | +----+-------+-----+ | 3 | Alexa | 3 | +----+-------+-----+ persistent*Return the single unique key for a record. Example usageWe use shcema-1 and  #dataset-persist-unique-1 dataset-1 here. onlySimonConst :: MonadIO m => ReaderT SqlBackend m (Unique User) onlySimonConst = onlyUnique $ User "Simon" 999 mSimonConst <- onlySimonConst mSimonConst4 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. persistentA modification of , which takes the  itself instead of a # record. Returns a record matching one of the unique keys. This function makes the most sense on entities with a single  constructor. Example usageWith  #schema-persist-unique-1schema-1 and  #dataset-persist-unique-1 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-persist-unique-1 dataset-1, will get this record: +----+------+-----+ | id | name | age | +----+------+-----+ | 1 | SPJ | 40 | +----+------+-----+  persistentRetrieve a record from the database using the given unique keys. It will attempt to find a matching record for each : in the list, and returns the first one that has a match.Returns  if you provide an empty list ('[]') or if no value matches in the database. persistentAttempt 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  if the replacement was made. If uniqueness is violated, return a  with the  violation persistentCheck whether there are any conflicts for unique keys with this entity and existing entities in the database.Returns  if the entity would be unique, and could thus safely be inserted. on a conflict returns the conflicting key Example usageWe use  #schema-persist-unique-1schema-1 and  #dataset-persist-unique-1 dataset-1 here.This would be : *mAlanConst <- checkUnique $ User "Alan" 70While this would be  because SPJ already exists: (mSpjConst <- checkUnique $ User "SPJ" 60  persistentCheck whether there are any conflicts for unique keys with this entity and existing entities in the database.Returns  if the entity would stay unique, and could thus safely be updated. on a conflict returns the conflicting keyThis is similar to , except it's useful for updating - when the particular entity already exists, it would normally conflict with itself. This variant ignores those conflicts Example usageWe use  #schema-persist-unique-1schema-1 and  #dataset-persist-unique-1 dataset-1 here.This would be : *mAlanConst <- checkUnique $ User "Alan" 70While this would be  because SPJ already exists: (mSpjConst <- checkUnique $ User "SPJ" 60 persistentThe slow but generic  implementation for any ,. * Lookup corresponding entities (if any) (. * If the record exists, update using (. * If it does not exist, insert using . @since 2.11 persistentThe slow but generic  implementation for any . * Lookup corresponding entities (if any) for each record using & * For pre-existing records, issue a  for each old key and new record * For new records, issue a bulk  persistent This function returns a list of A that correspond to the 7 keys on that record. This is useful for comparing two record+s for equality only on the basis of their  keys. persistentnew record to insert persistent/updates to perform if the record already exists persistent.the record in the database after the operation persistent uniqueness constraint to find by persistentnew record to insert persistent/updates to perform if the record already exists persistent.the record in the database after the operation persistent4A list of the records you want to insert or replace. persistent uniqueness constraint to find by persistentnew record to insert persistent/updates to perform if the record already exists persistent.the record in the database after the operationNone  ?RE  persistent0Backends supporting conditional write operations persistentUpdate individual fields on any record matching the given criterion. persistent0Delete all records matching the given criterion. persistent0Backends supporting conditional read operations. persistentGet all records matching the given criterion in the specified order. Returns also the identifiers. persistent,Get just the first record for the criterion. persistentGet the .s of all records matching the given criterion. persistent;The total number of records fulfilling the given criterion.  persistentCheck if there is at least one record fulfilling the given criterion. persistentGet all records matching the given criterion in the specified order. Returns also the identifiers. persistentGet the .s of all records matching the given criterion. persistentCall ! but return the result as a list. persistentCall ! but return the result as a list.  None  ?S persistentFor combinations of backends and entities that support cascade-deletion. @Cascade-deletion@ means that entries that depend on other entries to be deleted will be deleted as well. persistent3Perform cascade-deletion of single database entry. persistent5Cascade-deletion of entries satisfying given filters.None  -?V persistentA 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. persistentA 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. persistentA 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.None #$-?\  persistent$A backend which is a wrapper around  SqlBackend. persistentLike  SqlPersistT but compatible with any SQL backend which can handle read and write queries. persistentLike  SqlPersistT but compatible with any SQL backend which can handle read queries. persistentA constraint synonym which witnesses that a backend is SQL and can run read and write queries. persistentA constraint synonym which witnesses that a backend is SQL and can run read queries. persistent5An SQL backend which can handle read or write queries%The constructor was exposed in 2.10.0 persistent1An SQL backend which can only handle read queries&The constructor was exposed in 2.10.0. persistentUseful for running a write query against an untagged backend with unknown capabilities. persistentUseful for running a read query against a backend with read and write capabilities. persistentUseful for running a read query against a backend with unknown capabilities.:bcdefg:bcdefg#None ?d   persistentAn exception indicating that Persistent refused to run some unsafe migrations. Contains a list of pairs where the Bool tracks whether the migration was unsafe (True means unsafe), and the Sql is the sql statement for the migration. persistentA single column (see rawSql). Any  PersistField may be used here, including A% (which does not do any processing).  persistent8Values to configure a pool of database connections. See  Data.Pool for details. persistent.How many stripes to divide the pool into. See  Data.Pool for details. Default: 1. persistentHow long connections can remain idle before being disposed of, in seconds. Default: 600 persistentHow many connections should be held in the connection pool. Default: 10 persistentA + is a four level monad stack consisting of: []0 representing a log of errors in the migrations.  representing a list of migrations to run, along with whether or not they are safe.  , aka the % transformer for database interop. for arbitrary IO.  persistent:This value specifies how a field references another table.  persistentThe table name that the  persistent'The name of the foreign key constraint.  persistentWhether or not updates/deletions to the referenced table cascade to this table.  persistentInitializes a ConnectionPoolConfig with default values. See the documentation of  for each field's default value. persistentThis  instance renders an error message suitable for printing to the console. This is a little dodgy, but since GHC uses Show instances when displaying uncaught exceptions, we have little choice.$None  #$?i  persistent8Record of functions to override the default behavior in /. It is recommended you initialize this with  and override the default values, so that as new fields are added, your code still compiles.For added safety, use the getBackendSpecific* and setBackendSpecific* functions, as a breaking change to the record field labels won't be reflected in a major version bump of the library.  persistentIf the override is defined, then this returns a function that accepts an entity name and field name and provides the  ! for the foreign key constraint.An abstract accessor for the   persistentSet the backend's foreign key generation function to this value.  persistentCreates an empty . (i.e. use the default behavior; no overrides) persistent0Create the list of columns for the given entity.None  ? persistentAssign a field a value. Example usage updateAge :: MonadIO m => ReaderT SqlBackend m () updateAge = updateWhere [UserName ==. "SPJ" ] [UserAge =. 45]  Similar to  which is shown in the above example you can use other functions present in the module Database.Persist.Class#. Note that the first parameter of  is [ val] and second parameter is [* val]. By comparing this with the type of  and 4, you can see that they match up in the above usage. The above query when applied on  #dataset dataset-1, will produce this: +-----+-----+--------+ |id |name |age | +-----+-----+--------+ |1 |SPJ |40 -> 45| +-----+-----+--------+ |2 |Simon|41 | +-----+-----+--------+ persistentAssign a field by addition (+=). Example usage addAge :: MonadIO m => ReaderT SqlBackend m () addAge = updateWhere [UserName ==. "SPJ" ] [UserAge +=. 1]  The above query when applied on  #dataset dataset-1, will produce this: +-----+-----+---------+ |id |name |age | +-----+-----+---------+ |1 |SPJ |40 -> 41 | +-----+-----+---------+ |2 |Simon|41 | +-----+-----+---------+ persistentAssign a field by subtraction (-=). Example usage subtractAge :: MonadIO m => ReaderT SqlBackend m () subtractAge = updateWhere [UserName ==. "SPJ" ] [UserAge -=. 1]  The above query when applied on  #dataset dataset-1, will produce this: +-----+-----+---------+ |id |name |age | +-----+-----+---------+ |1 |SPJ |40 -> 39 | +-----+-----+---------+ |2 |Simon|41 | +-----+-----+---------+ persistent"Assign a field by multiplication (*=). Example usage multiplyAge :: MonadIO m => ReaderT SqlBackend m () multiplyAge = updateWhere [UserName ==. "SPJ" ] [UserAge *=. 2]  The above query when applied on  #dataset dataset-1, will produce this: +-----+-----+--------+ |id |name |age | +-----+-----+--------+ |1 |SPJ |40 -> 80| +-----+-----+--------+ |2 |Simon|41 | +-----+-----+--------+ persistentAssign a field by division (/=). Example usage divideAge :: MonadIO m => ReaderT SqlBackend m () divideAge = updateWhere [UserName ==. "SPJ" ] [UserAge /=. 2]  The above query when applied on  #dataset dataset-1, will produce this: +-----+-----+---------+ |id |name |age | +-----+-----+---------+ |1 |SPJ |40 -> 20 | +-----+-----+---------+ |2 |Simon|41 | +-----+-----+---------+ persistentCheck for equality. Example usage selectSPJ :: MonadIO m => ReaderT SqlBackend m [Entity User] selectSPJ = selectList [UserName ==. "SPJ" ] []  The above query when applied on  #dataset dataset-1, will produce this: +-----+-----+-----+ |id |name |age | +-----+-----+-----+ |1 |SPJ |40 | +-----+-----+-----+ persistentNon-equality check. Example usage selectSimon :: MonadIO m => ReaderT SqlBackend m [Entity User] selectSimon = selectList [UserName !=. "SPJ" ] []  The above query when applied on  #dataset dataset-1, will produce this: +-----+-----+-----+ |id |name |age | +-----+-----+-----+ |2 |Simon|41 | +-----+-----+-----+ persistentLess-than check. Example usage selectLessAge :: MonadIO m => ReaderT SqlBackend m [Entity User] selectLessAge = selectList [UserAge <. 41 ] []  The above query when applied on  #dataset dataset-1, will produce this: +-----+-----+-----+ |id |name |age | +-----+-----+-----+ |1 |SPJ |40 | +-----+-----+-----+ persistentLess-than or equal check. Example usage selectLessEqualAge :: MonadIO m => ReaderT SqlBackend m [Entity User] selectLessEqualAge = selectList [UserAge <=. 40 ] []  The above query when applied on  #dataset dataset-1, will produce this: +-----+-----+-----+ |id |name |age | +-----+-----+-----+ |1 |SPJ |40 | +-----+-----+-----+ persistentGreater-than check. Example usage selectGreaterAge :: MonadIO m => ReaderT SqlBackend m [Entity User] selectGreaterAge = selectList [UserAge >. 40 ] []  The above query when applied on  #dataset dataset-1, will produce this: +-----+-----+-----+ |id |name |age | +-----+-----+-----+ |2 |Simon|41 | +-----+-----+-----+ persistentGreater-than or equal check. Example usage selectGreaterEqualAge :: MonadIO m => ReaderT SqlBackend m [Entity User] selectGreaterEqualAge = selectList [UserAge >=. 41 ] []  The above query when applied on  #dataset dataset-1, will produce this: +-----+-----+-----+ |id |name |age | +-----+-----+-----+ |2 |Simon|41 | +-----+-----+-----+ persistent Check if value is in given list. Example usage selectUsers :: MonadIO m => ReaderT SqlBackend m [Entity User] selectUsers = selectList [UserAge <-. [40, 41]] []  The above query when applied on  #dataset dataset-1, will produce this: +-----+-----+-----+ |id |name |age | +-----+-----+-----+ |1 |SPJ |40 | +-----+-----+-----+ |2 |Simon|41 | +-----+-----+-----+ selectSPJ :: MonadIO m => ReaderT SqlBackend m [Entity User] selectSPJ = selectList [UserAge <-. [40]] []  The above query when applied on  #dataset dataset-1, will produce this: +-----+-----+-----+ |id |name |age | +-----+-----+-----+ |1 |SPJ |40 | +-----+-----+-----+ persistent$Check if value is not in given list. Example usage selectSimon :: MonadIO m => ReaderT SqlBackend m [Entity User] selectSimon = selectList [UserAge /<-. [40]] []  The above query when applied on  #dataset dataset-1, will produce this: +-----+-----+-----+ |id |name |age | +-----+-----+-----+ |2 |Simon|41 | +-----+-----+-----+ persistent,The OR of two lists of filters. For example: selectList ([ PersonAge >. 25 , PersonAge <. 30 ] ||. [ PersonIncome >. 15000 , PersonIncome <. 25000 ]) []>will filter records where a person's age is between 25 and 30 or1 a person's income is between (15000 and 25000).If you are looking for an (&&.) operator to do (A AND B AND (C OR D)) you can use the (++)! operator instead as there is no (&&.). For example: selectList ([ PersonAge >. 25 , PersonAge <. 30 ] ++ ([PersonCategory ==. 1] ||. [PersonCategory ==. 5])) []>will filter records where a person's age is between 25 and 30 and' (person's category is either 1 or 5). persistentConvert list of As into textual representation of JSON object. This is a type-constrained synonym for . persistentConvert map (list of tuples) into textual representation of JSON object. This is a type-constrained synonym for . persistent+A more general way to convert instances of  type class to strict text . persistentFIXME What's this exactly? =@>?APONMLKJIHGFEDCBSQRTmnywvtrqusxpoz~}|{33333444444443None  ?x  persistentReturns  if the entity has a natural key defined with the Primary keyword.A natural key is a key that is inherent to the record, and is part of the actual Haskell record. The opposite of a natural key is a "surrogate key", which is not part of the normal domain object. Automatically generated ID columns are the most common surrogate ID, while an email address is a common natural key. User email String name String Primary email Person Id UUID name String Follower name String  Given these entity definitions, User would return , because the Primary keyword sets the email column to be the primary key. The generated Haskell type would look like this: data User = User { userEmail :: String , userName :: String } Person would be false. While the Id syntax allows you to define a custom ID type for an entity, the Id column is a surrogate key.The same is true for Follower. The automatically generated autoincremented integer primary key is a surrogate key./There's nothing preventing you from defining a Primary definition that refers to a surrogate key. This is totally fine.  persistentReturns  if the provided entity has a custom composite primary key. Composite keys have multiple fields in them. User email String name String Primary userId Profile personId PersonId email String Primary personId email Person Id UUID name String Follower name String %Given these entity definitions, only Profile would return , because it is the only entity with multiple columns in the primary key. User" has a single column natural key. Person8 has a custom single column surrogate key defined with Id. And Follower, has a default single column surrogate key. persistent Gets the m for an .  persistent Make a list A suitable for database inserts. Pairs nicely with the function .#Does not include generated columns.  persistent*Returns a list of escaped field names and "?" placeholder values for performing inserts. This does not include generated columns.#Does not include generated columns. persistentAn escape function%None />?g? persistentTells Persistent what database column type should be used to store a Haskell type.ExamplesSimple Boolean Alternative 7data Switch = On | Off deriving (Show, Eq) instance  Switch where  s = case s of On -> G True Off -> G False  (G b) = if b then  On else  Off  x = Left $ "File.hs: When trying to deserialize a Switch: expected PersistBool, received: " <> T.pack (show x) instance  Switch where  _ =  Non-Standard Database TypesIf your database supports non-standard types, such as Postgres' uuid, you can use  to use them: ,import qualified Data.UUID as UUID instance  UUID where  = PersistLiteralEncoded . toASCIIBytes  (PersistLiteralEncoded/ uuid) = case fromASCIIBytes uuid of  ->  $ "Model/CustomTypes.hs: Failed to deserialize a UUID; received: " <> T.pack (show uuid)  uuid' ->  uuid'  x = Left $ "File.hs: When trying to deserialize a UUID: expected PersistLiteralEncoded, received: "-- > <> T.pack (show x) instance  UUID where  _ =  "uuid" User Created Database TypesSimilarly, some databases support creating custom types, e.g. Postgres'  https://www.postgresql.org/docs/current/static/sql-createdomain.htmlDOMAIN and  https://www.postgresql.org/docs/current/static/datatype-enum.htmlENUM features. You can use  to specify a custom type: >CREATE DOMAIN ssn AS text CHECK ( value ~ '^[0-9]{9}$');  instance PersistFieldSQL SSN where  _ =  "ssn"  CREATE TYPE rainbow_color AS ENUM ('red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet');  instance PersistFieldSQL RainbowColor where  _ =  "rainbow_color"   persistentThis newtype wrapper is useful when selecting an entity out of the database and you want to provide a prefix to the table being selected.Consider this raw SQL query: SELECT ?? FROM my_long_table_name AS mltn INNER JOIN other_table AS ot ON mltn.some_col = ot.other_col WHERE ...We don't want to refer to my_long_table_name every time, so we create an alias. If we want to select it, we have to tell the raw SQL quasi-quoter that we expect the entity to be prefixed with some other name.3We can give the above query a type with this, like:  getStuff ::  [8 "mltn" MyLongTableName] getStuff = rawSql queryText [] The  bit is a boilerplate newtype wrapper, so you can remove it with  , like this:  getStuff ::  [ MyLongTableName] getStuff =  @"mltn"  rawSql queryText [] The 1 symbol is a "type application" and requires the &TypeApplications@ language extension. persistent1Class for data types that may be retrived from a rawSql query. persistentNumber of columns that this data type needs and the list of substitutions for SELECT placeholders ??. persistent>A string telling the user why the column count is what it is. persistent1Transform a row of the result into the data type.  persistent'A helper function to tell GHC what the  prefix should be. This allows you to use a type application to specify the prefix, instead of specifying the etype on the result.*As an example, here's code that uses this:  myQuery ::  [( Person] myQuery = fmap (unPrefix @"p")  $ rawSql query [] where query = "SELECT ?? FROM person AS p"   persistent  persistent  persistent  persistent  persistent  persistent  persistent  persistent  persistent  persistent  persistent  persistent  persistent  persistent  persistent  persistent  persistent  persistent  persistent  persistent  persistent  persistent  persistent  persistent  persistent  persistent  persistent  persistent  persistent  persistent  persistent  persistent  persistent  persistent  persistent  persistent  persistent  persistent  persistent  persistent  persistent  persistent  persistent  persistent  persistent  persistent  persistent  persistent  persistent  persistent  persistent  persistent  persistent  persistent persistent  persistentThis type uses the  version, which will exhibit overflow and underflow behavior. Additionally, it permits negative values in the database, which isn't ideal. &None ?@ persistentExecute a raw SQL statement persistentExecute a raw SQL statement and return the number of rows it has modified. persistentExecute a raw SQL statement and return its results as a list. If you do not expect a return value, use of  is recommended.If you're using s$ (which is quite likely), then you must; use entity selection placeholders (double question mark, ?? ). These ?? placeholders are then replaced for the names of the columns that we need for your entities. You'll receive an error if you don't use the placeholders. Please see the s documentation for more details.0You may put value placeholders (question marks, ?) in your SQL query. These placeholders are then replaced by the values you pass on the second parameter, already correctly escaped. You may want to use 2 to help you constructing the placeholder values.Since you're giving a raw SQL statement, you don't get any guarantees regarding safety. If  is not able to parse the results of your query back, then an exception is raised. However, most common problems are mitigated by using the entity selection placeholder ??>, and you shouldn't see any error at all if you're not using .Some example of  based on this schema: share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase| Person name String age Int Maybe deriving Show BlogPost title String authorId PersonId deriving Show |] #Examples based on the above schema: getPerson :: MonadIO m => ReaderT SqlBackend m [Entity Person] getPerson = rawSql "select ?? from person where name=?" [PersistText "john"] getAge :: MonadIO m => ReaderT SqlBackend m [Single Int] getAge = rawSql "select person.age from person where name=?" [PersistText "john"] getAgeName :: MonadIO m => ReaderT SqlBackend m [(Single Int, Single Text)] getAgeName = rawSql "select person.age, person.name from person where name=?" [PersistText "john"] getPersonBlog :: MonadIO m => ReaderT SqlBackend m [(Entity Person, Entity BlogPost)] getPersonBlog = rawSql "select ??,?? from person,blog_post where person.id = blog_post.author_id" [] Minimal working program for PostgreSQL backend based on the above concepts:  {-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} import Control.Monad.IO.Class (liftIO) import Control.Monad.Logger (runStderrLoggingT) import Database.Persist import Control.Monad.Reader import Data.Text import Database.Persist.Sql import Database.Persist.Postgresql import Database.Persist.TH share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase| Person name String age Int Maybe deriving Show |] conn = "host=localhost dbname=new_db user=postgres password=postgres port=5432" getPerson :: MonadIO m => ReaderT SqlBackend m [Entity Person] getPerson = rawSql "select ?? from person where name=?" [PersistText "sibi"] liftSqlPersistMPool y x = liftIO (runSqlPersistMPool y x) main :: IO () main = runStderrLoggingT $ withPostgresqlPool conn 10 $ liftSqlPersistMPool $ do runMigration migrateAll xs <- getPerson liftIO (print xs)  persistent*SQL statement, possibly with placeholders. persistent Values to fill the placeholders. persistent*SQL statement, possibly with placeholders. persistent Values to fill the placeholders. persistent*SQL statement, possibly with placeholders. persistent Values to fill the placeholders.'None  ?  persistentGet a connection from the pool, run the given action, and then return the connection to the pool.This function performs the given action in a transaction. If an exception occurs during the action, then the transaction is rolled back.Note: This function previously timed out after 2 seconds, but this behavior was buggy and caused more problems than it solved. Since version 2.1.2, it performs no timeout checks.  persistentLike -, but supports specifying an isolation level.  persistentLike , but does not surround the action in a transaction. This action might leave your database in a weird state.  persistentThis function is how  and  are defined. In addition to the action to be performed and the  of conections to use, we give you the opportunity to provide three actions - initialize, afterwards, and onException.  persistentStarts a new transaction on the connection. When the acquired connection is released the transaction is committed and the connection returned to the pool.Upon an exception the transaction is rolled back and the connection destroyed.9This is equivalent to 'runSqlConn but does not incur the < constraint, meaning it can be used within, for example, a Conduit pipeline.  persistentLike 3, but lets you specify an explicit isolation level.  persistentLike -, but supports specifying an isolation level.  persistentCreates a pool of connections to a SQL database which can be used by the Pool backend -> m a function. After the function completes, the connections are destroyed.  persistent0Creates a pool of connections to a SQL database. persistentCreate a connection and run sql queries within it. This function automatically closes the connection on it's completion. Example usage  {-# LANGUAGE GADTs #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeFamilies#-} {-# LANGUAGE TemplateHaskell#-} {-# LANGUAGE QuasiQuotes#-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} import Control.Monad.IO.Class (liftIO) import Control.Monad.Logger import Conduit import Database.Persist import Database.Sqlite import Database.Persist.Sqlite import Database.Persist.TH share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase| Person name String age Int Maybe deriving Show |] openConnection :: LogFunc -> IO SqlBackend openConnection logfn = do conn <- open "/home/sibi/test.db" wrapConnection conn logfn main :: IO () main = do runNoLoggingT $ runResourceT $ withSqlConn openConnection (\backend -> flip runSqlConn backend $ do runMigration migrateAll insert_ $ Person "John doe" $ Just 35 insert_ $ Person "Divya" $ Just 36 (pers :: [Entity Person]) <- selectList [] [] liftIO $ print pers return () )%On executing it, you get this output: Migrating: CREATE TABLE "person"("id" INTEGER PRIMARY KEY,"name" VARCHAR NOT NULL,"age" INTEGER NULL) [Entity {entityKey = PersonKey {unPersonKey = SqlBackendKey {unSqlBackendKey = 1}}, entityVal = Person {personName = "John doe", personAge = Just 35}},Entity {entityKey = PersonKey {unPersonKey = SqlBackendKey {unSqlBackendKey = 2}}, entityVal = Person {personName = "Hema", personAge = Just 36}}] persistent;Run this action immediately before the action is performed. persistent:Run this action immediately after the action is completed. persistentThis action is performed when an exception is received. The exception is provided as a convenience - it is rethrown once this cleanup function is complete. persistentcreate a new connection persistentconnection count persistent#Function to create a new connection persistent#Function to create a new connection(None  8useful for a backend to implement tableName by adding escaping persistentget the SQL string for the field that an EntityField represents Useful for raw SQL queriesYour backend may provide a more convenient fieldName function which does not operate in a Monad persistent>useful for a backend to implement fieldName by adding escaping)None  ?*None  ?  persistent7Used when determining how to prefix a column name in a WHERE clause.  persistentPrefix the column with the table name. This is useful if the column name might be ambiguous.  persistent Prefix the column name with the EXCLUDED? keyword. This is used with the Postgresql backend when doing ON CONFLICT DO UPDATE% clauses - see the documentation on  upsertWhere and upsertManyWhere. persistentSame as *, but returns the number of rows affected. persistentSame as *, but returns the number of rows affected.  persistent Render a [ record] into a 0 value suitable for inclusion into a SQL query.  persistent Render a [ record] into a  value suitable for inclusion into a SQL query, as well as the [A] to properly fill in the ? place holders. persistentGenerates sql for limit and offset for postgres, sqlite and mysql. persistent*include table name or PostgresSQL EXCLUDED persistent include WHERE persistentinclude table name or EXCLUDED persistentinclude table name or EXCLUDED +None ? persistentGiven a , this parses it and returns either a list of errors associated with the migration or a list of migrations to do. persistentLike ,, but instead of returning the value in an  value, it calls  on the error values. persistentPrints a migration. persistent Convert a  to a list of  values corresponding to their  statements. persistentReturn all of the 4 values associated with the given migration. Calls + if there's a parse error on any migration. persistentRuns a migration. If the migration fails to parse or if any of the migrations are unsafe, then this throws a .  persistentSame as , but does not report the individual migrations on stderr. Instead it returns a list of the executed SQL commands.+This is a safer/more robust alternative to , but may be less silent for some persistent implementations, most notably persistent-postgresql persistentSame as , but returns a list of the SQL commands executed instead of printing them to stderr.2This function silences the migration by remapping . As a result, it is not thread-safe and can clobber output from other parts of the program. This implementation method was chosen to also silence postgresql migration output on stderr, but is not recommended! persistentLike , but this will perform the unsafe database migrations instead of erroring out.  persistentSame as , but returns a list of the SQL commands executed instead of printing them to stderr. persistent1Given a list of old entity definitions and a new  in val, this creates a 9 to update the old list of definitions with the new one.  persistentReport a single error in a .  persistentReport multiple errors in a .  persistent&Add a migration to the migration plan.  persistentAdd a  (aka a [(, )]) to the migration plan.  persistentRun an action against the database during a migration. Can be useful for eg creating Postgres extensions: runSqlCommand $ 2 "CREATE EXTENSION IF NOT EXISTS "uuid-ossp";" []  persistentIs the migration safe to run? (eg a non-destructive and idempotent update on the schema) persistentA 7 value representing the command to run on the database.None ./?$   persistent;A specification for how the implied ID columns are created. By default,  persistent- will give each table a default column named id (customizable by PersistSettings;), and the column type will be whatever you'd expect from  BackendKey yourBackendType . For The  SqlBackend9 type, this is an auto incrementing integer primary key.You might want to give a different example. A common use case in postgresql is to use the UUID type, and automatically generate them using a SQL function.'Previously, you'd need to add a custom Id annotation for each model. User Id UUID default="uuid_generate_v1mc()" name Text Dog Id UUID default="uuid_generate_v1mc()" name Text user UserIdNow, you can simply create an ' that corresponds to this declaration. newtype UUID = UUID  ByteString instance  UUID where toPersistValue (UUID bs) = P > bs fromPersistValue pv = case pv of PersistLiteral_ Escaped bs -> Right (UUID bs) _ -> Left "nope" instance  UUID where  _ =  UUID With this instance at the ready, we can now create our implicit definition: uuidDef :: ImplicitIdDef uuidDef = mkImplicitIdDef @UUID "uuid_generate_v1mc()" And we can use setImplicitIdDef to use this with the MkPersistSettings for our block. mkPersist (setImplicitIdDef uuidDef sqlSettings) [persistLowerCase| ... |] TODO: either explain interaction with mkMigrate or fix it. see issue #1249 for more details.  persistentThe field type. Accepts the * if you want to refer to it. By default, Id, is appended to the end of the Haskell name.  persistentThe - for the default column. By default, this is = to correspond with an autoincrementing integer primary key.  persistent(The Bool argument is whether or not the MkPersistBackend type has the  mpsGeneric field set.The  is the  mpsBackend value.The default uses  BackendKey  SqlBackend (or a generic equivalent).  persistentThe default expression for the field. Note that setting this to  is unsafe. see  2https://github.com/yesodweb/persistent/issues/1247 for more information.&With some cases - like the Postgresql SERIAL8 type - this is safe, since there's an implied default.  persistentSpecify the maximum length for a key column. This is necessary for VARCHAR columns, like UUID in MySQL. MySQL will throw a runtime error if a text or binary column is used in an index without a length specification.  persistent Create an  based on the  and  constraints in scope.This function uses the TypeApplications syntax. Let's look at an example that works with Postgres UUIDs. newtype UUID = UUID Text deriving newtype PersistField instance PersistFieldSql UUID where sqlType _ = SqlOther "UUID" idDef :: ImplicitIdDef idDef = mkImplicitIdDefTypeable @UUID "uuid_generate_v1mc()"This  will generate default UUID columns, and the database will call the uuid_generate_v1mc()> function to generate the value for new rows being inserted. If the type t is  or  then a max_len2 attribute of 200 is set. To customize this, use .  persistentSet the maximum length of the implied ID column. This is required for any type where the associated  is a TEXT or VARCHAR sort of thing.  persistentThis function converts a  type into a  persistent* representation of the type of a field - FieldTyp.  persistent$Remove the default attribute of the  column. This will require you to provide an ID for the model with every insert, using  insertKey instead of insert, unless the type has some means of getting around that in the migrations.As an example, the Postgresql SERIAL type expands to an autoincrementing integer. Postgres will implicitly create the relevant series and set the default to be NEXTVAL( series_name);. A default is therefore unnecessary to use for this type.However, for a UUID, postgres *does not* have an implicit default. You must either specify a default UUID generation function, or insert them yourself (again, using  insertKey).This function will be deprecated in the future when omiting the default implicit ID column is more fully supported. persistentThe default expression to use for columns. Should be valid SQL in the language you're using.  None  ?+  persistentThis is the default variant. Setting the implicit ID definition to this value should not have any change at all on how entities are defined by default.,None 2<=>?   persistent=A newtype wrapper for compatible backends, mainly useful for  DerivingVia.#When writing a new backend that is  with an existing backend, instances for the new backend can be naturally defined in terms of the instances for the existing backend.*For example, if you decide to augment the  SqlBackend with some additional features: data BetterSqlBackend = BetterSqlBackend { sqlBackend :: SqlBackend, ... } instance BackendCompatible SqlBackend BetterSqlBackend where projectBackend = sqlBackend Then you can use  DerivingVia% to automatically get instances like: deriving via (Compatible SqlBackend BetterSqlBackend) instance PersistStoreRead BetterSqlBackend deriving via (Compatible SqlBackend BetterSqlBackend) instance PersistStoreWrite BetterSqlBackend ... These instances will go through the compatible backend (in this case,  SqlBackend) for all their queries.9These instances require that both backends have the same , but deriving  will enforce that for you. deriving via (Compatible SqlBackend BetterSqlBackend) instance HasPersistBackend BetterSqlBackend -None 2<=?  persistentGives a bunch of useful instance declarations for a backend based on its compatibility with another backend, using .*The argument should be a type of the form " forall v1 ... vn. Compatible b s  (Quantification is optional, but supported because TH won't let you have unbound type variables in a type splice). The instance is produced for s$ based on the instance defined for b6, which is constrained in the instance head to exist. v1 ... vn are implicitly quantified in the instance, which is derived via  b s.  persistentGives a bunch of useful instance declarations for a backend key based on its compatibility with another backend & key, using .*The argument should be a type of the form " forall v1 ... vn. Compatible b s  (Quantification is optional, but supported because TH won't let you have unbound type variables in a type splice). The instance is produced for  s# based on the instance defined for  b6, which is constrained in the instance head to exist. v1 ... vn are implicitly quantified in the instance, which is derived via  ( b s).None ?+None ? persistentCommit the current transaction and begin a new one. This is used when a transaction commit is required within the context of  (which brackets its provided action with a transaction begin/commit pair).  persistentCommit the current transaction and begin a new one with the specified isolation level. persistentRoll back the current transaction and begin a new one. This rolls back to the state of the last call to  or the enclosing  call.  persistentRoll back the current transaction and begin a new one with the specified isolation level. =@>?APONMLKJIHGFEDCBSQRTbcdefmnywvtrqusxpoz~}|{bcdefNone #$&./2;<>?" persistent Name of the toJSON implementation for Entity a. persistent Name of the fromJSON implementation for Entity a. persistentSettings to be passed to the  function. persistent?Which database backend we're using. This type is used for the 5 associated type in the entities that are generated.If the  value is set to , then this type is used for the non-Generic type alias. The data and type will be named: *data ModelGeneric backend = Model { ... } 5And, for convenience's sake, we provide a type alias: 4type Model = ModelGeneric $(the type you give here)  persistentCreate generic types that can be used with multiple backends. Good for reusable code, but makes error messages harder to understand. Default: False. persistent6Prefix field names with the model name. Default: True.Note: this field is deprecated. Use the mpsFieldLabelModifier and  instead.  persistentCustomise the field accessors and lens names using the entity and field name. Both arguments are upper cased."Default: appends entity and field.Note: this setting is ignored if mpsPrefixFields is set to False.  persistentCustomise the Constraint names using the entity and field name. The result should be a valid haskell type (start with an upper cased letter).!Default: appends entity and fieldNote: this setting is ignored if mpsPrefixFields is set to False. persistent Generate ToJSON/FromJSON* instances for each model types. If it's Nothing*, no instances will be generated. Default:  Just  {  = 'entityIdToJSON ,  = 'entityIdFromJSON }  persistentInstead of generating normal field accessors, generator lens-style accessors.Default: False persistentAutomatically derive these typeclass instances for all record and key types. Default: [] persistentConverts a quasi-quoted syntax into a list of entity definitions, to be used as input to the template haskell generation code (mkPersist). persistentApply  to . persistentApply  to . persistentSame as , but uses an external file instead of a quasiquotation. The recommended file extension is .persistentmodels. persistentSame as , but uses several external files instead of one. Splitting your Persistent definitions into multiple modules can potentially dramatically speed up compile times."The recommended file extension is .persistentmodels.Examples7Split your Persistent definitions into multiple files (models1, models27), then create a new module for each new file and run  there:  -- Model1.hs  [ ] $(  "models1")   -- Model2.hs  [ ] $(  "models2") Use  to create your migrations: -- Migrate.hs  [ "migrateAll"] $( : ["models1.persistentmodels","models2.persistentmodels"]) Tip: To get the same import behavior as if you were declaring all your models in one file, import your new files as Name into another file, then export  module Name.This approach may be used in the future to reduce memory usage during compilation, but so far we've only seen mild reductions.See  1https://github.com/yesodweb/persistent/issues/778persistent#778 and  /https://github.com/yesodweb/persistent/pull/791persistent#791 for more details. persistentTakes a list of (potentially) independently defined entities and properly links all foreign keys to reference the right #, tying the knot between entities.Allows users to define entities indepedently or in separate modules and then fix the cross-references between them at runtime to create a . persistentCalls  to Quasi.parse individual entities in isolation afterwards, sets references to other entities+In 2.13.0.0, this was changed to splice in [] instead of []. persistent"Create data types and appropriate  instances for the given ,s. Works well with the persist quasi-quoter.  persistentLike '  persistentSet the  in the given . The default value is . persistent Create an MkPersistSettings with default values. persistentUse the  SqlPersist backend.  persistentReturns . if the key definition has less than 2 fields. persistent%Render an error message based on the  tableName and  fieldName with the provided message. persistent&Produce code similar to the following:  instance PersistEntity e => PersistField e where toPersistValue = entityToPersistValueHelper fromPersistValue = entityFromPersistValueHelper ["col1", "col2"] sqlType _ = SqlString  persistent.Apply the given list of functions to the same  EntityDefs.*This function is useful for cases such as:share [mkSave "myDefs", mkPersist sqlSettings] [persistLowerCase|...|] persistent Save the  EntityDef!s passed in under the given name. This function was deprecated in persistent-2.13.0.09. It doesn't properly fix foreign keys. Please refer to  for a replacement. persistent Generate a  instance for the given  EntityDefs.This function is deprecated as of 2.13.0.0. You can now set cascade behavior directly in the quasiquoter. persistentCreates a declaration for the [] from the  persistent schema. This is necessary because the Persistent QuasiQuoter is unable to know the correct type of ID fields, and assumes that they are all Int64.%Provide this in the list you give to  , much like .  [ "migrateAll",  "entityDefs"] [...]  persistentAutomatically creates a valid + instance for any datatype that has valid  and ( instances. Can be very convenient for  types. persistentAutomatically creates a valid + instance for any datatype that has valid  and  instances. For a datatype T* it generates instances similar to these:  instance PersistField T where toPersistValue = PersistByteString . L.toStrict . encode fromPersistValue = (left T.pack) . eitherDecodeStrict' <=< fromPersistValue instance PersistFieldSql T where sqlType _ = SqlString   persistentThe basic function for migrating models, no Template Haskell required./It's probably best to use this in concert with , and then call $ with the result from that function. share [mkPersist sqlSettings, mkEntityDefList "entities"] [persistLowerCase| ... |] migrateAll =  entities  The function  currently implements exactly this behavior now. If you're splitting up the entity definitions into separate files, then it is better to use the entity definition list and the concatenate all the models together into a big list to call with . module Foo where share [mkPersist s, mkEntityDefList "fooModels"] ... module Bar where share [mkPersist s, mkEntityDefList "barModels"] ... module Migration where import Foo import Bar migrateAll = migrateModels (fooModels <> barModels)  persistentCreates a single function to perform all migrations for the entities defined here. One thing to be aware of is dependencies: if you have entities with foreign references, make sure to place those definitions after the entities they reference.In persistent-2.13.0.0, this was changed to *ignore* the input entity def list, and instead defer to  to get the correct entities. This avoids problems where the QuasiQuoter is unable to know what the right reference types are. This sets < to be the "single source of truth" for entity definitions.  persistent A list of & that have been defined in a previous  call. persistent Value for  persistent#The name that will be given to the  list.++5./012345667889::;<<=>>?@@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~                                                                                                                                                                                                                                                  ###################################$$$$$$%%%%%%%%%%&&&&&&"'''''''''''''''''(((((((((((((********++++++++++++++++,,,--     #$$%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%&''**persistent-2.13.0.3-L98VgAAdaWv9xCVMOjMCNr$Database.Persist.Class.PersistConfigDatabase.Persist.NamesDatabase.Persist.PersistValue3Database.Persist.SqlBackend.Internal.IsolationLevel"Database.Persist.FieldDef.InternalDatabase.Persist.Types#Database.Persist.EntityDef.InternalDatabase.Persist.FieldDef.Database.Persist.SqlBackend.Internal.Statement4Database.Persist.SqlBackend.Internal.InsertSqlResult1Database.Persist.SqlBackend.Internal.MkSqlBackendDatabase.Persist.EntityDef#Database.Persist.Class.PersistField$Database.Persist.Class.PersistEntityDatabase.Persist.Quasi.InternalDatabase.Persist.Quasi#Database.Persist.Class.PersistStore$Database.Persist.SqlBackend.InternalDatabase.Persist.SqlBackend$Database.Persist.Class.PersistUnique#Database.Persist.Class.PersistQuery$Database.Persist.Class.DeleteCascadeDatabase.Persist.Class#Database.Persist.Sql.Types.InternalDatabase.Persist.SqlDatabase.PersistDatabase.Persist.Sql.Util'Database.Persist.ImplicitIdDef.InternalDatabase.Persist.ImplicitIdDefDatabase.Persist.CompatibleDatabase.Persist.THDatabase.Persist.Types.BaseDatabase.Persist.GenericSqlrawSqlDatabase.Persist.Sql.TypesDatabase.Persist.Sql.InternalDatabase.Persist.Sql.ClassDatabase.Persist.Sql.RawDatabase.Persist.Sql.Run(Database.Persist.Sql.Orphan.PersistStore)Database.Persist.Sql.Orphan.PersistUnique(Database.Persist.Sql.Orphan.PersistQueryDatabase.Persist.Sql.Migration!Database.Persist.Compatible.TypesDatabase.Persist.Compatible.TH PersistConfigPersistConfigBackendPersistConfigPool loadConfigapplyEnvcreatePoolConfigrunPool$fPersistConfigEitherConstraintNameHSunConstraintNameHSConstraintNameDBunConstraintNameDB EntityNameDBunEntityNameDB EntityNameHSunEntityNameHS FieldNameHS unFieldNameHS FieldNameDB unFieldNameDB DatabaseName escapeWith$fDatabaseNameFieldNameDB$fDatabaseNameEntityNameDB$fDatabaseNameConstraintNameDB$fShowConstraintNameHS$fEqConstraintNameHS$fReadConstraintNameHS$fOrdConstraintNameHS$fLiftLiftedRepConstraintNameHS$fShowConstraintNameDB$fEqConstraintNameDB$fReadConstraintNameDB$fOrdConstraintNameDB$fLiftLiftedRepConstraintNameDB$fShowEntityNameDB$fEqEntityNameDB$fReadEntityNameDB$fOrdEntityNameDB$fLiftLiftedRepEntityNameDB$fShowEntityNameHS$fEqEntityNameHS$fReadEntityNameHS$fOrdEntityNameHS$fLiftLiftedRepEntityNameHS$fShowFieldNameHS$fEqFieldNameHS$fReadFieldNameHS$fOrdFieldNameHS$fLiftLiftedRepFieldNameHS$fShowFieldNameDB$fEqFieldNameDB$fReadFieldNameDB$fOrdFieldNameDB$fLiftLiftedRepFieldNameDB LiteralTypeEscaped Unescaped DbSpecific PersistValue PersistTextPersistByteString PersistInt64 PersistDoublePersistRational PersistBool PersistDayPersistTimeOfDayPersistUTCTime PersistNull PersistList PersistMapPersistObjectId PersistArrayPersistLiteral_PersistLiteralPersistLiteralEscapedPersistDbSpecificfromPersistValueText$fFromJSONPersistValue$fToJSONPersistValue$fPathPiecePersistValue$fFromHttpApiDataPersistValue$fToHttpApiDataPersistValue$fShowPersistValue$fReadPersistValue$fEqPersistValue$fOrdPersistValue$fShowLiteralType$fReadLiteralType$fEqLiteralType$fOrdLiteralTypeIsolationLevelReadUncommitted ReadCommittedRepeatableRead SerializablemakeIsolationLevelStatement$fShowIsolationLevel$fEqIsolationLevel$fEnumIsolationLevel$fOrdIsolationLevel$fBoundedIsolationLevelFieldDef fieldHaskellfieldDB fieldType fieldSqlType fieldAttrs fieldStrictfieldReference fieldCascade fieldCommentsfieldGeneratedfieldIsImplicitIdColumn PersistUpdateAssignAddSubtractMultiplyDivideBackendSpecificUpdateUpdateException KeyNotFound UpsertError PersistFilterEqNeGtLtGeLeInNotInBackendSpecificFilterSqlType SqlStringSqlInt32SqlInt64SqlReal SqlNumericSqlBoolSqlDaySqlTime SqlDayTimeSqlBlobSqlOtherPersistException PersistErrorPersistMarshalErrorPersistInvalidFieldPersistForeignConstraintUnmetPersistMongoDBErrorPersistMongoDBUnsupported CascadeActionCascadeRestrictSetNull SetDefault FieldCascade fcOnUpdate fcOnDelete ForeignDefforeignRefTableHaskellforeignRefTableDBNameforeignConstraintNameHaskellforeignConstraintNameDBNameforeignFieldCascade foreignFields foreignAttrsforeignNullableforeignToPrimaryForeignFieldDef CompositeDefcompositeFieldscompositeAttrs UniqueDef uniqueHaskell uniqueDBName uniqueFields uniqueAttrs EmbedFieldDef emFieldDB emFieldEmbedEmbedEntityDefembeddedHaskellembeddedFields ReferenceDef NoReference ForeignRefEmbedRef CompositeRef SelfReference FieldType FTTypeConFTTypePromotedFTAppFTList FieldAttrFieldAttrMaybeFieldAttrNullableFieldAttrMigrationOnlyFieldAttrSafeToRemoveFieldAttrNoreferenceFieldAttrReferenceFieldAttrConstraintFieldAttrDefaultFieldAttrSqltypeFieldAttrMaxlen FieldAttrSqlFieldAttrOtherAttr ExtraLine EntityIdDef EntityIdFieldEntityIdNaturalKey EntityDef entityHaskellentityDBentityId entityAttrs entityFields entityUniquesentityForeigns entityDerives entityExtra entitySumentityComments WhyNullable ByMaybeAttrByNullableAttr IsNullableNullable NotNullable CheckmarkActiveInactiveentitiesPrimary entityPrimarykeyAndEntityFieldsparseFieldAttrsisFieldNotGeneratedisHaskellFieldtoEmbedEntityDef noCascaderenderFieldCascaderenderCascadeAction Statement stmtFinalize stmtReset stmtExecute stmtQueryInsertSqlResult ISRSingle ISRInsertGet ISRManyKeysLogFuncMkSqlBackendArgs connPrepare connInsertSql connStmtMap connCloseconnMigrateSql connBegin connCommit connRollbackconnEscapeFieldNameconnEscapeTableNameconnEscapeRawName connNoLimit connRDBMSconnLimitOffset connLogFunc setFieldAttrsoverFieldAttrs addFieldAttrgetEntityUniquesgetEntityHaskellNamegetEntityDBNamegetEntityExtrasetEntityDBNamegetEntityCommentsgetEntityForeignDefsgetEntityFieldsgetEntityFieldsDatabase isEntitySum getEntityIdgetEntityIdField setEntityIdsetEntityIdDefgetEntityKeyFieldsoverEntityFieldsSomePersistFieldOverflowNaturalunOverflowNatural PersistFieldtoPersistValuefromPersistValue getPersistMap$fPersistFieldCheckmark$fPersistFieldPersistValue$fPersistFieldMap$fPersistFieldIntMap$fPersistField(,)$fPersistFieldSet$fPersistFieldVector$fPersistField[]$fPersistFieldMaybe$fPersistFieldNatural$fPersistFieldUTCTime$fPersistFieldTimeOfDay$fPersistFieldDay$fPersistFieldBool$fPersistFieldRatio$fPersistFieldFixed$fPersistFieldDouble$fPersistFieldWord64$fPersistFieldWord32$fPersistFieldWord16$fPersistFieldWord8$fPersistFieldWord$fPersistFieldInt64$fPersistFieldInt32$fPersistFieldInt16$fPersistFieldInt8$fPersistFieldInt$fPersistFieldMarkupM$fPersistFieldText$fPersistFieldText0$fPersistFieldByteString$fPersistField[]0$fPersistFieldOverflowNatural$fPersistFieldSomePersistField$fEqOverflowNatural$fShowOverflowNatural$fOrdOverflowNatural SymbolToField symbolToFieldEntity entityKey entityVal FilterValue FilterValues UnsafeValueFilter FilterAndFilterOr BackendFilter filterField filterValue filterFilter SelectOptAscDescOffsetByLimitToUpdate BackendUpdate updateField updateValue updateUpdate PersistEntityPersistEntityBackendKey EntityFieldUnique keyToValues keyFromValuespersistIdField entityDefpersistFieldDeftoPersistFieldsfromPersistValuespersistUniqueKeyspersistUniqueToFieldNamespersistUniqueToValues fieldLenskeyFromRecordM recordName entityValueskeyValueEntityToJSONkeyValueEntityFromJSONentityIdToJSONentityIdFromJSONtoPersistValueJSONfromPersistValueJSONtoPersistValueEnumfromPersistValueEnum$fPersistFieldEntity$fIsLabelsymEntityField $fReadEntity $fShowEntity $fOrdEntity $fEqEntity$fGenericEntityForeignFieldReferenceffrSourceFieldffrTargetFieldUnboundForeignFieldListFieldListImpliedIdFieldListHasReferencesUnboundForeignDefunboundForeignFieldsunboundForeignDefUnboundCompositeDefunboundCompositeColsunboundCompositeAttrs UnboundIdDefunboundIdEntityNameunboundIdDBNameunboundIdAttrsunboundIdCascade unboundIdType PrimarySpec NaturalKey SurrogateKey DefaultKeyUnboundFieldDefunboundFieldNameHSunboundFieldNameDBunboundFieldAttrsunboundFieldStrictunboundFieldTypeunboundFieldCascadeunboundFieldGeneratedunboundFieldCommentsUnboundEntityDefunboundForeignDefsunboundPrimarySpecunboundEntityDefunboundEntityFieldsLinesWithCommentslwcLines lwcCommentsLine lineIndenttokensToken DocCommentPersistSettings psToDBName psToFKNamepsStrictFieldspsIdNameparseFieldTypeupperCaseSettingslowerCaseSettingstoFKNameInfixedparsepreparse parseLineassociateLinesunbindEntityDefgetUnboundFieldDefsunbindFieldDefunboundIdDefToFieldDef mkKeyConTypemkAutoIdField' splitExtras takeColsEx getSqlNameOrnullableisHaskellUnboundFieldgetUnboundEntityNameHS$fSemigroupLinesWithComments$fEqUnboundEntityDef$fOrdUnboundEntityDef$fShowUnboundEntityDef$fLiftLiftedRepUnboundEntityDef$fEqUnboundForeignDef$fOrdUnboundForeignDef$fShowUnboundForeignDef $fLiftLiftedRepUnboundForeignDef$fEqUnboundForeignFieldList$fOrdUnboundForeignFieldList$fShowUnboundForeignFieldList&$fLiftLiftedRepUnboundForeignFieldList$fEqForeignFieldReference$fOrdForeignFieldReference$fShowForeignFieldReference$$fLiftLiftedRepForeignFieldReference$fEqPrimarySpec$fOrdPrimarySpec$fShowPrimarySpec$fLiftLiftedRepPrimarySpec$fEqUnboundCompositeDef$fOrdUnboundCompositeDef$fShowUnboundCompositeDef"$fLiftLiftedRepUnboundCompositeDef$fEqUnboundIdDef$fOrdUnboundIdDef$fShowUnboundIdDef$fLiftLiftedRepUnboundIdDef$fEqUnboundFieldDef$fOrdUnboundFieldDef$fShowUnboundFieldDef$fLiftLiftedRepUnboundFieldDef$fEqLinesWithComments$fShowLinesWithComments$fEqLine $fShowLine $fShowToken $fEqToken$fShowParseState getPsToDBName setPsToDBName setPsToFKNamesetPsUseSnakeCaseForiegnKeysgetPsStrictFieldssetPsStrictFields getPsIdName setPsIdNamePersistStoreWriteinsertinsert_ insertMany insertMany_insertEntityMany insertKeyrepsert repsertManyreplacedeleteupdate updateGetPersistStoreReadgetgetMany PersistCore BackendKey ToBackendKey toBackendKeyfromBackendKeyPersistRecordBackendBackendCompatibleprojectBackendIsPersistBackendmkPersistBackendHasPersistBackend BaseBackendpersistBackendwithBaseBackendwithCompatibleBackend liftPersistgetJust getJustEntity belongsTo belongsToJust insertEntity getEntity insertRecord SqlBackendconnInsertManySql connUpsertSqlconnPutManySql connMaxParamsconnRepsertManySql mkSqlBackend$fIsPersistBackendSqlBackend$fHasPersistBackendSqlBackendgetEscapedFieldNamegetEscapedRawNamegetEscapeRawNameFunctiongetConnLimitOffsetgetConnUpsertSqlsetConnMaxParamssetConnRepsertManySqlsetConnInsertManySqlsetConnUpsertSqlsetConnPutManySqlAtLeastOneUniqueKeyrequireUniquesPMultipleUniqueKeysErrorNoUniqueKeysErrorOnlyOneUniqueKey onlyUniquePPersistUniqueWritedeleteBy insertUniqueupsertupsertByputManyPersistUniqueReadgetByonlyOneUniqueDefatLeastOneUniqueDefinsertByinsertUniqueEntity onlyUnique getByValuegetByValueUniques replaceUnique checkUniquecheckUniqueUpdateabledefaultUpsertBydefaultPutManypersistUniqueKeyValuesPersistQueryWrite updateWhere deleteWherePersistQueryReadselectSourceRes selectFirst selectKeysRescountexists selectSource selectKeys selectListselectKeysList DeleteCascade deleteCascadedeleteCascadeWhere PersistStore PersistQuery PersistUnique IsSqlBackend SqlWriteTSqlReadTSqlBackendCanWriteSqlBackendCanReadSqlWriteBackend&$sel:unSqlWriteBackend:SqlWriteBackendSqlReadBackend$$sel:unSqlReadBackend:SqlReadBackendwriteToUnknown readToWrite readToUnknown $fIsPersistBackendSqlReadBackend!$fHasPersistBackendSqlReadBackend!$fIsPersistBackendSqlWriteBackend"$fHasPersistBackendSqlWriteBackendPersistUnsafeMigrationExceptionSingleunSingleConnectionPoolConfigconnectionPoolConfigStripesconnectionPoolConfigIdleTimeoutconnectionPoolConfigSizeConnectionPool MigrationCautiousMigrationSql SqlPersistM SqlPersistTPersistentSqlExceptionStatementAlreadyFinalizedCouldn'tGetSQLConnectionColumnReference crTableNamecrConstraintNamecrFieldCascadeColumncNamecNullcSqlTypecDefault cGeneratedcDefaultConstraintNamecMaxLen cReferencedefaultConnectionPoolConfigBackendSpecificOverrides getBackendSpecificForeignKeyName setBackendSpecificForeignKeyNameemptyBackendSpecificOverridesdefaultAttribute mkColumns=.+=.-=.*=./=.==.!=.<.<=.>.>=.<-./<-.||. listToJSON mapToJSON toJsonTextlimitOffsetOrderkeyAndEntityColumnNamesentityColumnCount hasNaturalKeyhasCompositePrimaryKey dbIdColumnsdbIdColumnsEsc dbColumnsparseEntityValues isIdFieldupdateFieldDefupdatePersistValuecommaSeparated mkUpdateText mkUpdateText' parenWrappedmkInsertValuesmkInsertPlaceholdersPersistFieldSqlsqlTypeEntityWithPrefixunEntityWithPrefixRawSql rawSqlColsrawSqlColCountReasonrawSqlProcessRowunPrefixrawQuery rawQueryRes rawExecuterawExecuteCount getStmtConn runSqlPoolrunSqlPoolWithIsolationrunSqlPoolNoTransactionrunSqlPoolWithHooksacquireSqlConnacquireSqlConnWithIsolation runSqlConnrunSqlConnWithIsolationrunSqlPersistMrunSqlPersistMPoolliftSqlPersistMPool withSqlPoolwithSqlPoolWithConfig createSqlPoolcreateSqlPoolWithConfig withSqlConnclose'SqlWriteBackendKeyunSqlWriteBackendKeySqlReadBackendKeyunSqlReadBackendKey SqlBackendKeyunSqlBackendKey withRawQuerytoSqlKey fromSqlKey getTableName tableDBName getFieldName fieldDBNameFilterTablePrefixPrefixTableNamePrefixExcludeddeleteWhereCountupdateWhereCount filterClausefilterClauseWithValsdecorateSQLWithLimitOffsetparseMigrationparseMigration'printMigration showMigration getMigration runMigrationrunMigrationQuietrunMigrationSilentrunMigrationUnsaferunMigrationUnsafeQuietmigrate reportError reportErrors addMigration addMigrations runSqlCommand ImplicitIdDef iidFieldTypeiidFieldSqlTypeiidType iidDefault iidMaxLenmkImplicitIdDefsetImplicitIdDefMaxLenfieldTypeFromTypeableunsafeClearDefaultImplicitIdautoIncrementingInteger Compatible unCompatiblemakeCompatibleInstancesmakeCompatibleKeyInstancestransactionSavetransactionSaveWithIsolationtransactionUndotransactionUndoWithIsolation EntityJSON entityToJSONentityFromJSONMkPersistSettings mpsBackend mpsGenericmpsPrefixFieldsmpsFieldLabelModifiermpsConstraintLabelModifier mpsEntityJSONmpsGenerateLensesmpsDeriveInstances persistWithpersistUpperCasepersistLowerCasepersistFileWithpersistManyFileWithembedEntityDefsparseReferences mkPersist mkPersistWithsetImplicitIdDefmkPersistSettings sqlSettingslensPTH pkNewtype fieldErrorpersistFieldFromEntitysharemkSavemkDeleteCascademkEntityDefListderivePersistFieldderivePersistFieldJSON migrateModels mkMigratediscoverEntities$fShowFTTypeConDescr$fShowSqlTypeExp$aeson-1.5.6.0-4Fai2YBAOjp98HRNOvB9PwData.Aeson.Types.InternalValueghc-prim GHC.TypesTrueFalsebase GHC.MaybeNothingMaybeGHC.BaseNonEmpty text-1.2.3.2Data.Text.InternalTextOnlyUniqueException SelfEmbedentityKeyFields GHC.NaturalNaturalGHC.IntInt64Wordbytestring-0.10.10.0Data.ByteString.Internal ByteString Data.EitherEitherRightLeftGHC.EnumEnumBoundedtransformers-0.5.6.2Control.Monad.Trans.ReaderReaderTJustControl.Monad.Trans.Writer.LazyWriterTIO%$fShowPersistUnsafeMigrationExceptionGHC.ShowShowbackendSpecificForeignKeyNameData.Aeson.Types.ToJSONToJSON Data.Functor<$>$fRawSql(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,)$fRawSql(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,)$fRawSql(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,)$fRawSql(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,)$fRawSql(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,)$fRawSql(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,)$fRawSql(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,)$fRawSql(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,)?$fRawSql(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,)>$fRawSql(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,)=$fRawSql(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,)<$fRawSql(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,);$fRawSql(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,):$fRawSql(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,)9$fRawSql(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,)8$fRawSql(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,)7$fRawSql(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,)6$fRawSql(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,)5$fRawSql(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,)4$fRawSql(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,)3$fRawSql(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,)2$fRawSql(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,)1$fRawSql(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,)0$fRawSql(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,)/$fRawSql(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,).$fRawSql(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,)-$fRawSql(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,),$fRawSql(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,)+$fRawSql(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,)*$fRawSql(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,))$fRawSql(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,)($fRawSql(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,)'$fRawSql(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,)&$fRawSql(,,,,,,,,,,,,,,,,,,,,,,,,,,,,)%$fRawSql(,,,,,,,,,,,,,,,,,,,,,,,,,,,)$$fRawSql(,,,,,,,,,,,,,,,,,,,,,,,,,,)#$fRawSql(,,,,,,,,,,,,,,,,,,,,,,,,,)"$fRawSql(,,,,,,,,,,,,,,,,,,,,,,,,)!$fRawSql(,,,,,,,,,,,,,,,,,,,,,,,) $fRawSql(,,,,,,,,,,,,,,,,,,,,,,)$fRawSql(,,,,,,,,,,,,,,,,,,,,,)$fRawSql(,,,,,,,,,,,,,,,,,,,,)$fRawSql(,,,,,,,,,,,,,,,,,,,)$fRawSql(,,,,,,,,,,,,,,,,,,)$fRawSql(,,,,,,,,,,,,,,,,,)$fRawSql(,,,,,,,,,,,,,,,,)$fRawSql(,,,,,,,,,,,,,,,)$fRawSql(,,,,,,,,,,,,,,)$fRawSql(,,,,,,,,,,,,,)$fRawSql(,,,,,,,,,,,,)$fRawSql(,,,,,,,,,,,)$fRawSql(,,,,,,,,,,)$fRawSql(,,,,,,,,,)$fRawSql(,,,,,,,,) $fRawSqlMaybe $fPersistFieldSqlOverflowNaturalgetStmt,resource-pool-0.2.3.2-KX1jewTp7d0E5JKwXiQz7V Data.PoolPool,unliftio-core-0.2.0.1-9GVcmaajsglG88oErAZOTVControl.Monad.IO.Unlift MonadUnliftIO rawRunSqlPoolrawAcquireSqlConnfilterClauseHelperGHC.ErrerrorGHC.IO.Handle.FDstderrBooltemplate-haskellLanguage.Haskell.TH.SyntaxTypeData.Typeable.InternalTypeableStringGHC.ReadReadData.Aeson.Types.FromJSONFromJSON++