Convert a list of values to an Array.
Moduleyesod-1.6.2.1Haskell2010
Yesod
This module simply re-exports from other modules for your convenience.
- 113 types
- 50 classes
- 494 values
- Packageyesod-1.6.2.1
- Exports677
- LanguageHaskell2010
- LicenceMIT
- SourceYesod.hs
Re-exports from yesod-core
677 declarationsA convenience method to run an application using the Warp webserver on the specified port. Automatically calls toWaiApp. Provides a default set of middlewares. This set may change at any point without a breaking version number. Currently, it includes:
Logging
GZIP compression
Automatic HEAD method handling
Request method override with the _method query string parameter
Accept header override with the _accept query string parameter
If you need more fine-grained control of middlewares, please use toWaiApp directly.
Since 1.2.0
Define settings for a Yesod applications. All methods have intelligent defaults, and therefore no implementation is required.
Methods
approot :: Approot siteAn absolute URL to the root of the application. Do not include trailing slash.
Default value: guessApproot. If you know your application root statically, it will be more efficient and more reliable to instead use ApprootStatic or ApprootMaster. If you do not need full absolute URLs, you can use ApprootRelative instead.
Note: Prior to yesod-core 1.5, the default value was ApprootRelative.
catchHandlerExceptions :: MonadUnliftIO m => site -> m a -> (SomeException -> m a) -> m aallows the user to specify how exceptions are cought. by default all async exceptions are thrown and synchronous exceptions render a 500 page. To catch all exceptions (even async) to render a 500 page, set this to catchSyncOrAsync. Beware this may have negative effects with functions like
timeout.errorHandler :: ErrorResponse -> HandlerFor site TypedContentOutput error response pages.
Default value: defaultErrorHandler.
defaultLayout :: WidgetFor site () -> HandlerFor site HtmlApplies some form of layout to the contents of a page.
urlParamRenderOverride :: site -> Route site -> [(Text, Text)] -> Maybe BuilderOverride the rendering function for a particular URL and query string parameters. One use case for this is to offload static hosting to a different domain name to avoid sending cookies.
For backward compatibility default implementation is in terms of
urlRenderOverride, probably ineffectiveSince 1.4.23
isAuthorized :: Route site -> Bool -> HandlerFor site AuthResultDetermine if a request is authorized or not.
Return Authorized if the request is authorized, Unauthorized a message if unauthorized. If authentication is required, return AuthenticationRequired.
isWriteRequest :: Route site -> HandlerFor site BoolDetermines whether the current request is a write request. By default, this assumes you are following RESTful principles, and determines this from request method. In particular, all except the following request methods are considered write: GET HEAD OPTIONS TRACE.
This function is used to determine if a request is authorized; see isAuthorized.
authRoute :: site -> Maybe (Route site)The default route for authentication.
Used in particular by isAuthorized, but library users can do whatever they want with it.
cleanPath :: site -> [Text] -> Either [Text] [Text]A function used to clean up path segments. It returns Right with a clean path or Left with a new set of pieces the user should be redirected to. The default implementation enforces:
No double slashes
There is no trailing slash.
Note that versions of Yesod prior to 0.7 used a different set of rules involing trailing slashes.
joinPath :: site -> Text -> [Text] -> [(Text, Text)] -> BuilderBuilds an absolute URL by concatenating the application root with the pieces of a path and a query string, if any. Note that the pieces of the path have been previously cleaned up by cleanPath.
addStaticContent :: Text -> Text -> ByteString -> HandlerFor site (Maybe (Either Text (Route site, [(Text, Text)])))This function is used to store some static content to be served as an external file. The most common case of this is stashing CSS and JavaScript content in an external file; the
Yesod.Widgetmodule uses this feature.The return value is Nothing if no storing was performed; this is the default implementation. A Just Left gives the absolute URL of the file, whereas a Just Right gives the type-safe URL. The former is necessary when you are serving the content outside the context of a Yesod application, such as via memcached.
maximumContentLength :: site -> Maybe (Route site) -> Maybe Word64Maximum allowed length of the request body, in bytes. This method may be ignored if maximumContentLengthIO is overridden.
If
Nothing, no maximum is applied.Default: 2 megabytes.
maximumContentLengthIO :: site -> Maybe (Route site) -> IO (Maybe Word64)Maximum allowed length of the request body, in bytes. This is similar to maximumContentLength, but the result lives in
IO. This allows you to dynamically change the maximum file size based on some external source like a database or anIORef.The default implementation uses maximumContentLength. Future version of yesod will remove maximumContentLength and use this method exclusively.
makeLogger :: site -> IO LoggerCreates a
Loggerto use for log messages.Note that a common technique (endorsed by the scaffolding) is to create a
Loggervalue and place it in your foundation datatype, and have this method return that already created value. That way, you can use that sameLoggerfor printing messages during app initialization.Default: the defaultMakeLogger function.
messageLoggerSource :: site -> Logger -> Loc -> LogSource -> LogLevel -> LogStr -> IO ()Send a message to the
Loggerprovided bygetLogger.Default: the defaultMessageLoggerSource function, using shouldLogIO to check whether we should log.
jsLoader :: site -> ScriptLoadPosition siteWhere to Load sripts from. We recommend the default value, BottomOfBody.
jsAttributes :: site -> [(Text, Text)]Default attributes to put on the JavaScript script tag generated for julius files
jsAttributesHandler :: HandlerFor site [(Text, Text)]Same as
jsAttributesbut allows you to run arbitrary Handler codeThis is useful if you need to add a randomised nonce value to the script tag generated by
widgetFile. If this function is overridden thenjsAttributesis ignored.makeSessionBackend :: site -> IO (Maybe SessionBackend)Create a session backend. Returning Nothing disables sessions. If you'd like to change the way that the session cookies are created, take a look at customizeSessionCookies.
Default: Uses clientsession with a 2 hour timeout.
fileUpload :: site -> RequestBodyLength -> FileUploadHow to store uploaded files.
Default: When the request body is greater than 50kb, store in a temp file. For chunked request bodies, store in a temp file. Otherwise, store in memory.
shouldLogIO :: site -> LogSource -> LogLevel -> IO BoolShould we log the given log source/level combination.
Default: the defaultShouldLogIO function.
Since 1.2.4
yesodMiddleware :: ToTypedContent res => HandlerFor site res -> HandlerFor site resA Yesod middleware, which will wrap every handler function. This allows you to run code before and after a normal handler.
Default: the defaultYesodMiddleware function.
Since: 1.1.6
yesodWithInternalState :: site -> Maybe (Route site) -> (InternalState -> IO a) -> IO aHow to allocate an
InternalStatefor each request.The default implementation is almost always what you want. However, if you know that you are never taking advantage of the
MonadResourceinstance in your handler functions, setting this to a dummy implementation can provide a small optimization. Only do this if you really know what you're doing, otherwise you can turn safe code into a runtime error!Since 1.4.2
defaultMessageWidget :: Html -> HtmlUrl (Route site) -> WidgetFor site ()Convert a title and HTML snippet into a
Widget. Used primarily for wrapping up error messages for better display.
A JSON value represented as a Haskell value.
Instances41Eq, Data, Ord, Read, Show, IsString, …
Eq ValueDefined in aeson-2.2.3.0 · Data.Aeson.Types.InternalData ValueDefined in aeson-2.2.3.0 · Data.Aeson.Types.InternalOrd ValueDefined in aeson-2.2.3.0 · Data.Aeson.Types.InternalThe ordering is total, consistent with Eq instance. However, nothing else about the ordering is specified, and it may change from environment to environment and version to version of either this package or its dependencies (
hashableand 'unordered-containers').Read ValueDefined in aeson-2.2.3.0 · Data.Aeson.Types.InternalShow ValueDefined in aeson-2.2.3.0 · Data.Aeson.Types.InternalSince version 1.5.6.0 version object values are printed in lexicographic key order
Example1 expression toJSON $ H.fromList [("a", True), ("z", False)]Object (fromList [("a",Bool True),("z",Bool False)])
Example1 expression toJSON $ H.fromList [("z", False), ("a", True)]Object (fromList [("a",Bool True),("z",Bool False)])
IsString ValueDefined in aeson-2.2.3.0 · Data.Aeson.Types.InternalGeneric ValueDefined in aeson-2.2.3.0 · Data.Aeson.Types.InternalNFData ValueDefined in aeson-2.2.3.0 · Data.Aeson.Types.InternalArbitrary ValueDefined in aeson-2.2.3.0 · Data.Aeson.Types.InternalCoArbitrary ValueDefined in aeson-2.2.3.0 · Data.Aeson.Types.InternalFunction ValueDefined in aeson-2.2.3.0 · Data.Aeson.Types.InternalHashable ValueDefined in aeson-2.2.3.0 · Data.Aeson.Types.InternalFromJSON ValueDefined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONToJSON ValueDefined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJavascript ValueDefined in shakespeare-2.1.0.1 · Text.JuliusHasContentType ValueDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToContent ValueDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToTypedContent ValueDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentLift ValueDefined in aeson-2.2.3.0 · Data.Aeson.Types.InternalKeyValue Encoding SeriesDefined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONKeyValueOmit Encoding SeriesDefined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSON(GToJSON' Encoding arity a, ConsToJSON Encoding arity a, Constructor c) => SumToJSON' TwoElemArray Encoding arity (C1 c a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSON(GToJSON' Value arity a, ConsToJSON Value arity a, Constructor c) => SumToJSON' TwoElemArray Value arity (C1 c a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONGToJSON' Encoding arity U1Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONGToJSON' Encoding arity V1Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONGToJSON' Value arity U1Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONGToJSON' Value arity V1Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON1 f => GToJSON' Encoding One (Rec1 f)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON1 f => GToJSON' Value One (Rec1 f)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON a => GToJSON' Encoding arity (K1 i a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON a => GToJSON' Value arity (K1 i a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSON(EncodeProduct arity a, EncodeProduct arity b) => GToJSON' Encoding arity (a :*: b)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSON(WriteProduct arity a, WriteProduct arity b, ProductSize a, ProductSize b) => GToJSON' Value arity (a :*: b)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSON(ToJSON1 f, GToJSON' Encoding One g) => GToJSON' Encoding One (f :.: g)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSON(ToJSON1 f, GToJSON' Value One g) => GToJSON' Value One (f :.: g)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONvalue ~ Value => KeyValue Value (KeyMap value)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONvalue ~ Value => KeyValueOmit Value (KeyMap value)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONFromPairs Value (DList Pair)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONv ~ Value => KeyValuePair v (DList Pair)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSON(key ~ Key, value ~ Value) => KeyValue Value (key, value)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONtype Rep Value = D1 ('MetaDataDefined in aeson-2.2.3.0 · Data.Aeson.Types.Internal"Value"
"Data.Aeson.Types.Internal"
"aeson-2.2.3.0-8wqDv5YwVfEFAGhRLvt8rk"
'False) ((C1 ('MetaCons"Object"
'PrefixI 'False) (S1 ('MetaSel 'Nothing 'NoSourceUnpackedness 'SourceStrict 'DecidedStrict) (Rec0 Object)) :+: (C1 ('MetaCons"Array"
'PrefixI 'False) (S1 ('MetaSel 'Nothing 'NoSourceUnpackedness 'SourceStrict 'DecidedStrict) (Rec0 Array)) :+: C1 ('MetaCons"String"
'PrefixI 'False) (S1 ('MetaSel 'Nothing 'NoSourceUnpackedness 'SourceStrict 'DecidedStrict) (Rec0 Text)))) :+: (C1 ('MetaCons"Number"
'PrefixI 'False) (S1 ('MetaSel 'Nothing 'NoSourceUnpackedness 'SourceStrict 'DecidedStrict) (Rec0 Scientific)) :+: (C1 ('MetaCons"Bool"
'PrefixI 'False) (S1 ('MetaSel 'Nothing 'NoSourceUnpackedness 'SourceStrict 'DecidedStrict) (Rec0 Bool)) :+: C1 ('MetaCons"Null"
'PrefixI 'False) U1)))
The WAI application.
Note that, since WAI 3.0, this type is structured in continuation passing
style to allow for proper safe resource handling. This was handled in the
past via other means (e.g., ResourceT). As a demonstration:
app :: Application
app req respond = bracket_
(putStrLn "Allocating scarce resource")
(putStrLn "Cleaning up")
(respond $ responseLBS status200 [] "Hello World")
Instances2ToApplication
ToApplication ApplicationDefined in wai-extra-3.1.16 · Network.Wai.UrlMapToApplication UrlMapDefined in wai-extra-3.1.16 · Network.Wai.UrlMap
Constructors
Instances5Eq, Ord, Read, Show, Lift
Eq LogLevelDefined in monad-logger-0.3.42 · Control.Monad.LoggerOrd LogLevelDefined in monad-logger-0.3.42 · Control.Monad.LoggerRead LogLevelDefined in monad-logger-0.3.42 · Control.Monad.LoggerShow LogLevelDefined in monad-logger-0.3.42 · Control.Monad.LoggerLift LogLevelDefined in monad-logger-0.3.42 · Control.Monad.Logger
Associated types
type family HandlerSite (m :: Type -> Type)type family SubHandlerSite (m :: Type -> Type)
Methods
liftHandler :: HandlerFor (HandlerSite m) a -> m aliftSubHandler :: SubHandlerFor (SubHandlerSite m) (HandlerSite m) a -> m a
Instances15MonadHandler, …
MonadHandler (HandlerFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.Class.HandlerMonadHandler (WidgetFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.Class.HandlerMonadHandler m => MonadHandler (MaybeT m)Defined in yesod-core-1.6.26.0 · Yesod.Core.Class.HandlerMonadHandler (SubHandlerFor sub master)Defined in yesod-core-1.6.26.0 · Yesod.Core.Class.HandlerMonadHandler m => MonadHandler (ExceptT e m)Defined in yesod-core-1.6.26.0 · Yesod.Core.Class.HandlerMonadHandler m => MonadHandler (IdentityT m)Defined in yesod-core-1.6.26.0 · Yesod.Core.Class.HandlerMonadHandler m => MonadHandler (ReaderT r m)Defined in yesod-core-1.6.26.0 · Yesod.Core.Class.HandlerMonadHandler m => MonadHandler (StateT s m)Defined in yesod-core-1.6.26.0 · Yesod.Core.Class.HandlerMonadHandler m => MonadHandler (StateT s m)Defined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handler(Monoid w, MonadHandler m) => MonadHandler (WriterT w m)Defined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handler(Monoid w, MonadHandler m) => MonadHandler (WriterT w m)Defined in yesod-core-1.6.26.0 · Yesod.Core.Class.HandlerMonadHandler m => MonadHandler (ConduitM i o m)Defined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handler(Monoid w, MonadHandler m) => MonadHandler (RWST r w s m)Defined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handler(Monoid w, MonadHandler m) => MonadHandler (RWST r w s m)Defined in yesod-core-1.6.26.0 · Yesod.Core.Class.HandlerMonadHandler m => MonadHandler (Pipe l i o u m)Defined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handler
Bypass remaining handler code and output the given file.
For some backends, this is more efficient than reading in the file to memory, since they can optimize file sending via a system call to sendfile.
Associated types
data family Route aThe type-safe URLs associated with a site argument.
Methods
renderRoute :: Route a -> ([Text], [(Text, Text)])
Instances3RenderRoute
RenderRoute LiteAppDefined in yesod-core-1.6.26.0 · Yesod.Core.Internal.LiteAppRenderRoute WaiSubsiteDefined in yesod-core-1.6.26.0 · Yesod.Core.TypesRenderRoute WaiSubsiteWithAuthDefined in yesod-core-1.6.26.0 · Yesod.Core.Types
The type-safe URLs associated with a site argument.
Instances18RedirectUrl, Eq, Ord, Read, Show, Route, …
RedirectUrl master (Route master)Defined in yesod-core-1.6.26.0 · Yesod.Core.Handler(key ~ Text, val ~ Text) => RedirectUrl master (Route master, Map key val)Defined in yesod-core-1.6.26.0 · Yesod.Core.Handler(key ~ Text, val ~ Text) => RedirectUrl master (Route master, [(key, val)])Defined in yesod-core-1.6.26.0 · Yesod.Core.HandlerEq (Route LiteApp)Defined in yesod-core-1.6.26.0 · Yesod.Core.Internal.LiteAppEq (Route WaiSubsite)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesEq (Route WaiSubsiteWithAuth)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesOrd (Route LiteApp)Defined in yesod-core-1.6.26.0 · Yesod.Core.Internal.LiteAppOrd (Route WaiSubsite)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesOrd (Route WaiSubsiteWithAuth)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesRead (Route LiteApp)Defined in yesod-core-1.6.26.0 · Yesod.Core.Internal.LiteAppRead (Route WaiSubsite)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesRead (Route WaiSubsiteWithAuth)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesShow (Route LiteApp)Defined in yesod-core-1.6.26.0 · Yesod.Core.Internal.LiteAppShow (Route WaiSubsite)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesShow (Route WaiSubsiteWithAuth)Defined in yesod-core-1.6.26.0 · Yesod.Core.Typesdata Route LiteAppDefined in yesod-core-1.6.26.0 · Yesod.Core.Internal.LiteAppdata Route WaiSubsiteDefined in yesod-core-1.6.26.0 · Yesod.Core.Typesdata Route WaiSubsiteWithAuthDefined in yesod-core-1.6.26.0 · Yesod.Core.Types
A type that can be converted from JSON, with the possibility of failure.
In many cases, you can get the compiler to generate parsing code for you (see below). To begin, let's cover writing an instance by hand.
There are various reasons a conversion could fail. For example, an Object could be missing a required key, an Array could be of the wrong size, or a value could be of an incompatible type.
The basic ways to signal a failed conversion are as follows:
fail yields a custom error message: it is the recommended way of reporting a failure;
empty (or mzero) is uninformative: use it when the error is meant to be caught by some
(<|>);typeMismatch can be used to report a failure when the encountered value is not of the expected JSON type; unexpected is an appropriate alternative when more than one type may be expected, or to keep the expected type implicit.
prependFailure (or modifyFailure) add more information to a parser's error messages.
An example type and instance using typeMismatch and prependFailure:
-- Allow ourselves to write Text literals.
{-# LANGUAGE OverloadedStrings #-}
data Coord = Coord { x :: Double, y :: Double }
instance FromJSON Coord where
parseJSON (Object v) = Coord
<$> v .: "x"
<*> v .: "y"
-- We do not expect a non-Object value here.
-- We could use empty to fail, but typeMismatch
-- gives a much more informative error message.
parseJSON invalid =
prependFailure "parsing Coord failed, "
(typeMismatch "Object" invalid)
For this common case of only being concerned with a single type of JSON value, the functions withObject, withScientific, etc. are provided. Their use is to be preferred when possible, since they are more terse. Using withObject, we can rewrite the above instance (assuming the same language extension and data type) as:
instance FromJSON Coord where
parseJSON = withObject "Coord" $ \v -> Coord
<$> v .: "x"
<*> v .: "y"
Instead of manually writing your FromJSON instance, there are two options to do it automatically:
Data.Aeson.TH provides Template Haskell functions which will derive an instance at compile time. The generated instance is optimized for your type so it will probably be more efficient than the following option.
The compiler can provide a default generic implementation for parseJSON.
To use the second, simply add a deriving Generic clause to your
datatype and declare a FromJSON instance for your datatype without giving
a definition for parseJSON.
For example, the previous example can be simplified to just:
{-# LANGUAGE DeriveGeneric #-}
import GHC.Generics
data Coord = Coord { x :: Double, y :: Double } deriving Generic
instance FromJSON Coord
or using the DerivingVia extension
deriving via Generically Coord instance FromJSON Coord
The default implementation will be equivalent to
parseJSON = genericParseJSON defaultOptions; if you need different
options, you can customize the generic decoding by defining:
customOptions = defaultOptions
{ fieldLabelModifier = map toUpper
}
instance FromJSON Coord where
parseJSON = genericParseJSON customOptions
Methods
parseJSON :: Value -> Parser aparseJSONList :: Value -> Parser [a]omittedField :: Maybe aDefault value for optional fields. Used by
(.:?=)operator, and Generics and TH deriving withallowOmittedFields = True(default).
Instances119FromJSON, …
FromJSON KeyDefined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON DotNetTimeDefined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON ValueDefined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON IntSetDefined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON IntegerDefined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONThis instance includes a bounds check to prevent maliciously large inputs to fill up the memory of the target system. You can newtype Scientific and provide your own instance using withScientific if you want to allow larger inputs.
FromJSON NaturalDefined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON VoidDefined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON AllDefined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON AnyDefined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON VersionDefined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON CTimeDefined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON Int16Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON Int32Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON Int64Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON Int8Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON Word16Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON Word32Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON Word64Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON Word8Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON BoolDefined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON CharDefined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON DoubleDefined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON FloatDefined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON IntDefined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON OrderingDefined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON WordDefined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON URIDefined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON PersistValueDefined in persistent-2.14.6.3 · Database.Persist.PersistValueFromJSON ScientificDefined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON TextDefined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON TextDefined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON ShortTextDefined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON CalendarDiffDaysDefined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON DayDefined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON MonthDefined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON QuarterDefined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON QuarterOfYearDefined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON DayOfWeekDefined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON DiffTimeDefined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONThis instance includes a bounds check to prevent maliciously large inputs to fill up the memory of the target system. You can newtype Scientific and provide your own instance using withScientific if you want to allow larger inputs.
FromJSON NominalDiffTimeDefined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONThis instance includes a bounds check to prevent maliciously large inputs to fill up the memory of the target system. You can newtype Scientific and provide your own instance using withScientific if you want to allow larger inputs.
FromJSON SystemTimeDefined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON UTCTimeDefined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON CalendarDiffTimeDefined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON LocalTimeDefined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON TimeOfDayDefined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON ZonedTimeDefined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONSupported string formats:
YYYY-MM-DD HH:MMZYYYY-MM-DD HH:MM:SSZYYYY-MM-DD HH:MM:SS.SSSZThe first space may instead be a
T, and the second space is optional. TheZrepresents UTC. TheZmay be replaced with a time zone offset of the form+0000or-08:00, where the first two digits are hours, the:is optional and the second two digits (also optional) are minutes.FromJSON UUIDDefined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON TextareaDefined in yesod-form-1.7.9 · Yesod.Form.FieldsFromJSON ()Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON (BackendKey SqlReadBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanFromJSON (BackendKey SqlWriteBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanFromJSON (BackendKey SqlBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanFromJSON a => FromJSON (First a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON a => FromJSON (Last a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON a => FromJSON (Max a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON a => FromJSON (Min a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON a => FromJSON (WrappedMonoid a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON a => FromJSON (IntMap a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON a => FromJSON (Seq a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON a => FromJSON (DNonEmpty a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON a => FromJSON (DList a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON a => FromJSON (NonEmpty a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON a => FromJSON (Identity a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON a => FromJSON (First a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON a => FromJSON (Last a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON a => FromJSON (Down a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON a => FromJSON (Dual a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON a => FromJSON (Product a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON a => FromJSON (Sum a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON a => FromJSON (Maybe a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON a => FromJSON (Array a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON a => FromJSON (SmallArray a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON a => FromJSON (Maybe a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON a => FromJSON (Vector a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON a => FromJSON (a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON a => FromJSON [a]Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON v => FromJSON (KeyMap v)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON v => FromJSON (Tree v)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON1 f => FromJSON (Fix f)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSON(FromJSON a, Integral a) => FromJSON (Ratio a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSON(FromJSON1 f, Functor f) => FromJSON (Mu f)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSON(FromJSON1 f, Functor f) => FromJSON (Nu f)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSON(Storable a, FromJSON a) => FromJSON (Vector a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSON(Generic a, GFromJSON Zero (Rep a)) => FromJSON (Generically a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSON(Eq a, Hashable a, FromJSON a) => FromJSON (HashSet a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSON(Ord a, FromJSON a) => FromJSON (Set a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSON(BackendCompatible b s, FromJSON (BackendKey b)) => FromJSON (BackendKey (Compatible b s))Defined in persistent-2.14.6.3 · Database.Persist.Compatible.Types(Prim a, FromJSON a) => FromJSON (PrimArray a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSON(Prim a, FromJSON a) => FromJSON (Vector a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSON(Vector Vector a, FromJSON a) => FromJSON (Vector a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON (Proxy a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONHasResolution a => FromJSON (Fixed a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONThis instance includes a bounds check to prevent maliciously large inputs to fill up the memory of the target system. You can newtype Scientific and provide your own instance using withScientific if you want to allow larger inputs.
(FromJSON a, FromJSON b) => FromJSON (Either a b)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSON(FromJSON a, FromJSON b) => FromJSON (Either a b)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSON(FromJSON a, FromJSON b) => FromJSON (These a b)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSON(FromJSON a, FromJSON b) => FromJSON (Pair a b)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSON(FromJSON a, FromJSON b) => FromJSON (These a b)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSON(FromJSON a, FromJSON b) => FromJSON (a, b)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSON(FromJSON v, FromJSONKey k, Eq k, Hashable k) => FromJSON (HashMap k v)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSON(FromJSONKey k, Ord k, FromJSON v) => FromJSON (Map k v)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON a => FromJSON (Const a b)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSONFromJSON b => FromJSON (Tagged a b)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSON(FromJSON a, FromJSON b, FromJSON c) => FromJSON (a, b, c)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSON(FromJSON1 f, FromJSON1 g, FromJSON a) => FromJSON (These1 f g a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSON(FromJSON a, FromJSON b, FromJSON c, FromJSON d) => FromJSON (a, b, c, d)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSON(FromJSON1 f, FromJSON1 g, FromJSON a) => FromJSON (Product f g a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSON(FromJSON1 f, FromJSON1 g, FromJSON a) => FromJSON (Sum f g a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSON(FromJSON a, FromJSON b, FromJSON c, FromJSON d, FromJSON e) => FromJSON (a, b, c, d, e)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSON(FromJSON1 f, FromJSON1 g, FromJSON a) => FromJSON (Compose f g a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSON(FromJSON a, FromJSON b, FromJSON c, FromJSON d, FromJSON e, FromJSON f) => FromJSON (a, b, c, d, e, f)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSON(FromJSON a, FromJSON b, FromJSON c, FromJSON d, FromJSON e, FromJSON f, FromJSON g) => FromJSON (a, b, c, d, e, f, g)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSON(FromJSON a, FromJSON b, FromJSON c, FromJSON d, FromJSON e, FromJSON f, FromJSON g, FromJSON h) => FromJSON (a, b, c, d, e, f, g, h)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSON(FromJSON a, FromJSON b, FromJSON c, FromJSON d, FromJSON e, FromJSON f, FromJSON g, FromJSON h, FromJSON i) => FromJSON (a, b, c, d, e, f, g, h, i)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSON(FromJSON a, FromJSON b, FromJSON c, FromJSON d, FromJSON e, FromJSON f, FromJSON g, FromJSON h, FromJSON i, FromJSON j) => FromJSON (a, b, c, d, e, f, g, h, i, j)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSON(FromJSON a, FromJSON b, FromJSON c, FromJSON d, FromJSON e, FromJSON f, FromJSON g, FromJSON h, FromJSON i, FromJSON j, FromJSON k) => FromJSON (a, b, c, d, e, f, g, h, i, j, k)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSON(FromJSON a, FromJSON b, FromJSON c, FromJSON d, FromJSON e, FromJSON f, FromJSON g, FromJSON h, FromJSON i, FromJSON j, FromJSON k, FromJSON l) => FromJSON (a, b, c, d, e, f, g, h, i, j, k, l)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSON(FromJSON a, FromJSON b, FromJSON c, FromJSON d, FromJSON e, FromJSON f, FromJSON g, FromJSON h, FromJSON i, FromJSON j, FromJSON k, FromJSON l, FromJSON m) => FromJSON (a, b, c, d, e, f, g, h, i, j, k, l, m)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSON(FromJSON a, FromJSON b, FromJSON c, FromJSON d, FromJSON e, FromJSON f, FromJSON g, FromJSON h, FromJSON i, FromJSON j, FromJSON k, FromJSON l, FromJSON m, FromJSON n) => FromJSON (a, b, c, d, e, f, g, h, i, j, k, l, m, n)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSON(FromJSON a, FromJSON b, FromJSON c, FromJSON d, FromJSON e, FromJSON f, FromJSON g, FromJSON h, FromJSON i, FromJSON j, FromJSON k, FromJSON l, FromJSON m, FromJSON n, FromJSON o) => FromJSON (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o)Defined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSON
A generic handler monad, which can have a different subsite and master site. We define a newtype for better error message.
Instances15Monad, Functor, Applicative, MonadIO, MonadThrow, PrimMonad, …
Monad (HandlerFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesFunctor (HandlerFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesApplicative (HandlerFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesMonadIO (HandlerFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesMonadThrow (HandlerFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesPrimMonad (HandlerFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesMonadUnliftIO (HandlerFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesMonadResource (HandlerFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesMonadLogger (HandlerFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesMonadLoggerIO (HandlerFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesMonadHandler (HandlerFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.Class.HandlerMonadReader (HandlerData site site) (HandlerFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.Typestype PrimState (HandlerFor site) = PrimState IODefined in yesod-core-1.6.26.0 · Yesod.Core.Typestype HandlerSite (HandlerFor site) = siteDefined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handlertype SubHandlerSite (HandlerFor site) = siteDefined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handler
Monads in which IO computations may be embedded. Any monad built by applying a sequence of monad transformers to the IO monad will be an instance of this class.
Instances should satisfy the following laws, which state that liftIO is a transformer of monads:
Methods
liftIO :: IO a -> m aLift a computation from the IO monad. This allows us to run IO computations in any monadic stack, so long as it supports these kinds of operations (i.e. IO is the base monad for the stack).
Example
import Control.Monad.Trans.State -- from the "transformers" library printState :: Show s => StateT s IO () printState = do state <- get liftIO $ print stateHad we omitted
liftIO, we would have ended up with this error:• Couldn't match type ‘IO’ with ‘StateT s IO’ Expected type: StateT s IO () Actual type: IO ()The important part here is the mismatch between
StateT s IO ()andIO ().Luckily, we know of a function that takes an
IO aand returns an(m a):liftIO, enabling us to run the program and see the expected results:> evalStateT printState "hello" "hello" > evalStateT printState 3 3
Instances32MonadIO, …
MonadIO IODefined in base-4.20.2.0 · Control.Monad.IO.ClassMonadIO AcquireDefined in resourcet-1.3.0 · Data.Acquire.InternalMonadIO QDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.SyntaxMonadIO (HandlerFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesMonadIO (WidgetFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesMonadIO m => MonadIO (PropertyM m)Defined in QuickCheck-2.15.0.1 · Test.QuickCheck.MonadicMonadIO m => MonadIO (ZeptoT m)Defined in attoparsec-0.14.4 · Data.Attoparsec.ZeptoMonadIO m => MonadIO (CatchT m)Defined in exceptions-0.10.9 · Control.Monad.Catch.PureMonadIO m => MonadIO (LoggingT m)Defined in monad-logger-0.3.42 · Control.Monad.LoggerMonadIO m => MonadIO (NoLoggingT m)Defined in monad-logger-0.3.42 · Control.Monad.LoggerMonadIO m => MonadIO (WriterLoggingT m)Defined in monad-logger-0.3.42 · Control.Monad.LoggerMonadIO m => MonadIO (ResourceT m)Defined in resourcet-1.3.0 · Control.Monad.Trans.Resource.InternalMonadIO m => MonadIO (MaybeT m)Defined in transformers-0.6.1.1 · Control.Monad.Trans.MaybeMonad m => MonadIO (QuoteToQuasi m)Defined in th-compat-0.1.6 · Language.Haskell.TH.Syntax.CompatMonadIO (SubHandlerFor child master)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesMonadIO m => MonadIO (ExceptT e m)Defined in transformers-0.6.1.1 · Control.Monad.Trans.ExceptMonadIO m => MonadIO (IdentityT m)Defined in transformers-0.6.1.1 · Control.Monad.Trans.IdentityMonadIO m => MonadIO (ReaderT r m)Defined in transformers-0.6.1.1 · Control.Monad.Trans.ReaderMonadIO m => MonadIO (SelectT r m)Defined in transformers-0.6.1.1 · Control.Monad.Trans.SelectMonadIO m => MonadIO (StateT s m)Defined in transformers-0.6.1.1 · Control.Monad.Trans.State.LazyMonadIO m => MonadIO (StateT s m)Defined in transformers-0.6.1.1 · Control.Monad.Trans.State.StrictMonadIO m => MonadIO (WriterT w m)Defined in transformers-0.6.1.1 · Control.Monad.Trans.Writer.CPS(Monoid w, MonadIO m) => MonadIO (WriterT w m)Defined in transformers-0.6.1.1 · Control.Monad.Trans.Writer.Lazy(Monoid w, MonadIO m) => MonadIO (WriterT w m)Defined in transformers-0.6.1.1 · Control.Monad.Trans.Writer.Strict(Monoid w, Functor m, MonadIO m) => MonadIO (AccumT w m)Defined in transformers-0.6.1.1 · Control.Monad.Trans.AccumMonadIO m => MonadIO (ConduitT i o m)Defined in conduit-1.3.6.1 · Data.Conduit.Internal.ConduitMonadIO m => MonadIO (ParsecT s u m)Defined in parsec-3.1.18.0 · Text.Parsec.PrimMonadIO m => MonadIO (ContT r m)Defined in transformers-0.6.1.1 · Control.Monad.Trans.ContMonadIO m => MonadIO (RWST r w s m)Defined in transformers-0.6.1.1 · Control.Monad.Trans.RWS.CPS(Monoid w, MonadIO m) => MonadIO (RWST r w s m)Defined in transformers-0.6.1.1 · Control.Monad.Trans.RWS.Lazy(Monoid w, MonadIO m) => MonadIO (RWST r w s m)Defined in transformers-0.6.1.1 · Control.Monad.Trans.RWS.StrictMonadIO m => MonadIO (Pipe l i o u m)Defined in conduit-1.3.6.1 · Data.Conduit.Internal.Pipe
Retrieve the value associated with the given key of an Object. The result is empty if the key is not present or the value cannot be converted to the desired type.
This accessor is appropriate if the key and value must be present in an object for it to be valid. If the key and value are optional, use .:? instead.
Methods
toWidget :: (MonadWidget m, HandlerSite m ~ site) => a -> m ()
Instances12ToWidget, …
ToWidget site HtmlDefined in yesod-core-1.6.26.0 · Yesod.Core.WidgetToWidget site CssDefined in yesod-core-1.6.26.0 · Yesod.Core.WidgetToWidget site JavascriptDefined in yesod-core-1.6.26.0 · Yesod.Core.WidgetToWidget site TextDefined in yesod-core-1.6.26.0 · Yesod.Core.WidgetToWidget site BuilderDefined in yesod-core-1.6.26.0 · Yesod.Core.WidgetToWidget site TextDefined in yesod-core-1.6.26.0 · Yesod.Core.WidgetToWidget site CssBuilderDefined in yesod-core-1.6.26.0 · Yesod.Core.Widget(site' ~ site, a ~ ()) => ToWidget site' (WidgetFor site a)Defined in yesod-core-1.6.26.0 · Yesod.Core.Widgetrender ~ RY site => ToWidget site (render -> Html)Defined in yesod-core-1.6.26.0 · Yesod.Core.Widgetrender ~ RY site => ToWidget site (render -> Css)Defined in yesod-core-1.6.26.0 · Yesod.Core.Widgetrender ~ RY site => ToWidget site (render -> Javascript)Defined in yesod-core-1.6.26.0 · Yesod.Core.Widgetrender ~ RY site => ToWidget site (render -> CssBuilder)Defined in yesod-core-1.6.26.0 · Yesod.Core.Widget
A type-safe, concise method of creating breadcrumbs for pages. For each resource, you declare the title of the page and the parent resource (if present).
Methods
breadcrumbs :: (YesodBreadcrumbs site, Show (Route site), Eq (Route site)) => HandlerFor site (Text, [(Route site, Text)])Gets the title of the current page and the hierarchy of parent pages, along with their respective titles.
This class is automatically instantiated when you use the template haskell mkYesod function. You should never need to deal with it directly.
Methods
yesodDispatch :: YesodRunnerEnv site -> Application
Instances1YesodDispatch
YesodDispatch LiteAppDefined in yesod-core-1.6.26.0 · Yesod.Core.Internal.LiteApp
Methods
yesodSubDispatch :: YesodSubRunnerEnv sub master -> Application
Instances2YesodSubDispatch
YesodSubDispatch WaiSubsite masterDefined in yesod-core-1.6.26.0 · Yesod.Core.Class.DispatchYesodSubDispatch WaiSubsiteWithAuth masterDefined in yesod-core-1.6.26.0 · Yesod.Core.Class.Dispatch
Instances15HandlerSite, …
type HandlerSite (ConduitM i o m) = HandlerSite mDefined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handlertype HandlerSite (Pipe l i o u m) = HandlerSite mDefined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handlertype HandlerSite (ExceptT e m) = HandlerSite mDefined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handlertype HandlerSite (IdentityT m) = HandlerSite mDefined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handlertype HandlerSite (MaybeT m) = HandlerSite mDefined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handlertype HandlerSite (RWST r w s m) = HandlerSite mDefined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handlertype HandlerSite (RWST r w s m) = HandlerSite mDefined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handlertype HandlerSite (ReaderT r m) = HandlerSite mDefined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handlertype HandlerSite (StateT s m) = HandlerSite mDefined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handlertype HandlerSite (StateT s m) = HandlerSite mDefined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handlertype HandlerSite (WriterT w m) = HandlerSite mDefined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handlertype HandlerSite (WriterT w m) = HandlerSite mDefined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handlertype HandlerSite (HandlerFor site) = siteDefined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handlertype HandlerSite (SubHandlerFor sub master) = masterDefined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handlertype HandlerSite (WidgetFor site) = siteDefined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handler
Methods
liftWidget :: WidgetFor (HandlerSite m) a -> m a
Instances13MonadWidget, …
MonadWidget (WidgetFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.Class.HandlerMonadWidget m => MonadWidget (MaybeT m)Defined in yesod-core-1.6.26.0 · Yesod.Core.Class.HandlerMonadWidget m => MonadWidget (ExceptT e m)Defined in yesod-core-1.6.26.0 · Yesod.Core.Class.HandlerMonadWidget m => MonadWidget (IdentityT m)Defined in yesod-core-1.6.26.0 · Yesod.Core.Class.HandlerMonadWidget m => MonadWidget (ReaderT r m)Defined in yesod-core-1.6.26.0 · Yesod.Core.Class.HandlerMonadWidget m => MonadWidget (StateT s m)Defined in yesod-core-1.6.26.0 · Yesod.Core.Class.HandlerMonadWidget m => MonadWidget (StateT s m)Defined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handler(Monoid w, MonadWidget m) => MonadWidget (WriterT w m)Defined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handler(Monoid w, MonadWidget m) => MonadWidget (WriterT w m)Defined in yesod-core-1.6.26.0 · Yesod.Core.Class.HandlerMonadWidget m => MonadWidget (ConduitM i o m)Defined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handler(Monoid w, MonadWidget m) => MonadWidget (RWST r w s m)Defined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handler(Monoid w, MonadWidget m) => MonadWidget (RWST r w s m)Defined in yesod-core-1.6.26.0 · Yesod.Core.Class.HandlerMonadWidget m => MonadWidget (Pipe l i o u m)Defined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handler
Instances15SubHandlerSite, …
type SubHandlerSite (ConduitM i o m) = SubHandlerSite mDefined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handlertype SubHandlerSite (Pipe l i o u m) = SubHandlerSite mDefined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handlertype SubHandlerSite (ExceptT e m) = SubHandlerSite mDefined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handlertype SubHandlerSite (IdentityT m) = SubHandlerSite mDefined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handlertype SubHandlerSite (MaybeT m) = SubHandlerSite mDefined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handlertype SubHandlerSite (RWST r w s m) = SubHandlerSite mDefined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handlertype SubHandlerSite (RWST r w s m) = SubHandlerSite mDefined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handlertype SubHandlerSite (ReaderT r m) = SubHandlerSite mDefined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handlertype SubHandlerSite (StateT s m) = SubHandlerSite mDefined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handlertype SubHandlerSite (StateT s m) = SubHandlerSite mDefined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handlertype SubHandlerSite (WriterT w m) = SubHandlerSite mDefined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handlertype SubHandlerSite (WriterT w m) = SubHandlerSite mDefined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handlertype SubHandlerSite (HandlerFor site) = siteDefined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handlertype SubHandlerSite (SubHandlerFor sub master) = subDefined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handlertype SubHandlerSite (WidgetFor site) = siteDefined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handler
Check if a given request is authorized via isAuthorized and isWriteRequest.
Since 1.2.0
csrfCheckMiddleware :: HandlerFor site res-> HandlerFor site BoolWhether or not to perform the CSRF check.
-> CI ByteStringThe header name to lookup the CSRF token from.
-> TextThe POST parameter name to lookup the CSRF token from.
-> HandlerFor site res
Looks up the CSRF token from the request headers or POST parameters. If the value doesn't match the token stored in the session, this function throws a PermissionDenied error.
For details, see the "AJAX CSRF protection" section of Yesod.Core.Handler.
Since 1.4.14
Takes a SetCookie and overrides its value with a CSRF token, then sets the cookie. See setCsrfCookieWithCookie.
For details, see the "AJAX CSRF protection" section of Yesod.Core.Handler.
Make sure to set the setCookiePath to the root path of your application, otherwise you'll generate a new CSRF token for every path of your app. If your app is run from from e.g. www.example.com/app1, use app1. The vast majority of sites will just use /.
Since 1.4.14
Customize the cookies used by the session backend. You may use this function on your definition of makeSessionBackend.
For example, you could set the cookie domain so that it would work across many subdomains:
makeSessionBackend site =
(fmap . fmap) (customizeSessionCookies addDomain) ...
where
addDomain cookie = cookie { setCookieDomain = Just ".example.com" }
Default: Do not customize anything (id).
Calls csrfCheckMiddleware with isWriteRequest, defaultCsrfHeaderName, and defaultCsrfParamName as parameters.
Since 1.4.14
Calls defaultCsrfSetCookieMiddleware and defaultCsrfCheckMiddleware.
For details, see the "AJAX CSRF protection" section of Yesod.Core.Handler.
You can chain this middleware together with other middleware like so:
yesodMiddleware = defaultYesodMiddleware . defaultCsrfMiddleware
or:
yesodMiddleware app = defaultYesodMiddleware $ defaultCsrfMiddleware $ app
Since 1.4.14
Calls csrfSetCookieMiddleware with the defaultCsrfCookieName.
The cookie's path is set to /, making it valid for your whole website.
Since 1.4.14
The default error handler for errorHandler.
Default implementation of makeLogger. Sends to stdout and automatically flushes on each write.
Since 1.4.10
Default implementation of messageLoggerSource. Checks if the message should be logged using the provided function, and if so, formats using formatLogMessage. You can use defaultShouldLogIO as the provided function.
Since 1.4.10
Default implementation of shouldLog. Logs everything at or
above LevelInfo.
Since 1.4.10
Default implementation of yesodMiddleware. Adds the response header "Vary: Accept, Accept-Language", "X-XSS-Protection: 1; mode=block", and performs authorization checks.
Since 1.2.0
Create a SessionBackend which reads the session key from the named
environment variable.
This can be useful if:
You can't rely on a persistent file system (e.g. Heroku)
Your application is open source (e.g. you can't commit the key)
By keeping a consistent value in the environment variable, your users will have consistent sessions without relying on the file system.
Note: A suitable value should only be obtained in one of two ways:
Run this code without the variable set, a value will be generated and printed on
devstdout/Use
clientsession-generate
Since 1.4.5
Default formatting for log messages. When you use
the template haskell logging functions for to log with information
about the source location, that information will be appended to
the end of the log. When you use the non-TH logging functions,
like logDebugN, this function does not include source
information. This currently works by checking to see if the
package name is the string "<unknown>". This is a hack,
but it removes some of the visual clutter from non-TH logs.
Since 1.4.10
Get the textual application root from an Approot value.
Since 1.4.17
Guess the approot based on request headers. For more information, see Network.Wai.Middleware.Approot
In the case of headers being unavailable, it falls back to ApprootRelative
Since 1.4.16
Guess the approot based on request headers, with fall back to the
specified AppRoot.
Since 1.4.16
Helps defend against CSRF attacks by setting the SameSite attribute on session cookies to Lax. With the Lax setting, the cookie will be sent with same-site requests, and with cross-site top-level navigations.
This option is liable to change in future versions of Yesod as the spec evolves. View more information here.
loadClientSession :: Key-> IO ClientSessionDateCache-> ByteStringsession name
-> Request-> IO (SessionMap, SaveSession)
Apply a Strict-Transport-Security header with the specified timeout to all responses so that browsers will rewrite all http links to https until the timeout expires. For security, the max-age of the STS header should always equal or exceed the client sessions timeout. This defends against SSL-stripping man-in-the-middle attacks. It is only effective if a secure connection has already been made; Strict-Transport-Security headers are ignored over HTTP.
Since 1.4.7
Defends against session hijacking by setting the secure bit on session cookies so that browsers will not transmit them over http. With this setting on, it follows that the server will regard requests made over http as sessionless, because the session cookie will not be included in the request. Use this as part of a total security measure which also includes disabling HTTP traffic to the site or issuing redirects from HTTP urls, and composing sslOnlyMiddleware with the site's yesodMiddleware.
Since 1.4.7
Helps defend against CSRF attacks by setting the SameSite attribute on session cookies to Strict. With the Strict setting, the cookie will only be sent with same-site requests.
This option is liable to change in future versions of Yesod as the spec evolves. View more information here.
Convert a widget to a PageContent.
Methods
getContentType :: Monad m => m a -> ContentType
Instances12HasContentType, …
HasContentType EncodingDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentHasContentType ValueDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentHasContentType HtmlDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentHasContentType CssDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentHasContentType JavascriptDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentHasContentType TextDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentHasContentType TextDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentHasContentType RepJsonDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentHasContentType RepPlainDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentHasContentType RepXmlDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentHasContentType (JSONResponse a)Defined in yesod-core-1.6.26.0 · Yesod.Core.ContentHasContentType a => HasContentType (DontFullyEvaluate a)Defined in yesod-core-1.6.26.0 · Yesod.Core.Content
Anything which can be converted into Content. Most of the time, you will want to use the ContentBuilder constructor. An easier approach will be to use a pre-defined toContent function, such as converting your data into a lazy bytestring and then calling toContent on that.
Please note that the built-in instances for lazy data structures (String, lazy ByteString, lazy Text and Html) will not automatically include the content length for the ContentBuilder constructor.
Instances24ToContent, …
ToContent EncodingDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToContent ValueDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToContent HtmlDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToContent BuilderDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToContent ByteStringDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToContent ByteStringDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToContent StringDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToContent VoidDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToContent CssDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToContent JavascriptDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToContent TextDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToContent TextDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToContent ContentDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToContent RepJsonDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToContent RepPlainDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToContent RepXmlDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToContent TypedContentDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToContent ()Defined in yesod-core-1.6.26.0 · Yesod.Core.ContentToContent (JSONResponse a)Defined in yesod-core-1.6.26.0 · Yesod.Core.ContentToContent a => ToContent (DontFullyEvaluate a)Defined in yesod-core-1.6.26.0 · Yesod.Core.ContentToContent (ContentType, Content)Defined in yesod-core-1.6.26.0 · Yesod.Core.ContentToFlushBuilder builder => ToContent (ConduitT () builder (ResourceT IO) ())Defined in yesod-core-1.6.26.0 · Yesod.Core.ContentToFlushBuilder builder => ToContent (SealedConduitT () builder (ResourceT IO) ())Defined in yesod-core-1.6.26.0 · Yesod.Core.ContentToFlushBuilder builder => ToContent (Pipe () () builder () (ResourceT IO) ())Defined in yesod-core-1.6.26.0 · Yesod.Core.Content
A class for all data which can be sent in a streaming response. Note that for textual data, instances must use UTF-8 encoding.
Since 1.2.0
Methods
toFlushBuilder :: a -> Flush Builder
Instances14ToFlushBuilder, …
ToFlushBuilder HtmlDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToFlushBuilder BuilderDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToFlushBuilder ByteStringDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToFlushBuilder ByteStringDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToFlushBuilder StringDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToFlushBuilder TextDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToFlushBuilder TextDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToFlushBuilder (Flush Html)Defined in yesod-core-1.6.26.0 · Yesod.Core.ContentToFlushBuilder (Flush Builder)Defined in yesod-core-1.6.26.0 · Yesod.Core.ContentToFlushBuilder (Flush ByteString)Defined in yesod-core-1.6.26.0 · Yesod.Core.ContentToFlushBuilder (Flush ByteString)Defined in yesod-core-1.6.26.0 · Yesod.Core.ContentToFlushBuilder (Flush String)Defined in yesod-core-1.6.26.0 · Yesod.Core.ContentToFlushBuilder (Flush Text)Defined in yesod-core-1.6.26.0 · Yesod.Core.ContentToFlushBuilder (Flush Text)Defined in yesod-core-1.6.26.0 · Yesod.Core.Content
Any type which can be converted to TypedContent.
Since 1.2.0
Methods
toTypedContent :: a -> TypedContent
Instances17ToTypedContent, …
ToTypedContent EncodingDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToTypedContent ValueDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToTypedContent HtmlDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToTypedContent VoidDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToTypedContent CssDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToTypedContent JavascriptDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToTypedContent TextDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToTypedContent TextDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToTypedContent RepJsonDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToTypedContent RepPlainDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToTypedContent RepXmlDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToTypedContent TypedContentDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToTypedContent ()Defined in yesod-core-1.6.26.0 · Yesod.Core.ContentToTypedContent (JSONResponse a)Defined in yesod-core-1.6.26.0 · Yesod.Core.ContentToTypedContent [Char]Defined in yesod-core-1.6.26.0 · Yesod.Core.ContentToTypedContent a => ToTypedContent (DontFullyEvaluate a)Defined in yesod-core-1.6.26.0 · Yesod.Core.ContentToTypedContent (ContentType, Content)Defined in yesod-core-1.6.26.0 · Yesod.Core.Content
Give just the media types as a pair.
For example, "text/html; charset=utf-8" returns ("text", "html")
Zero-length enumerator.
Removes "extra" information at the end of a content type string. In particular, removes everything after the semicolon, if present.
For example, "text/html; charset=utf-8" is commonly used to specify the character encoding for HTML data. This function would return "text/html".
All of the default middlewares, excluding logging.
Since 1.2.12
Default constructor for yreGetMaxExpires field. Low level function for simple manual construction of YesodRunnerEnv.
A default set of middlewares.
Since 1.2.0
Same as toWaiAppPlain, but provides a default set of middlewares. This set may change with future releases, but currently covers:
Logging
GZIP compression
Automatic HEAD method handling
Request method override with the _method query string parameter
Accept header override with the _accept query string parameter
Convert the given argument into a WAI application, executable with any WAI handler. This function will provide no middlewares; if you want commonly used middlewares, please use toWaiApp.
Pure low level function to construct WAI application. Usefull when you need not standard way to run your app, or want to embed it inside another app.
Deprecated. Please use warp instead
Deprecated synonym for warp.
Runs your application using default middlewares (i.e., via toWaiApp). It reads port information from the PORT environment variable, as used by tools such as Keter and the FP Complete School of Haskell.
Note that the exact behavior of this function may be modified slightly over time to work correctly with external tools, without a change to the type signature.
Add a fragment identifier to a route to be used when redirecting. For example:
redirect (NewsfeedR :#: storyId)@since 1.2.9.
Constructors
a :#: b
Instances2RedirectUrl, Show
(RedirectUrl master a, PathPiece b) => RedirectUrl master (Fragment a b)Defined in yesod-core-1.6.26.0 · Yesod.Core.Handler(Show a, Show b) => Show (Fragment a b)Defined in yesod-core-1.6.26.0 · Yesod.Core.Handler
Deprecated. Use HandlerFor directly
Internal representation of a single provided representation.
Some value which can be turned into a URL for redirects.
Methods
toTextUrl :: (MonadHandler m, HandlerSite m ~ master) => a -> m TextConverts the value to the URL and a list of query-string parameters.
Instances6RedirectUrl
RedirectUrl master StringDefined in yesod-core-1.6.26.0 · Yesod.Core.HandlerRedirectUrl master TextDefined in yesod-core-1.6.26.0 · Yesod.Core.HandlerRedirectUrl master (Route master)Defined in yesod-core-1.6.26.0 · Yesod.Core.Handler(RedirectUrl master a, PathPiece b) => RedirectUrl master (Fragment a b)Defined in yesod-core-1.6.26.0 · Yesod.Core.Handler(key ~ Text, val ~ Text) => RedirectUrl master (Route master, Map key val)Defined in yesod-core-1.6.26.0 · Yesod.Core.Handler(key ~ Text, val ~ Text) => RedirectUrl master (Route master, [(key, val)])Defined in yesod-core-1.6.26.0 · Yesod.Core.Handler
Set an arbitrary response header.
Note that, while the data type used here is Text, you must provide only ASCII value to be HTTP compliant.
Adds a status and message in the user's session.
See getMessages.
Adds a message in the user's session but uses RenderMessage to allow for i18n
See getMessages.
Set an Expires header in the past, meaning this content should not be cached.
Return a 405 method not supported page.
Retrieves a value from the cache used by cachedBy.
Sets a value in the cache used by cachedBy.
Retrieves a value from the cache used by cached.
Set the Cache-Control header to indicate this response should be cached for the given number of seconds.
Sets a value in the cache used by cached.
Use a per-request cache to avoid performing the same action multiple times. Values are stored by their type, the result of typeOf from Typeable. Therefore, you should use different newtype wrappers at each cache site.
For example, yesod-auth uses an un-exported newtype, CachedMaybeAuth and exports functions that utilize it such as maybeAuth. This means that another module can create its own newtype wrapper to cache the same type from a different action without any cache conflicts.
See the original announcement: http://www.yesodweb.com/blog/2013/03/yesod-1-2-cleaner-internals
a per-request cache. just like cached. cached can only cache a single value per type. cachedBy stores multiple values per type by usage of a ByteString key
cached is ideal to cache an action that has only one value of a type, such as the session's current user cachedBy is required if the action has parameters and can return multiple values per type. You can turn those parameters into a ByteString cache key. For example, caching a lookup of a Link by a token where multiple token lookups might be performed.
Takes a header name to lookup a CSRF token. If the value doesn't match the token stored in the session, this function throws a PermissionDenied error.
checkCsrfHeaderOrParam :: (MonadHandler m, MonadLogger m)=> CI ByteStringThe header name to lookup the CSRF token
-> TextThe POST parameter name to lookup the CSRF token
-> m ()
Checks that a valid CSRF token is present in either the request headers or POST parameters. If the value doesn't match the token stored in the session, this function throws a PermissionDenied error.
Takes a POST parameter name to lookup a CSRF token. If the value doesn't match the token stored in the session, this function throws a PermissionDenied error.
Clear all session variables.
@since: 1.0.1
Remove a previously set ultimate destination. See setUltDest.
The default cookie name for the CSRF token ("XSRF-TOKEN").
The default header name for the CSRF token ("X-XSRF-TOKEN").
The default parameter name for the CSRF token ("_token")
Unset the cookie on the client.
Note: although the value used for key and path is Text, you should only use ASCII values to be HTTP compliant.
Unsets a session variable. See setSession.
Set an Expires header to the given date.
Stream the data from the file. Since Yesod 1.2, this has been generalized
to work in any MonadResource.
Extract a strict ByteString body from a FileInfo.
This function will block while reading the file.
do
fileByteString <- fileSourceByteString fileInfoforkHandler :: (SomeException -> HandlerFor site ())error handler
-> HandlerFor site ()-> HandlerFor site ()
forkIO for a Handler (run an action in the background)
Uses handlerToIO, liftResourceT, and resourceForkIO for correctness and efficiency
Get the route requested by the user. If this is a 404 response- where the user requested an invalid route- this function will return Nothing.
Helper function for setCookieExpires value
Gets just the last message in the user's session, discards the rest and the status
getMessageRender :: (MonadHandler m, RenderMessage (HandlerSite m) message) => m (message -> Text)Gets all messages in the user's session, and then clears the variable.
See addMessage.
Get all the post parameters passed to the handler. To also get the submitted files (if any), you have to use runRequestBody instead of this function.
Get all session variables.
Get the URL rendering function.
The URL rendering function with query-string parameters.
Get the master site application argument.
Get a specific component of the master site application argument.
Analogous to the gets function for operating on StateT.
Deprecated. Use withUrlRenderer instead
Deprecated synonym for withUrlRenderer.
Returns a function that runs HandlerFor actions inside IO.
Sometimes you want to run an inner HandlerFor action outside the control flow of an HTTP request (on the outer HandlerFor action). For example, you may want to spawn a new thread:
getFooR :: Handler RepHtml
getFooR = do
runInnerHandler <- handlerToIO
liftIO $ forkIO $ runInnerHandler $ do
Code here runs inside HandlerFor but on a new thread.
This is the inner HandlerFor.
...
Code here runs inside the request's control flow.
This is the outer HandlerFor.
...
Another use case for this function is creating a stream of
server-sent events using HandlerFor actions (see
yesod-eventsource).
Most of the environment from the outer HandlerFor is preserved on the inner HandlerFor, however:
The request body is cleared (otherwise it would be very difficult to prevent huge memory leaks).
The cache is cleared (see cached).
Changes to the response made inside the inner HandlerFor are
ignored (e.g., session variables, cookies, response headers).
This allows the inner HandlerFor to outlive the outer
HandlerFor (e.g., on the forkIO example above, a response
may be sent to the client without killing the new thread).
Takes a header name to lookup a CSRF token, and returns whether the value matches the token stored in the session.
Takes a POST parameter name to lookup a CSRF token, and returns whether the value matches the token stored in the session.
Return a 400 invalid arguments page.
Return a 400 invalid arguments page.
Get the list of supported languages supplied by the user.
Languages are determined based on the following (in descending order of preference):
The _LANG get parameter.
The _LANG user session variable.
The _LANG cookie.
Accept-Language HTTP header.
Yesod will seek the first language from the returned list matched with languages supporting by your application. This language will be used to render i18n templates. If a matching language is not found the default language will be used.
This is handled by parseWaiRequest (not exposed).
NOTE: Before version 1.6.19.0, this function prioritized the session
variable above all other sources.
Lookup basic authentication data from Authorization header of request. Returns user name and password
Lookup bearer authentication datafrom Authorization header of request. Returns bearer token value
Lookup for cookie data.
Lookup for cookie data.
Lookup for POSTed files.
Lookup for POSTed files.
Lookup for GET parameters.
Lookup for GET parameters.
Lookup a request header.
Lookup a request header.
Lookup for POST parameters.
Lookup for session data.
Lookup for session data in binary format.
Set the Expires header to some date in 2037. In other words, this content is never (realistically) expired.
Get a unique identifier.
Return a 401 status code
Return a 404 not found page. Also denotes no handler available.
Send a 304 not modified response immediately. This is a short-circuiting action.
Return a 403 permission denied page.
Return a 403 permission denied page.
Provide a single representation to be used, based on the request of the client. Should be used together with selectRep.
Same as provideRep, but instead of determining the content type from the type of the value itself, you provide the content type separately. This can be a convenience instead of creating newtype wrappers for uncommonly used content types.
provideRepType "application/x-special-format" "This is the content"Stream in the raw request body without any parsing.
Redirect to the given route. HTTP status code 303 for HTTP 1.1 clients and 302 for HTTP 1.0 This is the appropriate choice for a get-following-post technique, which should be the usual use case.
If you want direct control of the final status code, or need a different status code, please use redirectWith.
Redirect to a POST resource.
This is not technically a redirect; instead, it returns an HTML page with a POST form, and some Javascript to automatically submit the form. This can be useful when you need to post a plain link somewhere that needs to cause changes on the server.
redirectUltDest :: (RedirectUrl (HandlerSite m) url, MonadHandler m)=> urldefault destination if nothing in session
-> m a
Redirect to the ultimate destination in the user's session. Clear the value from the session.
The ultimate destination is set with setUltDest.
This function uses redirect, and thus will perform a temporary redirect to a GET request.
Redirect to the given URL with the specified status code.
Replace an existing header with a new value or add a new header if not present.
Note that, while the data type used here is Text, you must provide only ASCII value to be HTTP compliant.
Provide a pure value for the response body.
respond ct = return . TypedContent ct . toContentUse a Source for the response body.
Note that, for ease of use, the underlying monad is a HandlerFor. This
implies that you can run any HandlerFor action. However, since a streaming
response occurs after the response headers have already been sent, some
actions make no sense here. For example: short-circuit responses, setting
headers, changing status codes, etc.
Select a representation to send to the client based on the representations provided inside this do-block. Should be used together with provideRep.
In a streaming response, send a single chunk of data. This function works
on most datatypes, such as ByteString and Html.
Type-specialized version of sendChunk for strict ByteStrings.
Type-specialized version of sendChunk for Htmls.
Type-specialized version of sendChunk for lazy ByteStrings.
Type-specialized version of sendChunk for lazy Texts.
Type-specialized version of sendChunk for strict Texts.
Same as sendFile, but only sends part of a file.
In a streaming response, send a flush command, causing all buffered data to be immediately sent to the client.
Send a raw response. This is used for cases such as WebSockets. Requires WAI 2.1 or later, and a web server which supports raw responses (e.g., Warp).
Send a raw response without conduit. This is used for cases such as WebSockets. Requires WAI 3.0 or later, and a web server which supports raw responses (e.g., Warp).
Bypass remaining handler code and output the given content with a 200 status code.
Send a 201 Created response with the given route as the Location
response header.
Bypass remaining handler code and output no content with a 204 status code.
Bypass remaining handler code and output the given content with the given status code.
Bypass remaining handler code and output the given JSON with the given status code.
Switch over to handling the current request with a WAI Application.
Send a Response. Please note: this function is rarely necessary, and will disregard any changes to response headers and session that you have already specified. This function short-circuits. It should be considered only for very specific needs. If you are not sure if you need it, you don't.
Set the cookie on the client.
Sets a cookie with a CSRF token, using defaultCsrfCookieName for the cookie name.
The cookie's path is set to /, making it valid for your whole website.
Takes a SetCookie and overrides its value with a CSRF token, then sets the cookie.
Make sure to set the setCookiePath to the root path of your application, otherwise you'll generate a new CSRF token for every path of your app. If your app is run from from e.g. www.example.com/app1, use app1. The vast majority of sites will just use /.
Check the if-none-match header and, if it matches the given value, return a 304 not modified response. Otherwise, set the etag header to the given value.
Note that it is the responsibility of the caller to ensure that the provided value is a valid etag value, no sanity checking is performed by this function.
Deprecated. Please use addHeader instead
Deprecated synonym for addHeader.
Set the language in the user session. Will show up in languages on the next request.
Calls addMessage with an empty status
Calls addMessageI with an empty status
Set a variable in the user's session.
The session is handled by the clientsession package: it sets an encrypted and hashed cookie on the client. This ensures that all data is secure and not tampered with.
Same as setSession, but uses binary data for the value.
Sets the ultimate destination variable to the given route.
An ultimate destination is stored in the user session and can be loaded later by redirectUltDest.
Same as setUltDest, but uses the current page.
If this is a 404 handler, there is no current page, and then this call does nothing.
Sets the ultimate destination to the referer request header, if present.
This function will not overwrite an existing ultdest.
Check the if-none-match header and, if it matches the given value, return a 304 not modified response. Otherwise, set the etag header to the given value.
A weak etag is only expected to be semantically identical to the prior content, but doesn't have to be byte-for-byte identical. Therefore it can be useful for dynamically generated content that may be difficult to perform bytewise hashing upon.
Note that it is the responsibility of the caller to ensure that the provided value is a valid etag value, no sanity checking is performed by this function.
Get the request's Request value.
Provide a URL rendering function to the given function and return the result. Useful for processing Shakespearean templates.
Constructors
LiteAppunLiteApp :: Method -> [Text] -> Maybe (LiteHandler TypedContent)
Instances11Semigroup, Monoid, YesodDispatch, Yesod, ParseRoute, RenderRoute, …
Semigroup LiteAppDefined in yesod-core-1.6.26.0 · Yesod.Core.Internal.LiteAppMonoid LiteAppDefined in yesod-core-1.6.26.0 · Yesod.Core.Internal.LiteAppYesodDispatch LiteAppDefined in yesod-core-1.6.26.0 · Yesod.Core.Internal.LiteAppYesod LiteAppDefined in yesod-core-1.6.26.0 · Yesod.Core.Internal.LiteAppParseRoute LiteAppDefined in yesod-core-1.6.26.0 · Yesod.Core.Internal.LiteAppRenderRoute LiteAppDefined in yesod-core-1.6.26.0 · Yesod.Core.Internal.LiteAppEq (Route LiteApp)Defined in yesod-core-1.6.26.0 · Yesod.Core.Internal.LiteAppOrd (Route LiteApp)Defined in yesod-core-1.6.26.0 · Yesod.Core.Internal.LiteAppRead (Route LiteApp)Defined in yesod-core-1.6.26.0 · Yesod.Core.Internal.LiteAppShow (Route LiteApp)Defined in yesod-core-1.6.26.0 · Yesod.Core.Internal.LiteAppdata Route LiteAppDefined in yesod-core-1.6.26.0 · Yesod.Core.Internal.LiteApp
Deprecated. import runFakeHandler from Yesod.Core.Unsafe
yesodRender clientSessionDateCacher :: NominalDiffTimeInactive session validity.
-> IO (IO ClientSessionDateCache, IO ())
Generates URL datatype and site function for the given Resources. This is used for creating sites, not subsites. See mkYesodSubData and mkYesodSubDispatch for the latter. Use parseRoutes to create the Resources.
Contexts and type variables in the name of the datatype are parsed.
For example, a datatype App a with typeclass constraint MyClass a can be written as "(MyClass a) => App a".
Sometimes, you will want to declare your routes in one file and define your handlers elsewhere. For example, this is the only way to break up a monolithic file into smaller parts. Use this function, paired with mkYesodDispatch, to do just that.
mkYesodData but with custom options.
See mkYesodData.
See mkYesodDataOpts
mkYesod but with custom options.
mkYesodWith Deprecated. Contexts and type variables are now parsed from the name in mkYesod. https://github.com/yesodweb/yesod/pull/1366
Similar to mkYesod, except contexts and type variables are not parsed.
Instead, they are explicitly provided.
You can write (MyClass a) => App a with mkYesodWith [["MyClass","a"]] "App" ["a"] ....
Format as per RFC 1123.
Format as per RFC 822.
Format a UTCTime in W3 format.
Returns True if the client prefers application/json as
indicated by the Accept HTTP header.
Given the Content-Type header, returns if it is JSON.
This function is currently a simple check for application/json, but in the future may check for
alternative representations such as xxx/yyy+json.
defaultLayoutJson :: (Yesod site, ToJSON a)=> WidgetFor site ()HTML
-> HandlerFor site aJSON
-> HandlerFor site TypedContent
Provide both an HTML and JSON representation for a piece of data, using the default layout for the HTML output (defaultLayout).
jsonEncodingOrRedirect :: (MonadHandler m, ToJSON a)=> Route (HandlerSite m)Redirect target
-> aData to send via JSON
-> m Encoding
jsonEncodingOrRedirect simplifies the scenario where a POST handler sends a different response based on Accept headers:
200 with JSON data if the client prefers
application/json(e.g. AJAX, seeacceptsJSON).3xx otherwise, following the PRG pattern. @since 1.4.21
jsonOrRedirect :: (MonadHandler m, ToJSON a)=> Route (HandlerSite m)Redirect target
-> aData to send via JSON
-> m Value
jsonOrRedirect simplifies the scenario where a POST handler sends a different response based on Accept headers:
200 with JSON data if the client prefers
application/json(e.g. AJAX, seeacceptsJSON).3xx otherwise, following the PRG pattern.
Deprecated. Use returnJson instead
Wraps a data type in a RepJson. The data type must
support conversion to JSON via ToJSON.
Parse the request body to a data type as a JSON value. The
data type must support conversion from JSON via FromJSON.
If you want the raw JSON value, just ask for a Result
Value.
The MIME type must indicate JSON content. Requiring a JSON content-type helps secure your site against CSRF attacks (browsers will perform POST requests for form and text/plain content-types without doing a CORS check, and those content-types can easily contain valid JSON).
Note that this function will consume the request body. As such, calling it twice will result in a parse error on the second call, since the request body will no longer be available.
Same as parseCheckJsonBody, but does not check that the mime type indicates JSON content.
Note: This function is vulnerable to CSRF attacks.
Deprecated. Use parseCheckJsonBody or parseInsecureJsonBody instead
Same as parseInsecureJsonBody
Deprecated. Use requireCheckJsonBody or requireInsecureJsonBody instead
Same as parseInsecureJsonBody, but return an invalid args response on a parse error.
Provide a JSON representation for usage with selectReps, using aeson's
toJSON (aeson >= 0.11: toEncoding) function to perform the conversion.
Same as parseCheckJsonBody, but return an invalid args response on a parse error.
Same as parseInsecureJsonBody, but return an invalid args response on a parse error.
Deprecated. Use requireCheckJsonBody or requireInsecureJsonBody instead
Same as parseInsecureJsonBody, but return an invalid args response on a parse error.
Convert a value to a JSON representation via aeson's toJSON function.
Convert a value to a JSON representation via aeson's toEncoding function.
Headers to be added to a Result.
Constructors
AddCookie !SetCookieDeleteCookie !ByteString !ByteStringname and path
Header !(CI ByteString) !ByteStringkey and value
How to determine the root of the application for constructing URLs.
Note that future versions of Yesod may add new constructors without bumping
the major version number. As a result, you should not pattern match on
Approot values.
Constructors
ApprootRelativeNo application root.
ApprootStatic !TextApprootMaster !(master -> Text)ApprootRequest !(master -> Request -> Text)
Constructors
Instances3Eq, Read, Show
Eq AuthResultDefined in yesod-core-1.6.26.0 · Yesod.Core.TypesRead AuthResultDefined in yesod-core-1.6.26.0 · Yesod.Core.TypesShow AuthResultDefined in yesod-core-1.6.26.0 · Yesod.Core.Types
Responses to indicate some form of an error occurred.
Constructors
NotFoundThe requested resource was not found. Examples of when this occurs include when an incorrect URL is used, or
yesod-persistent'sget404doesn't find a value. HTTP status: 404.InternalError !TextSome sort of unexpected exception. If your application uses
throwIOor error to throw an exception, this is the form it would take. HTTP status: 500.InvalidArgs ![Text]Indicates some sort of invalid or missing argument, like a missing query parameter or malformed JSON body. Examples Yesod functions that send this include
requireCheckJsonBodyandYesod.Auth.GoogleEmail2. HTTP status: 400.NotAuthenticatedIndicates the user is not logged in. This is thrown when
isAuthorizedreturns AuthenticationRequired. HTTP code: 401.PermissionDenied !TextIndicates the user doesn't have permission to access the requested resource. This is thrown when
isAuthorizedreturns Unauthorized. HTTP code: 403.BadMethod !MethodIndicates the URL would have been valid if used with a different HTTP method (e.g. a GET was used, but only POST is handled.) HTTP code: 405.
Instances5Eq, Show, Generic, NFData, Rep
Eq ErrorResponseDefined in yesod-core-1.6.26.0 · Yesod.Core.TypesShow ErrorResponseDefined in yesod-core-1.6.26.0 · Yesod.Core.TypesGeneric ErrorResponseDefined in yesod-core-1.6.26.0 · Yesod.Core.TypesNFData ErrorResponseDefined in yesod-core-1.6.26.0 · Yesod.Core.Typestype Rep ErrorResponse = D1 ('MetaDataDefined in yesod-core-1.6.26.0 · Yesod.Core.Types"ErrorResponse"
"Yesod.Core.Types"
"yesod-core-1.6.26.0-AIDJV1wG4aNEjKoKb2CmY"
'False) ((C1 ('MetaCons"NotFound"
'PrefixI 'False) U1 :+: (C1 ('MetaCons"InternalError"
'PrefixI 'False) (S1 ('MetaSel 'Nothing 'NoSourceUnpackedness 'SourceStrict 'DecidedStrict) (Rec0 Text)) :+: C1 ('MetaCons"InvalidArgs"
'PrefixI 'False) (S1 ('MetaSel 'Nothing 'NoSourceUnpackedness 'SourceStrict 'DecidedStrict) (Rec0 [Text])))) :+: (C1 ('MetaCons"NotAuthenticated"
'PrefixI 'False) U1 :+: (C1 ('MetaCons"PermissionDenied"
'PrefixI 'False) (S1 ('MetaSel 'Nothing 'NoSourceUnpackedness 'SourceStrict 'DecidedStrict) (Rec0 Text)) :+: C1 ('MetaCons"BadMethod"
'PrefixI 'False) (S1 ('MetaSel 'Nothing 'NoSourceUnpackedness 'SourceStrict 'DecidedStrict) (Rec0 Method)))))
Constructors
Constructors
ContentBuilder !Builder !(Maybe Int)The content and optional content length.
ContentSource !(ConduitT () (Flush Builder) (ResourceT IO) ())ContentFile !FilePath !(Maybe FilePart)ContentDontEvaluate !Content
Instances4IsString, ToContent, ToTypedContent
IsString ContentDefined in yesod-core-1.6.26.0 · Yesod.Core.TypesToContent ContentDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToContent (ContentType, Content)Defined in yesod-core-1.6.26.0 · Yesod.Core.ContentToTypedContent (ContentType, Content)Defined in yesod-core-1.6.26.0 · Yesod.Core.Content
Newtype wrapper allowing injection of arbitrary content into CSS.
Usage:
toWidget $ CssBuilder "p { color: red }"Since: 1.1.3
Constructors
Instances6ToWidget, ToWidgetHead, ToWidgetMedia
ToWidget site CssBuilderDefined in yesod-core-1.6.26.0 · Yesod.Core.WidgetToWidgetHead site CssBuilderDefined in yesod-core-1.6.26.0 · Yesod.Core.WidgetToWidgetMedia site CssBuilderDefined in yesod-core-1.6.26.0 · Yesod.Core.Widgetrender ~ RY site => ToWidget site (render -> CssBuilder)Defined in yesod-core-1.6.26.0 · Yesod.Core.Widgetrender ~ RY site => ToWidgetHead site (render -> CssBuilder)Defined in yesod-core-1.6.26.0 · Yesod.Core.Widgetrender ~ RY site => ToWidgetMedia site (render -> CssBuilder)Defined in yesod-core-1.6.26.0 · Yesod.Core.Widget
Prevents a response body from being fully evaluated before sending the request.
Since 1.1.0
Constructors
Instances3HasContentType, ToContent, ToTypedContent
HasContentType a => HasContentType (DontFullyEvaluate a)Defined in yesod-core-1.6.26.0 · Yesod.Core.ContentToContent a => ToContent (DontFullyEvaluate a)Defined in yesod-core-1.6.26.0 · Yesod.Core.ContentToTypedContent a => ToTypedContent (DontFullyEvaluate a)Defined in yesod-core-1.6.26.0 · Yesod.Core.Content
Constructors
FileUploadMemory !(BackEnd ByteString)FileUploadDisk !(InternalState -> BackEnd FilePath)FileUploadSource !(BackEnd (ConduitT () ByteString (ResourceT IO) ()))
Content for a web page. By providing this datatype, we can easily create generic site templates, which would have the type signature:
PageContent url -> HtmlUrl urlConstructors
Deprecated. Please use Html instead
Instances3HasContentType, ToContent, ToTypedContent
HasContentType RepJsonDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToContent RepJsonDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToTypedContent RepJsonDefined in yesod-core-1.6.26.0 · Yesod.Core.Content
Instances3HasContentType, ToContent, ToTypedContent
HasContentType RepPlainDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToContent RepPlainDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToTypedContent RepPlainDefined in yesod-core-1.6.26.0 · Yesod.Core.Content
Instances3HasContentType, ToContent, ToTypedContent
HasContentType RepXmlDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToContent RepXmlDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToTypedContent RepXmlDefined in yesod-core-1.6.26.0 · Yesod.Core.Content
A tuple containing both the POST parameters and submitted files.
Constructors
SessionBackendsbLoadSession :: Request -> IO (SessionMap, SaveSession)Return the session data and a function to save the session
A handler monad for subsite
Instances13Monad, Functor, Applicative, MonadIO, MonadThrow, MonadUnliftIO, …
Monad (SubHandlerFor child master)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesFunctor (SubHandlerFor sub master)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesApplicative (SubHandlerFor child master)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesMonadIO (SubHandlerFor child master)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesMonadThrow (SubHandlerFor child master)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesMonadUnliftIO (SubHandlerFor child master)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesMonadResource (SubHandlerFor child master)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesMonadLogger (SubHandlerFor child master)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesMonadLoggerIO (SubHandlerFor child master)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesMonadHandler (SubHandlerFor sub master)Defined in yesod-core-1.6.26.0 · Yesod.Core.Class.HandlerMonadReader (HandlerData child master) (SubHandlerFor child master)Defined in yesod-core-1.6.26.0 · Yesod.Core.Typestype HandlerSite (SubHandlerFor sub master) = masterDefined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handlertype SubHandlerSite (SubHandlerFor sub master) = subDefined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handler
Constructors
Instances2ToContent, ToTypedContent
ToContent TypedContentDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToTypedContent TypedContentDefined in yesod-core-1.6.26.0 · Yesod.Core.Content
Wrap up a normal WAI application as a Yesod subsite. Ignore parent site's middleware and isAuthorized.
Constructors
Instances8ParseRoute, RenderRoute, YesodSubDispatch, Eq, Ord, Read, …
ParseRoute WaiSubsiteDefined in yesod-core-1.6.26.0 · Yesod.Core.TypesRenderRoute WaiSubsiteDefined in yesod-core-1.6.26.0 · Yesod.Core.TypesYesodSubDispatch WaiSubsite masterDefined in yesod-core-1.6.26.0 · Yesod.Core.Class.DispatchEq (Route WaiSubsite)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesOrd (Route WaiSubsite)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesRead (Route WaiSubsite)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesShow (Route WaiSubsite)Defined in yesod-core-1.6.26.0 · Yesod.Core.Typesdata Route WaiSubsiteDefined in yesod-core-1.6.26.0 · Yesod.Core.Types
Like WaiSubsite, but applies parent site's middleware and isAuthorized.
Constructors
Instances8ParseRoute, RenderRoute, YesodSubDispatch, Eq, Ord, Read, …
ParseRoute WaiSubsiteWithAuthDefined in yesod-core-1.6.26.0 · Yesod.Core.TypesRenderRoute WaiSubsiteWithAuthDefined in yesod-core-1.6.26.0 · Yesod.Core.TypesYesodSubDispatch WaiSubsiteWithAuth masterDefined in yesod-core-1.6.26.0 · Yesod.Core.Class.DispatchEq (Route WaiSubsiteWithAuth)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesOrd (Route WaiSubsiteWithAuth)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesRead (Route WaiSubsiteWithAuth)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesShow (Route WaiSubsiteWithAuth)Defined in yesod-core-1.6.26.0 · Yesod.Core.Typesdata Route WaiSubsiteWithAuthDefined in yesod-core-1.6.26.0 · Yesod.Core.Types
A generic widget, allowing specification of both the subsite and master
site datatypes. While this is simply a WriterT, we define a newtype for
better error messages.
Instances20ToWidget, Monad, Functor, Applicative, MonadIO, MonadThrow, …
(site' ~ site, a ~ ()) => ToWidget site' (WidgetFor site a)Defined in yesod-core-1.6.26.0 · Yesod.Core.WidgetMonad (WidgetFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesFunctor (WidgetFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesApplicative (WidgetFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesMonadIO (WidgetFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesMonadThrow (WidgetFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesPrimMonad (WidgetFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesMonadUnliftIO (WidgetFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesMonadResource (WidgetFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesMonadLogger (WidgetFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesMonadLoggerIO (WidgetFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesMonadHandler (WidgetFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.Class.HandlerMonadWidget (WidgetFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.Class.HandlerMonadReader (WidgetData site) (WidgetFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.Typesa ~ () => IsString (WidgetFor site a)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesA String can be trivially promoted to a widget.
For example, in a yesod-scaffold site you could use:
getHomeR = do defaultLayout "Widget text"a ~ () => Semigroup (WidgetFor site a)Defined in yesod-core-1.6.26.0 · Yesod.Core.Typesa ~ () => Monoid (WidgetFor site a)Defined in yesod-core-1.6.26.0 · Yesod.Core.Typestype PrimState (WidgetFor site) = PrimState IODefined in yesod-core-1.6.26.0 · Yesod.Core.Typestype HandlerSite (WidgetFor site) = siteDefined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handlertype SubHandlerSite (WidgetFor site) = siteDefined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handler
The parsed request information. This type augments the standard WAI Request with additional information.
Constructors
YesodRequestreqGetParams :: ![(Text, Text)]Same as queryString, but decoded to
Text.reqCookies :: ![(Text, Text)]reqWaiRequest :: !RequestreqLangs :: ![Text]Languages which the client supports. This is an ordered list by preference.
reqToken :: !Maybe TextA random, session-specific token used to prevent CSRF attacks.
reqSession :: !SessionMapInitial session sent from the client.
Since 1.2.0
reqAccept :: ![ContentType]An ordered list of the accepted content types.
Since 1.2.0
Methods
toWidgetBody :: (MonadWidget m, HandlerSite m ~ site) => a -> m ()
Instances4ToWidgetBody
ToWidgetBody site HtmlDefined in yesod-core-1.6.26.0 · Yesod.Core.WidgetToWidgetBody site JavascriptDefined in yesod-core-1.6.26.0 · Yesod.Core.Widgetrender ~ RY site => ToWidgetBody site (render -> Html)Defined in yesod-core-1.6.26.0 · Yesod.Core.Widgetrender ~ RY site => ToWidgetBody site (render -> Javascript)Defined in yesod-core-1.6.26.0 · Yesod.Core.Widget
Methods
toWidgetHead :: (MonadWidget m, HandlerSite m ~ site) => a -> m ()
Instances8ToWidgetHead, …
ToWidgetHead site HtmlDefined in yesod-core-1.6.26.0 · Yesod.Core.WidgetToWidgetHead site CssDefined in yesod-core-1.6.26.0 · Yesod.Core.WidgetToWidgetHead site JavascriptDefined in yesod-core-1.6.26.0 · Yesod.Core.WidgetToWidgetHead site CssBuilderDefined in yesod-core-1.6.26.0 · Yesod.Core.Widgetrender ~ RY site => ToWidgetHead site (render -> Html)Defined in yesod-core-1.6.26.0 · Yesod.Core.Widgetrender ~ RY site => ToWidgetHead site (render -> Css)Defined in yesod-core-1.6.26.0 · Yesod.Core.Widgetrender ~ RY site => ToWidgetHead site (render -> Javascript)Defined in yesod-core-1.6.26.0 · Yesod.Core.Widgetrender ~ RY site => ToWidgetHead site (render -> CssBuilder)Defined in yesod-core-1.6.26.0 · Yesod.Core.Widget
Allows adding some CSS to the page with a specific media type.
Since 1.2
Methods
toWidgetMedia :: (MonadWidget m, HandlerSite m ~ site) => Text -> a -> m ()Add the given content to the page, but only for the given media type.
Since 1.2
Instances4ToWidgetMedia
ToWidgetMedia site CssDefined in yesod-core-1.6.26.0 · Yesod.Core.WidgetToWidgetMedia site CssBuilderDefined in yesod-core-1.6.26.0 · Yesod.Core.Widgetrender ~ RY site => ToWidgetMedia site (render -> Css)Defined in yesod-core-1.6.26.0 · Yesod.Core.Widgetrender ~ RY site => ToWidgetMedia site (render -> CssBuilder)Defined in yesod-core-1.6.26.0 · Yesod.Core.Widget
Deprecated. Use WidgetFor directly
Link to the specified local script.
Link to the specified local script.
Link to the specified remote script.
Link to the specified remote script.
Link to the specified local stylesheet.
Link to the specified local stylesheet.
Link to the specified remote stylesheet.
Link to the specified remote stylesheet.
setDescription is not idempotent; we recommend setDescriptionIdemp instead Multiple calls to setDescription will insert multiple meta tags in the page head. If you want an idempotent function, use setDescriptionIdemp - but if you do, you may need to change your layout to include pageDescription.
Add description meta tag to the head of the page
Google does not use the description tag as a ranking signal, but the contents of this tag will likely affect your click-through rate since it shows up in search results.
The average length of the description shown in Google's search results is about 160 characters on desktop, and about 130 characters on mobile, at time of writing.
Source: https://www.advancedwebranking.com/blog/meta-tags-important-in-seo/
setDescriptionI is not idempotent; we recommend setDescriptionIdempI instead Multiple calls to setDescriptionI will insert multiple meta tags in the page head. If you want an idempotent function, use setDescriptionIdempI - but if you do, you may need to change your layout to include pageDescription.
Add translated description meta tag to the head of the page
n.b. See comments for setDescription.
Add description meta tag to the head of the page
Google does not use the description tag as a ranking signal, but the contents of this tag will likely affect your click-through rate since it shows up in search results.
The average length of the description shown in Google's search results is about 160 characters on desktop, and about 130 characters on mobile, at time of writing.
Unlike setDescription, this version is *idempotent* - calling it multiple times will result in only a single description meta tag in the head.
Source: https://www.advancedwebranking.com/blog/meta-tags-important-in-seo/
Add translated description meta tag to the head of the page
n.b. See comments for setDescriptionIdemp.
Unlike setDescriptionI, this version is *idempotent* - calling it multiple times will result in only a single description meta tag in the head.
Add OpenGraph image meta tag to the head of the page
Best practices:
Use custom images for shareable pages, e.g., homepage, articles, etc.
Use your logo or any other branded image for the rest of your pages.
Use images with a 1.91:1 ratio and minimum recommended dimensions of 1200x630 for optimal clarity across all devices.
Add OpenGraph type meta tag to the head of the page
See all available OG types here: https://ogp.me/#types
Set the page title.
Calling setTitle or setTitleI multiple times overrides previously set
values.
SEO Notes:
Title tags are the second most important on-page factor for SEO, after content
Every page should have a unique title tag
Start your title tag with your main targeted keyword
Don't stuff your keywords
Google typically shows 55-64 characters, so aim to keep your title length under 60 characters
Set the localised page title.
n.b. See comments for setTitle
Instances3ParseRoute
ParseRoute LiteAppDefined in yesod-core-1.6.26.0 · Yesod.Core.Internal.LiteAppParseRoute WaiSubsiteDefined in yesod-core-1.6.26.0 · Yesod.Core.TypesParseRoute WaiSubsiteWithAuthDefined in yesod-core-1.6.26.0 · Yesod.Core.Types
Methods
routeAttrs :: Route a -> Set Text
A quasi-quoter to parse a string into a list of Resources. Checks for overlapping routes, failing if present; use parseRoutesNoCheck to skip the checking. See documentation site for details on syntax.
Same as parseRoutes, but uses an external file instead of quasiquotation.
The recommended file extension is .yesodroutes.
Same as parseRoutesNoCheck, but uses an external file instead of quasiquotation.
The recommended file extension is .yesodroutes.
Same as parseRoutes, but performs no overlap checking.
General opts data type for generating yesod.
Contains options for what instances are derived for the route. Use the setting functions on defaultOpts to set specific fields.
Default options for generating routes.
Defaults to all instances derived.
Generates a function that takes a Text and logs a LevelDebug message. Usage:
$(logDebug) "This is a debug log message"Generates a function that takes a LogSource and Text and logs a LevelDebug message. Usage:
$logDebugS "SomeSource" "This is a debug log message"See logDebug
See logDebugS
See logDebug
See logDebugS
Generates a function that takes a Text and logs a LevelOther message. Usage:
$(logOther "My new level") "This is a log message"Generates a function that takes a LogSource, a level name and a Text and logs a LevelOther message. Usage:
$logOtherS "SomeSource" "My new level" "This is a log message"See logDebug
See logDebugS
Hamlet quasi-quoter. May only be used to generate expressions.
Generated expression have type HtmlUrl url, for some url.
data MyRoute = Home
render :: Render MyRoute
render Home _ = "/home"
>>> putStrLn (renderHtml ([hamlet|<a href=@{Home}>Home|] render))
<a href="/home">Home</a>
Like hamlet, but produces XHTML.
render with route interpolation. If using this module standalone, apart from type-safe routes, a dummy renderer can be used:
renderJavascriptUrl (\_ _ -> undefined) javascriptUrlWhen using Yesod, a renderer is generated for you, which can be accessed within the GHandler monad: getUrlRenderParams.
renderCss ([lucius|foo{bar:baz}|] undefined)"foo{bar:baz}"
mkMessage generate translations from translation files
This function will:
look in the supplied subdirectory for files ending in
.msggenerate a type based on the constructors found
create a RenderMessage instance
mkMessageFor create RenderMessage instance for an existing data-type
mkMessageVariant create an additional set of translations for a type created by mkMessage
maybeAuthorized Return the same URL if the user is authorized to see it.
Built on top of isAuthorized. This is useful for building page that only contain links to pages the user is allowed to see.
Return an Unauthorized value, with the given i18n message.
A type that can be converted to JSON.
Instances in general must specify toJSON and should (but don't need to) specify toEncoding.
An example type and instance:
-- Allow ourselves to write Text literals.
{-# LANGUAGE OverloadedStrings #-}
data Coord = Coord { x :: Double, y :: Double }
instance ToJSON Coord where
toJSON (Coord x y) = object ["x" .= x, "y" .= y]
toEncoding (Coord x y) = pairs ("x" .= x <> "y" .= y)
Instead of manually writing your ToJSON instance, there are two options to do it automatically:
Data.Aeson.TH provides Template Haskell functions which will derive an instance at compile time. The generated instance is optimized for your type so it will probably be more efficient than the following option.
The compiler can provide a default generic implementation for toJSON.
To use the second, simply add a deriving Generic clause to your
datatype and declare a ToJSON instance. If you require nothing other than
defaultOptions, it is sufficient to write (and this is the only
alternative where the default toJSON implementation is sufficient):
{-# LANGUAGE DeriveGeneric #-}
import GHC.Generics
data Coord = Coord { x :: Double, y :: Double } deriving Generic
instance ToJSON Coord where
toEncoding = genericToEncoding defaultOptions
or more conveniently using the DerivingVia extension
deriving via Generically Coord instance ToJSON Coord
If on the other hand you wish to customize the generic decoding, you have to implement both methods:
customOptions = defaultOptions
{ fieldLabelModifier = map toUpper
}
instance ToJSON Coord where
toJSON = genericToJSON customOptions
toEncoding = genericToEncoding customOptions
Previous versions of this library only had the toJSON method. Adding toEncoding had two reasons:
toEncoding is more efficient for the common case that the output of toJSON is directly serialized to a
ByteString. Further, expressing either method in terms of the other would be non-optimal.The choice of defaults allows a smooth transition for existing users: Existing instances that do not define toEncoding still compile and have the correct semantics. This is ensured by making the default implementation of toEncoding use toJSON. This produces correct results, but since it performs an intermediate conversion to a Value, it will be less efficient than directly emitting an Encoding. (this also means that specifying nothing more than
instance ToJSON Coordwould be sufficient as a generically decoding instance, but there probably exists no good reason to not specify toEncoding in new instances.)
Methods
toJSON :: a -> ValueConvert a Haskell value to a JSON-friendly intermediate type.
toEncoding :: a -> EncodingEncode a Haskell value as JSON.
The default implementation of this method creates an intermediate Value using toJSON. This provides source-level compatibility for people upgrading from older versions of this library, but obviously offers no performance advantage.
To benefit from direct encoding, you must provide an implementation for this method. The easiest way to do so is by having your types implement Generic using the
DeriveGenericextension, and then have GHC generate a method body as follows.instance ToJSON Coord where toEncoding = genericToEncoding defaultOptionstoJSONList :: [a] -> ValuetoEncodingList :: [a] -> EncodingomitField :: a -> BoolDefines when it is acceptable to omit a field of this type from a record. Used by
(.?=)operator, and Generics and TH deriving withomitNothingFields = True.
Instances119ToJSON, …
ToJSON KeyDefined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON DotNetTimeDefined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON ValueDefined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON IntSetDefined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON IntegerDefined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON NaturalDefined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON VoidDefined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON AllDefined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON AnyDefined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON VersionDefined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON CTimeDefined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON Int16Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON Int32Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON Int64Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON Int8Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON Word16Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON Word32Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON Word64Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON Word8Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON BoolDefined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON CharDefined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON DoubleDefined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON FloatDefined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON IntDefined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON OrderingDefined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON WordDefined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON URIDefined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON PersistValueDefined in persistent-2.14.6.3 · Database.Persist.PersistValueToJSON ScientificDefined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON TextDefined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON TextDefined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON ShortTextDefined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON CalendarDiffDaysDefined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON DayDefined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON MonthDefined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON QuarterDefined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON QuarterOfYearDefined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON DayOfWeekDefined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON DiffTimeDefined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON NominalDiffTimeDefined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON SystemTimeDefined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONEncoded as number
ToJSON UTCTimeDefined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON CalendarDiffTimeDefined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON LocalTimeDefined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON TimeOfDayDefined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON ZonedTimeDefined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON UUIDDefined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON TextareaDefined in yesod-form-1.7.9 · Yesod.Form.FieldsToJSON ()Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON (BackendKey SqlReadBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanToJSON (BackendKey SqlWriteBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanToJSON (BackendKey SqlBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanToJSON a => ToJSON (First a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON a => ToJSON (Last a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON a => ToJSON (Max a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON a => ToJSON (Min a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON a => ToJSON (WrappedMonoid a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON a => ToJSON (IntMap a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON a => ToJSON (Seq a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON a => ToJSON (Set a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON a => ToJSON (DNonEmpty a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON a => ToJSON (DList a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON a => ToJSON (NonEmpty a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON a => ToJSON (Identity a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON a => ToJSON (First a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON a => ToJSON (Last a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON a => ToJSON (Down a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON a => ToJSON (Dual a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON a => ToJSON (Product a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON a => ToJSON (Sum a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON a => ToJSON (Maybe a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON a => ToJSON (Array a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON a => ToJSON (SmallArray a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON a => ToJSON (Maybe a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON a => ToJSON (HashSet a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON a => ToJSON (Vector a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON a => ToJSON (a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON a => ToJSON [a]Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON v => ToJSON (KeyMap v)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON v => ToJSON (Tree v)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON1 f => ToJSON (Fix f)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSON(ToJSON a, Integral a) => ToJSON (Ratio a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSON(ToJSON1 f, Functor f) => ToJSON (Mu f)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSON(ToJSON1 f, Functor f) => ToJSON (Nu f)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSON(Storable a, ToJSON a) => ToJSON (Vector a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSON(Generic a, GToJSON' Value Zero (Rep a), GToJSON' Encoding Zero (Rep a)) => ToJSON (Generically a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSON(BackendCompatible b s, ToJSON (BackendKey b)) => ToJSON (BackendKey (Compatible b s))Defined in persistent-2.14.6.3 · Database.Persist.Compatible.Types(Prim a, ToJSON a) => ToJSON (PrimArray a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSON(Prim a, ToJSON a) => ToJSON (Vector a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSON(Vector Vector a, ToJSON a) => ToJSON (Vector a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON (Proxy a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONHasResolution a => ToJSON (Fixed a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSON(ToJSON a, ToJSON b) => ToJSON (Either a b)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSON(ToJSON a, ToJSON b) => ToJSON (Either a b)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSON(ToJSON a, ToJSON b) => ToJSON (These a b)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSON(ToJSON a, ToJSON b) => ToJSON (Pair a b)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSON(ToJSON a, ToJSON b) => ToJSON (These a b)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSON(ToJSON a, ToJSON b) => ToJSON (a, b)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSON(ToJSON v, ToJSONKey k) => ToJSON (Map k v)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSON(ToJSON v, ToJSONKey k) => ToJSON (HashMap k v)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON a => ToJSON (Const a b)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSONToJSON b => ToJSON (Tagged a b)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSON(ToJSON a, ToJSON b, ToJSON c) => ToJSON (a, b, c)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSON(ToJSON1 f, ToJSON1 g, ToJSON a) => ToJSON (These1 f g a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSON(ToJSON a, ToJSON b, ToJSON c, ToJSON d) => ToJSON (a, b, c, d)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSON(ToJSON1 f, ToJSON1 g, ToJSON a) => ToJSON (Product f g a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSON(ToJSON1 f, ToJSON1 g, ToJSON a) => ToJSON (Sum f g a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSON(ToJSON a, ToJSON b, ToJSON c, ToJSON d, ToJSON e) => ToJSON (a, b, c, d, e)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSON(ToJSON1 f, ToJSON1 g, ToJSON a) => ToJSON (Compose f g a)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSON(ToJSON a, ToJSON b, ToJSON c, ToJSON d, ToJSON e, ToJSON f) => ToJSON (a, b, c, d, e, f)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSON(ToJSON a, ToJSON b, ToJSON c, ToJSON d, ToJSON e, ToJSON f, ToJSON g) => ToJSON (a, b, c, d, e, f, g)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSON(ToJSON a, ToJSON b, ToJSON c, ToJSON d, ToJSON e, ToJSON f, ToJSON g, ToJSON h) => ToJSON (a, b, c, d, e, f, g, h)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSON(ToJSON a, ToJSON b, ToJSON c, ToJSON d, ToJSON e, ToJSON f, ToJSON g, ToJSON h, ToJSON i) => ToJSON (a, b, c, d, e, f, g, h, i)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSON(ToJSON a, ToJSON b, ToJSON c, ToJSON d, ToJSON e, ToJSON f, ToJSON g, ToJSON h, ToJSON i, ToJSON j) => ToJSON (a, b, c, d, e, f, g, h, i, j)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSON(ToJSON a, ToJSON b, ToJSON c, ToJSON d, ToJSON e, ToJSON f, ToJSON g, ToJSON h, ToJSON i, ToJSON j, ToJSON k) => ToJSON (a, b, c, d, e, f, g, h, i, j, k)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSON(ToJSON a, ToJSON b, ToJSON c, ToJSON d, ToJSON e, ToJSON f, ToJSON g, ToJSON h, ToJSON i, ToJSON j, ToJSON k, ToJSON l) => ToJSON (a, b, c, d, e, f, g, h, i, j, k, l)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSON(ToJSON a, ToJSON b, ToJSON c, ToJSON d, ToJSON e, ToJSON f, ToJSON g, ToJSON h, ToJSON i, ToJSON j, ToJSON k, ToJSON l, ToJSON m) => ToJSON (a, b, c, d, e, f, g, h, i, j, k, l, m)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSON(ToJSON a, ToJSON b, ToJSON c, ToJSON d, ToJSON e, ToJSON f, ToJSON g, ToJSON h, ToJSON i, ToJSON j, ToJSON k, ToJSON l, ToJSON m, ToJSON n) => ToJSON (a, b, c, d, e, f, g, h, i, j, k, l, m, n)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSON(ToJSON a, ToJSON b, ToJSON c, ToJSON d, ToJSON e, ToJSON f, ToJSON g, ToJSON h, ToJSON i, ToJSON j, ToJSON k, ToJSON l, ToJSON m, ToJSON n, ToJSON o) => ToJSON (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o)Defined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSON
Instances14PersistField, PersistFieldSql, ToHamletData, HasContentType, ToContent, ToTypedContent, …
PersistField HtmlDefined in persistent-2.14.6.3 · Database.Persist.Class.PersistFieldPersistFieldSql HtmlDefined in persistent-2.14.6.3 · Database.Persist.Sql.ClassToHamletData HtmlDefined in shakespeare-2.1.0.1 · Text.Hamlet.RuntimeHasContentType HtmlDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToContent HtmlDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToFlushBuilder HtmlDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToTypedContent HtmlDefined in yesod-core-1.6.26.0 · Yesod.Core.ContentToWidget site HtmlDefined in yesod-core-1.6.26.0 · Yesod.Core.WidgetToWidgetBody site HtmlDefined in yesod-core-1.6.26.0 · Yesod.Core.WidgetToWidgetHead site HtmlDefined in yesod-core-1.6.26.0 · Yesod.Core.Widgetrender ~ RY site => ToWidget site (render -> Html)Defined in yesod-core-1.6.26.0 · Yesod.Core.Widgetrender ~ RY site => ToWidgetBody site (render -> Html)Defined in yesod-core-1.6.26.0 · Yesod.Core.Widgetrender ~ RY site => ToWidgetHead site (render -> Html)Defined in yesod-core-1.6.26.0 · Yesod.Core.WidgetToFlushBuilder (Flush Html)Defined in yesod-core-1.6.26.0 · Yesod.Core.Content
Convert a value to Markup without escaping
A Monad which has the ability to log messages in some manner.
Instances20MonadLogger, …
MonadIO m => MonadLogger (LoggingT m)Defined in monad-logger-0.3.42 · Control.Monad.LoggerMonad m => MonadLogger (NoLoggingT m)Defined in monad-logger-0.3.42 · Control.Monad.LoggerMonad m => MonadLogger (WriterLoggingT m)Defined in monad-logger-0.3.42 · Control.Monad.LoggerMonadLogger (HandlerFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesMonadLogger (WidgetFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesMonadLogger m => MonadLogger (ResourceT m)Defined in monad-logger-0.3.42 · Control.Monad.LoggerMonadLogger m => MonadLogger (MaybeT m)Defined in monad-logger-0.3.42 · Control.Monad.LoggerMonadLogger (SubHandlerFor child master)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesMonadLogger m => MonadLogger (ExceptT e m)Defined in monad-logger-0.3.42 · Control.Monad.LoggerMonadLogger m => MonadLogger (IdentityT m)Defined in monad-logger-0.3.42 · Control.Monad.LoggerMonadLogger m => MonadLogger (ReaderT r m)Defined in monad-logger-0.3.42 · Control.Monad.LoggerMonadLogger m => MonadLogger (StateT s m)Defined in monad-logger-0.3.42 · Control.Monad.LoggerMonadLogger m => MonadLogger (StateT s m)Defined in monad-logger-0.3.42 · Control.Monad.Logger(MonadLogger m, Monoid w) => MonadLogger (WriterT w m)Defined in monad-logger-0.3.42 · Control.Monad.Logger(MonadLogger m, Monoid w) => MonadLogger (WriterT w m)Defined in monad-logger-0.3.42 · Control.Monad.LoggerMonadLogger m => MonadLogger (ConduitM i o m)Defined in monad-logger-0.3.42 · Control.Monad.LoggerMonadLogger m => MonadLogger (ContT r m)Defined in monad-logger-0.3.42 · Control.Monad.Logger(MonadLogger m, Monoid w) => MonadLogger (RWST r w s m)Defined in monad-logger-0.3.42 · Control.Monad.Logger(MonadLogger m, Monoid w) => MonadLogger (RWST r w s m)Defined in monad-logger-0.3.42 · Control.Monad.LoggerMonadLogger m => MonadLogger (Pipe l i o u m)Defined in monad-logger-0.3.42 · Control.Monad.Logger
Methods
fromPathMultiPiece :: [Text] -> Maybe stoPathMultiPiece :: s -> [Text]
Instances2PathMultiPiece
PathPiece a => PathMultiPiece [a]Defined in path-pieces-0.2.1 · Web.PathPiecesPersistEntity record => PathMultiPiece (ViaPersistEntity record)Defined in persistent-2.14.6.3 · Database.Persist.Class.PersistEntity
Methods
fromPathPiece :: Text -> Maybe stoPathPiece :: s -> Text
Instances23PathPiece, …
PathPiece IntegerDefined in path-pieces-0.2.1 · Web.PathPiecesPathPiece StringDefined in path-pieces-0.2.1 · Web.PathPiecesPathPiece Int16Defined in path-pieces-0.2.1 · Web.PathPiecesPathPiece Int32Defined in path-pieces-0.2.1 · Web.PathPiecesPathPiece Int64Defined in path-pieces-0.2.1 · Web.PathPiecesPathPiece Int8Defined in path-pieces-0.2.1 · Web.PathPiecesPathPiece Word16Defined in path-pieces-0.2.1 · Web.PathPiecesPathPiece Word32Defined in path-pieces-0.2.1 · Web.PathPiecesPathPiece Word64Defined in path-pieces-0.2.1 · Web.PathPiecesPathPiece Word8Defined in path-pieces-0.2.1 · Web.PathPiecesPathPiece BoolDefined in path-pieces-0.2.1 · Web.PathPiecesPathPiece IntDefined in path-pieces-0.2.1 · Web.PathPiecesPathPiece WordDefined in path-pieces-0.2.1 · Web.PathPiecesPathPiece PersistValueDefined in persistent-2.14.6.3 · Database.Persist.PersistValuePathPiece CheckmarkDefined in persistent-2.14.6.3 · Database.Persist.Types.BasePathPiece TextDefined in path-pieces-0.2.1 · Web.PathPiecesPathPiece TextDefined in path-pieces-0.2.1 · Web.PathPiecesPathPiece DayDefined in path-pieces-0.2.1 · Web.PathPiecesPathPiece ()Defined in path-pieces-0.2.1 · Web.PathPiecesPathPiece (BackendKey SqlReadBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanPathPiece (BackendKey SqlWriteBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanPathPiece (BackendKey SqlBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanPathPiece a => PathPiece (Maybe a)Defined in path-pieces-0.2.1 · Web.PathPieces
A Monad which allows for safe resource allocation. In theory, any monad
transformer stack which includes a ResourceT can be an instance of
MonadResource.
Note: runResourceT has a requirement for a MonadUnliftIO m monad,
which allows control operations to be lifted. A MonadResource does not
have this requirement. This means that transformers such as ContT can be
an instance of MonadResource. However, the ContT wrapper will need to be
unwrapped before calling runResourceT.
Since 0.3.0
Methods
liftResourceT :: ResourceT IO a -> m aLift a
ResourceT IOaction into the currentMonad.Since 0.4.0
Instances19MonadResource, …
MonadIO m => MonadResource (ResourceT m)Defined in resourcet-1.3.0 · Control.Monad.Trans.Resource.InternalMonadResource (HandlerFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesMonadResource (WidgetFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesMonadResource m => MonadResource (LoggingT m)Defined in monad-logger-0.3.42 · Control.Monad.LoggerMonadResource m => MonadResource (NoLoggingT m)Defined in monad-logger-0.3.42 · Control.Monad.LoggerMonadResource m => MonadResource (MaybeT m)Defined in resourcet-1.3.0 · Control.Monad.Trans.Resource.InternalMonadResource (SubHandlerFor child master)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesMonadResource m => MonadResource (ExceptT e m)Defined in resourcet-1.3.0 · Control.Monad.Trans.Resource.InternalMonadResource m => MonadResource (IdentityT m)Defined in resourcet-1.3.0 · Control.Monad.Trans.Resource.InternalMonadResource m => MonadResource (ReaderT r m)Defined in resourcet-1.3.0 · Control.Monad.Trans.Resource.InternalMonadResource m => MonadResource (StateT s m)Defined in resourcet-1.3.0 · Control.Monad.Trans.Resource.InternalMonadResource m => MonadResource (StateT s m)Defined in resourcet-1.3.0 · Control.Monad.Trans.Resource.Internal(Monoid w, MonadResource m) => MonadResource (WriterT w m)Defined in resourcet-1.3.0 · Control.Monad.Trans.Resource.Internal(Monoid w, MonadResource m) => MonadResource (WriterT w m)Defined in resourcet-1.3.0 · Control.Monad.Trans.Resource.InternalMonadResource m => MonadResource (ConduitT i o m)Defined in conduit-1.3.6.1 · Data.Conduit.Internal.ConduitMonadResource m => MonadResource (ContT r m)Defined in resourcet-1.3.0 · Control.Monad.Trans.Resource.Internal(Monoid w, MonadResource m) => MonadResource (RWST r w s m)Defined in resourcet-1.3.0 · Control.Monad.Trans.Resource.Internal(Monoid w, MonadResource m) => MonadResource (RWST r w s m)Defined in resourcet-1.3.0 · Control.Monad.Trans.Resource.InternalMonadResource m => MonadResource (Pipe l i o u m)Defined in conduit-1.3.6.1 · Data.Conduit.Internal.Pipe
A function generating an Html given a URL-rendering function.
Return type of template-reading functions.
an RFC1766 / ISO 639-1 language code (eg, fr, en-GB, etc).
the RenderMessage is used to provide translations for a message types
The master argument exists so that it is possible to provide more
than one set of translations for a message type. This is useful
if a library provides a default set of translations, but the user
of the library wants to provide a different set of translations.
Methods
renderMessage :: master -> [Lang] -> message -> Text
Instances2RenderMessage
RenderMessage master TextDefined in shakespeare-2.1.0.1 · Text.Shakespeare.I18Nmaster ~ master' => RenderMessage master (SomeMessage master')Defined in shakespeare-2.1.0.1 · Text.Shakespeare.I18N
Constructors
forall msg. RenderMessage master msg => SomeMessage msg
Instances2RenderMessage, IsString
master ~ master' => RenderMessage master (SomeMessage master')Defined in shakespeare-2.1.0.1 · Text.Shakespeare.I18NIsString (SomeMessage master)Defined in shakespeare-2.1.0.1 · Text.Shakespeare.I18N
class (forall (m :: Type -> Type). Monad m => Monad (t m)) => MonadTrans (t :: (Type -> Type) -> Type -> Type) whereThe class of monad transformers.
For any monad m, the result t m should also be a monad,
and lift should be a monad transformation from m to t m,
i.e. it should satisfy the following laws:
Since 0.6.0.0 and for GHC 8.6 and later, the requirement that t m
be a Monad is enforced by the implication constraint
forall m. Monad m => Monad (t m) enabled by the
QuantifiedConstraints extension.
Ambiguity error with GHC 9.0 to 9.2.2
These versions of GHC have a bug (https://gitlab.haskell.org/ghc/ghc/-/issues/20582) which causes constraints like
(MonadTrans t, forall m. Monad m => Monad (t m)) => ...
to be reported as ambiguous. For transformers 0.6 and later, this can be fixed by removing the second constraint, which is implied by the first.
Instances25MonadTrans, …
MonadTrans PropertyMDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.MonadicMonadTrans CatchTDefined in exceptions-0.10.9 · Control.Monad.Catch.PureMonadTrans LoggingTDefined in monad-logger-0.3.42 · Control.Monad.LoggerMonadTrans NoLoggingTDefined in monad-logger-0.3.42 · Control.Monad.LoggerMonadTrans WriterLoggingTDefined in monad-logger-0.3.42 · Control.Monad.LoggerMonadTrans ResourceTDefined in resourcet-1.3.0 · Control.Monad.Trans.Resource.InternalMonadTrans MaybeTDefined in transformers-0.6.1.1 · Control.Monad.Trans.MaybeMonadTrans AFormDefined in yesod-form-1.7.9 · Yesod.Form.TypesMonoid w => MonadTrans (AccumT w)Defined in transformers-0.6.1.1 · Control.Monad.Trans.AccumMonoid w => MonadTrans (WriterT w)Defined in transformers-0.6.1.1 · Control.Monad.Trans.Writer.LazyMonoid w => MonadTrans (WriterT w)Defined in transformers-0.6.1.1 · Control.Monad.Trans.Writer.StrictMonadTrans IdentityTDefined in transformers-0.6.1.1 · Control.Monad.Trans.IdentityMonadTrans (ExceptT e)Defined in transformers-0.6.1.1 · Control.Monad.Trans.ExceptMonadTrans (ReaderT r)Defined in transformers-0.6.1.1 · Control.Monad.Trans.ReaderMonadTrans (SelectT r)Defined in transformers-0.6.1.1 · Control.Monad.Trans.SelectMonadTrans (StateT s)Defined in transformers-0.6.1.1 · Control.Monad.Trans.State.LazyMonadTrans (StateT s)Defined in transformers-0.6.1.1 · Control.Monad.Trans.State.StrictMonadTrans (WriterT w)Defined in transformers-0.6.1.1 · Control.Monad.Trans.Writer.CPSMonadTrans (ConduitT i o)Defined in conduit-1.3.6.1 · Data.Conduit.Internal.ConduitMonadTrans (ParsecT s u)Defined in parsec-3.1.18.0 · Text.Parsec.PrimMonadTrans (ContT r)Defined in transformers-0.6.1.1 · Control.Monad.Trans.ContMonoid w => MonadTrans (RWST r w s)Defined in transformers-0.6.1.1 · Control.Monad.Trans.RWS.LazyMonoid w => MonadTrans (RWST r w s)Defined in transformers-0.6.1.1 · Control.Monad.Trans.RWS.StrictMonadTrans (RWST r w s)Defined in transformers-0.6.1.1 · Control.Monad.Trans.RWS.CPSMonadTrans (Pipe l i o u)Defined in conduit-1.3.6.1 · Data.Conduit.Internal.Pipe
Monads which allow their actions to be run in IO.
While MonadIO allows an IO action to be lifted into another monad, this class captures the opposite concept: allowing you to capture the monadic context. Note that, in order to meet the laws given below, the intuition is that a monad must have no monadic state, but may have monadic context. This essentially limits MonadUnliftIO to ReaderT and IdentityT transformers on top of IO.
Laws. For any function run provided by withRunInIO, it must meet the
monad transformer laws as reformulated for MonadUnliftIO:
run . return = returnrun (m >>= f) = run m >>= run . f
Instances of MonadUnliftIO must also satisfy the following laws:
- Identity law
withRunInIO (\run -> run m) = m- Inverse law
withRunInIO (\_ -> m) = liftIO m
As an example of an invalid instance, a naive implementation of
MonadUnliftIO (StateT s m) might be
withRunInIO inner =
StateT $ \s ->
withRunInIO $ \run ->
inner (run . flip evalStateT s)
This breaks the identity law because the inner run m would throw away
any state changes in m.
Methods
withRunInIO :: ((forall a. m a -> IO a) -> IO b) -> m bConvenience function for capturing the monadic context and running an IO action with a runner function. The runner function is used to run a monadic action
minIO.
Instances9MonadUnliftIO, …
MonadUnliftIO IODefined in unliftio-core-0.2.1.0 · Control.Monad.IO.UnliftMonadUnliftIO (HandlerFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesMonadUnliftIO (WidgetFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesMonadUnliftIO m => MonadUnliftIO (LoggingT m)Defined in monad-logger-0.3.42 · Control.Monad.LoggerMonadUnliftIO m => MonadUnliftIO (NoLoggingT m)Defined in monad-logger-0.3.42 · Control.Monad.LoggerMonadUnliftIO m => MonadUnliftIO (ResourceT m)Defined in resourcet-1.3.0 · Control.Monad.Trans.Resource.InternalMonadUnliftIO (SubHandlerFor child master)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesMonadUnliftIO m => MonadUnliftIO (IdentityT m)Defined in unliftio-core-0.2.1.0 · Control.Monad.IO.UnliftMonadUnliftIO m => MonadUnliftIO (ReaderT r m)Defined in unliftio-core-0.2.1.0 · Control.Monad.IO.Unlift
Constructors
OptionoptionDisplay :: TextThe user-facing label.
optionInternalValue :: aThe Haskell value being selected.
optionExternalValue :: TextThe representation of this value stored in the form.
A structure holding a list of options. Typically you can use a convenience function like mkOptionList or optionsPairs instead of creating this directly.
Extended by OptionListGrouped in 1.7.0.
Constructors
OptionListolOptions :: [Option a]olReadExternal :: Text -> Maybe aA function mapping from the form's value (optionExternalValue) to the selected Haskell value (optionInternalValue).
OptionListGroupedolOptionsGrouped :: [(Text, [Option a])]olReadExternalGrouped :: Text -> Maybe aA function mapping from the form's value (optionExternalValue) to the selected Haskell value (optionInternalValue).
Instances1Functor
Functor OptionListDefined in yesod-form-1.7.9 · Yesod.Form.Fields
A newtype wrapper around a Text whose ToMarkup instance converts newlines to HTML <br> tags.
(When text is entered into a <textarea>, newline characters are used to separate lines.
If this text is then placed verbatim into HTML, the lines won't be separated, thus the need for replacing with <br> tags).
If you don't need this functionality, simply use unTextarea to access the raw text.
Constructors
Instances10Eq, Ord, Read, Show, IsString, FromJSON, …
Eq TextareaDefined in yesod-form-1.7.9 · Yesod.Form.FieldsOrd TextareaDefined in yesod-form-1.7.9 · Yesod.Form.FieldsRead TextareaDefined in yesod-form-1.7.9 · Yesod.Form.FieldsShow TextareaDefined in yesod-form-1.7.9 · Yesod.Form.FieldsIsString TextareaDefined in yesod-form-1.7.9 · Yesod.Form.FieldsFromJSON TextareaDefined in yesod-form-1.7.9 · Yesod.Form.FieldsToJSON TextareaDefined in yesod-form-1.7.9 · Yesod.Form.FieldsToMarkup TextareaDefined in yesod-form-1.7.9 · Yesod.Form.FieldsPersistField TextareaDefined in yesod-form-1.7.9 · Yesod.Form.FieldsPersistFieldSql TextareaDefined in yesod-form-1.7.9 · Yesod.Form.Fields
Creates a group of radio buttons to answer the question given in the message. Radio buttons are used to allow differentiating between an empty response (Nothing) and a no response (Just False). Consider using the simpler checkBoxField if you don't need to make this distinction.
If this field is optional, the first radio button is labeled "<None>", the second "Yes" and the third "No".
If this field is required, the first radio button is labeled "Yes" and the second "No".
(Exact label titles will depend on localization).
Creates an input with type="checkbox".
While the default boolField implements a radio button so you
can differentiate between an empty response (Nothing) and a no
response (Just False), this simpler checkbox field returns an empty
response as Just False.
Note that this makes the field always optional.
Deprecated. This function seems to have a bug (label could not be found with byLabel algorithm)
Creates an input with type="checkbox" for selecting multiple options.
Creates an input with type="checkbox" for selecting multiple options.
Creates an input with type="checkbox" for selecting multiple options.
Creates an input with type="color".
The input value must be provided in hexadecimal format #rrggbb.
datetimeLocalField :: (Monad m, RenderMessage (HandlerSite m) FormMessage) => Field m LocalTimeCreates an input with type="datetime-local".
The input value must be provided in YYYY-MM-DD(T| )HH:MM[:SS] format.
Creates an input with type="date", validating the input using the parseDate function.
Add the time package and import the Data.Time.Calendar module to use this function.
Creates a input with type="number" and step=any.
Creates an input with type="email". Yesod will validate the email's correctness according to RFC5322 and canonicalize it by removing comments and whitespace (see Text.Email.Validate).
Creates an input with type="file".
Creates a <textarea> tag whose input is sanitized to prevent XSS attacks and is validated for having balanced tags.
Creates a input with type="number" and step=1.
Creates an OptionList, using a Map to implement the olReadExternal function.
Creates an OptionList, using a Map to implement the olReadExternalGrouped function.
Creates an input with type="email" with the multiple attribute; browsers might implement this as taking a comma separated list of emails. Each email address is validated as described in emailField.
Creates a <select> tag for selecting multiple options.
Creates a <select> tag for selecting multiple options.
Creates an OptionList from an Enum, using its Show instance for the user-facing value.
Creates an OptionList from a list of (display-value, internal value) pairs.
Creates an OptionList from a list of (display-value, internal value) pairs.
Selects a list of Entitys with the given Filter and SelectOpts. The (a -> msg) function is then used to derive the display value for an OptionList. Example usage:
Country
name Text
deriving Eq -- Must derive Eqdata CountryForm = CountryForm
{ country :: Entity Country
}
countryNameForm :: AForm Handler CountryForm
countryNameForm = CountryForm
<$> areq (selectField countries) "Which country do you live in?" Nothing
where
countries = optionsPersist [] [Asc CountryName] countryNameAn alternative to optionsPersist which returns just the Key instead of the entire Entity.
Creates an input with type="password".
Deprecated. This function seems to have a bug (label could not be found with byLabel algorithm)
Creates an input with type="radio" for selecting one option.
Creates an input with type="radio" for selecting one option.
Creates an input with type="radio" for selecting one option.
Creates an input with type="search". For browsers without autofocus support, a JS fallback is used if AutoFocus is true.
Creates a <select> tag with optional <optgroup>s for selecting one option. Example usage:
areq (selectField $ optionsPairs [(MsgValue1, "value1"),(MsgValue2, "value2")]) "Which value?" NothingselectFieldHelper :: (Eq a, RenderMessage site FormMessage)=> (Text -> Text -> [(Text, Text)] -> WidgetFor site () -> WidgetFor site ())Outermost part of the field
-> (Text -> Text -> Bool -> WidgetFor site ())An option for None if the field is optional
-> (Text -> Text -> [(Text, Text)] -> Text -> Bool -> Text -> WidgetFor site ())Other options
-> Maybe (Text -> WidgetFor site ())Group headers placed inbetween options
-> HandlerFor site (OptionList a)-> Field (HandlerFor site) a
A helper function for constucting selectFields with optional option groups. You may want to use this when you define your custom selectFields or radioFields.
Creates a <select> tag for selecting one option. Example usage:
areq (selectFieldList [("Value 1" :: Text, "value1"),("Value 2", "value2")]) "Which value?" NothingCreates a <select> tag with <optgroup>s for selecting one option.
Creates a input with type="text".
An alias for timeFieldTypeTime.
timeFieldTypeText :: (Monad m, RenderMessage (HandlerSite m) FormMessage) => Field m TimeOfDayCreates an input with type="text", parsing the time from an [H]H:MM[:SS] format, with an optional AM or PM (if not given, AM is assumed for compatibility with the 24 hour clock system).
This function exists for backwards compatibility with the old implementation of timeField, which used to use type="text". Consider using timeField or timeFieldTypeTime for improved UX and validation from the browser.
Add the time package and import the Data.Time.LocalTime module to use this function.
timeFieldTypeTime :: (Monad m, RenderMessage (HandlerSite m) FormMessage) => Field m TimeOfDayCreates an input with type="time". Browsers not supporting this type will fallback to a text field, and Yesod will parse the time as described in timeFieldTypeText.
Add the time package and import the Data.Time.LocalTime module to use this function.
Creates an input with type="url", validating the URL according to RFC3986.
withRadioField :: (Eq a, RenderMessage site FormMessage)=> (Text -> WidgetFor site () -> WidgetFor site ())nothing case for mopt
-> (Text -> Text -> Bool -> Text -> WidgetFor site () -> WidgetFor site ())cases for values
-> HandlerFor site (OptionList a)-> Field (HandlerFor site) a
Allows the user to place the option radio widget somewhere in the template. For example: If you want a table of radio options to select. radioField is an example on how to use this function.
type FormRender (m :: Type -> Type) a = AForm m a -> Markup -> MForm m (FormResult a, WidgetFor (HandlerSite m) ())Adds a CSS class to the fsAttrs in a FieldSettings.
Examples
addClass "login-form" [("class", "form-control"), ("id", "home-login")][("class","form-control login-form"),("id","home-login")]
Applicative equivalent of mopt.
areq :: (RenderMessage site FormMessage, HandlerSite m ~ site, MonadHandler m)=> Field m aform field
-> FieldSettings sitesettings for this field
-> Maybe aoptional default value
-> AForm m a
Applicative equivalent of mreq.
areqMsg :: (RenderMessage site msg, HandlerSite m ~ site, MonadHandler m)=> Field m aform field
-> FieldSettings sitesettings for this field
-> msgmessage to use in case value is Nothing
-> Maybe aoptional default value
-> AForm m a
Same as areq but with your own message to be rendered in case the value
is not provided.
This is useful when you have several required fields on the page and you want to differentiate between which fields were left blank. Otherwise the user sees "Value is required" multiple times, which is ambiguous.
Return the given error message if the predicate is false.
Same as checkM, but modifies the datatype.
In order to make this work, you must provide a function to convert back from the new datatype to the old one (the second argument to this function).
Since 1.1.2
Since a Field cannot be a Functor, it is not obvious how to "reuse" a Field
on a newtype or otherwise equivalent type. This function allows you to convert
a Field m a to a Field m b assuming you provide a bidirectional
conversion between the two, through the first two functions.
A simple example:
import Data.Monoid
sumField :: (Functor m, Monad m, RenderMessage (HandlerSite m) FormMessage) => Field m (Sum Int)
sumField = convertField Sum getSum intFieldAnother example, not using a newtype, but instead creating a Lazy Text field:
import qualified Data.Text.Lazy as TL
TextField :: (Functor m, Monad m, RenderMessage (HandlerSite m) FormMessage) => Field m TL.Text
lazyTextField = convertField TL.fromStrict TL.toStrict textFieldSince 1.3.16
Allows you to overwrite the error message on parse error.
Generate a FieldSettings from the given label.
Deprecated. Will require RenderMessage in next version of Yesod
Since 1.3.11
Similar to runFormPost, except it always ignores the currently available
environment. This is necessary in cases like a wizard UI, where a single
page will both receive and incoming form and produce a new, blank form. For
general usage, you can stick with runFormPost.
identifyForm :: Monad m=> TextForm identification string.
-> (Markup -> MForm m (FormResult a, WidgetFor (HandlerSite m) ()))-> Markup-> MForm m (FormResult a, WidgetFor (HandlerSite m) ())
Creates a hidden field on the form that identifies it. This identification is then used to distinguish between missing and wrong form data when a single handler contains more than one form.
For instance, if you have the following code on your handler:
((fooRes, fooWidget), fooEnctype) <- runFormPost fooForm
((barRes, barWidget), barEnctype) <- runFormPost barFormThen replace it with
((fooRes, fooWidget), fooEnctype) <- runFormPost $ identifyForm "foo" fooForm
((barRes, barWidget), barEnctype) <- runFormPost $ identifyForm "bar" barFormNote that it's your responsibility to ensure that the identification strings are unique (using the same one twice on a single handler will not generate any errors). This allows you to create a variable number of forms and still have them work even if their number or order change between the HTML generation and the form submission.
mFormToWForm :: (MonadHandler m, HandlerSite m ~ site)=> MForm m (a, FieldView site)input form
-> WForm m aoutput form
mreq :: (RenderMessage site FormMessage, HandlerSite m ~ site, MonadHandler m)=> Field m aform field
-> FieldSettings sitesettings for this field
-> Maybe aoptional default value
-> MForm m (FormResult a, FieldView site)
Converts a form field into monadic form. This field requires a value and will return FormFailure if left empty.
mreqMsg :: (RenderMessage site msg, HandlerSite m ~ site, MonadHandler m)=> Field m aform field
-> FieldSettings sitesettings for this field
-> msgMessage to use in case value is Nothing
-> Maybe aoptional default value
-> MForm m (FormResult a, FieldView site)
Same as mreq but with your own message to be rendered in case the value
is not provided.
This is useful when you have several required fields on the page and you want to differentiate between which fields were left blank. Otherwise the user sees "Value is required" multiple times, which is ambiguous.
Get a unique identifier.
A helper function for creating custom fields.
This is intended to help with the common case where a single input value is required, such as when parsing a text field.
Since 1.1
A generalized version of parseHelper, allowing any type for the message indicating a bad parse.
Since 1.3.6
removeClass Removes a CSS class from the fsAttrs in a FieldSettings.
Examples
removeClass "form-control" [("class","form-control login-form"),("id","home-login")][("class"," login-form"),("id","home-login")]
Deprecated. Please use the Yesod.Form.Bootstrap3 module.
Deprecated synonym for renderBootstrap2.
Render a form using Bootstrap v2-friendly shamlet syntax. If you're using Bootstrap v3, then you should use the functions from module Yesod.Form.Bootstrap3.
Sample Hamlet:
<form .form-horizontal method=post action=@{ActionR} enctype=#{formEnctype}>
<fieldset>
<legend>_{MsgLegend}
$case result
$of FormFailure reasons
$forall reason <- reasons
<div .alert .alert-error>#{reason}
$of _
^{formWidget}
<div .form-actions>
<input .btn .primary type=submit value=_{MsgSubmit}>Since 1.3.14
render a field inside a div
render a field inside a div, not displaying any label
Render a form into a series of tr tags. Note that, in order to allow you to add extra rows to the table, this function does not wrap up the resulting HTML in a table tag; you must do that yourself.
This function is used to both initially render a form and to later extract results from it. Note that, due to CSRF protection and a few other issues, forms submitted via GET and POST are slightly different. As such, be sure to call the relevant function based on how the form will be submitted, not the current request method.
For example, a common case is displaying a form on a GET request and having the form submit to a POST page. In such a case, both the GET and POST handlers should use runFormPost.
wFormToMForm :: (MonadHandler m, HandlerSite m ~ site)=> WForm m ainput form
-> MForm m (a, [FieldView site])output form
wopt :: (MonadHandler m, HandlerSite m ~ site)=> Field m aform field
-> FieldSettings sitesettings for this field
-> Maybe (Maybe a)optional default value
-> WForm m (FormResult (Maybe a))
wreq :: (RenderMessage site FormMessage, HandlerSite m ~ site, MonadHandler m)=> Field m aform field
-> FieldSettings sitesettings for this field
-> Maybe aoptional default value
-> WForm m (FormResult a)
Converts a form field into monadic form WForm. This field requires a value and will return FormFailure if left empty.
wreqMsg :: (RenderMessage site msg, HandlerSite m ~ site, MonadHandler m)=> Field m aform field
-> FieldSettings sitesettings for this field
-> msgmessage to use in case value is Nothing
-> Maybe aoptional default value
-> WForm m (FormResult a)
Same as wreq but with your own message to be rendered in case the value
is not provided.
This is useful when you have several required fields on the page and you want to differentiate between which fields were left blank. Otherwise the user sees "Value is required" multiple times, which is ambiguous.
Type for a form which parses a value of type a with the base monad m
(usually your Handler). Can compose this using its Applicative instance.
Constructors
FormInputunFormInput :: HandlerSite m -> [Text] -> Env -> FileEnv -> m (Either DText a)
Promote a Field into a FormInput, with its presence being optional. If
the value is present but does not parse correctly, the form will still fail.
ireq :: (Monad m, RenderMessage (HandlerSite m) FormMessage)=> Field m a-> Textname of the field
-> FormInput m a
Promote a Field into a FormInput, requiring that the value be present
and valid.
Run a FormInput on the GET parameters (i.e., query string). If parsing
fails, calls invalidArgs.
Run a FormInput on the GET parameters (i.e., query string). Does not
throw exceptions on failure.
Since 1.4.1
Run a FormInput on the POST parameters (i.e., request body). If parsing
fails, calls invalidArgs.
Run a FormInput on the POST parameters (i.e., request body). Does not
throw exceptions on failure.
Constructors
AFormunAForm :: (HandlerSite m, [Text]) -> Maybe (Env, FileEnv) -> Ints -> m (FormResult a, [FieldView (HandlerSite m)] -> [FieldView (HandlerSite m)], Ints, Enctype)
Instances6MonadTrans, Monad, Functor, Applicative, Semigroup, Monoid
MonadTrans AFormDefined in yesod-form-1.7.9 · Yesod.Form.TypesMonad m => Monad (AForm m)Defined in yesod-form-1.7.9 · Yesod.Form.TypesMonad m => Functor (AForm m)Defined in yesod-form-1.7.9 · Yesod.Form.TypesMonad m => Applicative (AForm m)Defined in yesod-form-1.7.9 · Yesod.Form.Types(Monad m, Semigroup a) => Semigroup (AForm m a)Defined in yesod-form-1.7.9 · Yesod.Form.Types(Monad m, Monoid a) => Monoid (AForm m a)Defined in yesod-form-1.7.9 · Yesod.Form.Types
The encoding type required by a form. The ToHtml instance produces values
that can be inserted directly into HTML.
Instances7Bounded, Enum, Eq, Semigroup, Monoid, ToMarkup, …
Bounded EnctypeDefined in yesod-form-1.7.9 · Yesod.Form.TypesEnum EnctypeDefined in yesod-form-1.7.9 · Yesod.Form.TypesEq EnctypeDefined in yesod-form-1.7.9 · Yesod.Form.TypesSemigroup EnctypeDefined in yesod-form-1.7.9 · Yesod.Form.TypesMonoid EnctypeDefined in yesod-form-1.7.9 · Yesod.Form.TypesToMarkup EnctypeDefined in yesod-form-1.7.9 · Yesod.Form.TypesToValue EnctypeDefined in yesod-form-1.7.9 · Yesod.Form.Types
Constructors
FieldfieldParse :: [Text] -> [FileInfo] -> m (Either (SomeMessage (HandlerSite m)) (Maybe a))fieldView :: FieldViewFunc m afieldEnctype :: Enctype
Constructors
Instances1IsString
IsString (FieldSettings a)Defined in yesod-form-1.7.9 · Yesod.Form.Types
A form can produce three different results: there was no data available, the data was invalid, or there was a successful parse.
The Applicative instance will concatenate the failure messages in two FormResults. The Alternative instance will choose FormFailure before FormSuccess, and FormMissing last of all.
Constructors
Instances9Functor, Applicative, Foldable, Traversable, Alternative, Eq, …
Functor FormResultDefined in yesod-form-1.7.9 · Yesod.Form.TypesApplicative FormResultDefined in yesod-form-1.7.9 · Yesod.Form.TypesFoldable FormResultDefined in yesod-form-1.7.9 · Yesod.Form.TypesTraversable FormResultDefined in yesod-form-1.7.9 · Yesod.Form.TypesAlternative FormResultDefined in yesod-form-1.7.9 · Yesod.Form.TypesEq a => Eq (FormResult a)Defined in yesod-form-1.7.9 · Yesod.Form.TypesShow a => Show (FormResult a)Defined in yesod-form-1.7.9 · Yesod.Form.TypesSemigroup m => Semigroup (FormResult m)Defined in yesod-form-1.7.9 · Yesod.Form.TypesMonoid m => Monoid (FormResult m)Defined in yesod-form-1.7.9 · Yesod.Form.Types
Constructors
MsgInvalidInteger TextMsgInvalidNumber TextMsgInvalidEntry TextMsgInvalidUrl TextMsgInvalidEmail TextMsgInvalidTimeFormatMsgInvalidHour TextMsgInvalidMinute TextMsgInvalidSecond TextMsgInvalidDayMsgCsrfWarningMsgValueRequiredMsgInputNotFound TextMsgSelectNoneMsgInvalidBool TextMsgBoolYesMsgBoolNoMsgDeleteMsgInvalidHexColorFormat TextMsgInvalidDatetimeFormat Text
Instances3Eq, Read, Show
Eq FormMessageDefined in yesod-form-1.7.9 · Yesod.Form.TypesRead FormMessageDefined in yesod-form-1.7.9 · Yesod.Form.TypesShow FormMessageDefined in yesod-form-1.7.9 · Yesod.Form.Types
MForm variant stacking a WriterT. The following code example using a monadic form MForm:
formToAForm $ do
(field1F, field1V) <- mreq textField MsgField1 Nothing
(field2F, field2V) <- mreq (checkWith field1F textField) MsgField2 Nothing
(field3F, field3V) <- mreq (checkWith field1F textField) MsgField3 Nothing
return
( MyForm <$> field1F <*> field2F <*> field3F
, [field1V, field2V, field3V]
)Could be rewritten as follows using WForm:
wFormToAForm $ do
field1F <- wreq textField MsgField1 Nothing
field2F <- wreq (checkWith field1F textField) MsgField2 Nothing
field3F <- wreq (checkWith field1F textField) MsgField3 Nothing
return $ MyForm <$> field1F <*> field2F <*> field3FRepresents a value containing all the configuration options for a specific backend. This abstraction makes it easier to write code that can easily swap backends.
Associated types
type family PersistConfigBackend c :: (Type -> Type) -> Type -> Typetype family PersistConfigPool c
Methods
loadConfig :: Value -> Parser cLoad the config settings from a Value, most likely taken from a YAML config file.
applyEnv :: c -> IO cModify the config settings based on environment variables.
createPoolConfig :: c -> IO (PersistConfigPool c)Create a new connection pool based on the given config settings.
runPool :: MonadUnliftIO m => c -> PersistConfigBackend c m a -> PersistConfigPool c -> m aRun a database action by taking a connection from the pool.
Instances1PersistConfig
(PersistConfig c1, PersistConfig c2, PersistConfigPool c1 ~ PersistConfigPool c2, PersistConfigBackend c1 ~ PersistConfigBackend c2) => PersistConfig (Either c1 c2)Defined in persistent-2.14.6.3 · Database.Persist.Class.PersistConfig
Backends supporting conditional read operations.
Methods
selectSourceRes :: (PersistRecordBackend record backend, MonadIO m1, MonadIO m2) => [Filter record] -> [SelectOpt record] -> ReaderT backend m1 (Acquire (ConduitM () (Entity record) m2 ()))Get all records matching the given criterion in the specified order. Returns also the identifiers.
NOTE: This function returns an Acquire and a ConduitM, which implies that it streams from the database. It does not. Please use selectList to simplify the code. If you want streaming behavior, consider
persistent-paginationwhich efficiently chunks a query into ranges, or investigate a backend-specific streaming solution.selectFirst :: (MonadIO m, PersistRecordBackend record backend) => [Filter record] -> [SelectOpt record] -> ReaderT backend m (Maybe (Entity record))Get just the first record for the criterion.
selectKeysRes :: (MonadIO m1, MonadIO m2, PersistRecordBackend record backend) => [Filter record] -> [SelectOpt record] -> ReaderT backend m1 (Acquire (ConduitM () (Key record) m2 ()))Get the Keys of all records matching the given criterion.
count :: (MonadIO m, PersistRecordBackend record backend) => [Filter record] -> ReaderT backend m IntThe total number of records fulfilling the given criterion.
exists :: (MonadIO m, PersistRecordBackend record backend) => [Filter record] -> ReaderT backend m BoolCheck if there is at least one record fulfilling the given criterion.
Instances4PersistQueryRead
PersistQueryRead SqlReadBackendDefined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistQuery · orphanPersistQueryRead SqlWriteBackendDefined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistQuery · orphanPersistQueryRead SqlBackendDefined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistQuery · orphan(HasPersistBackend b, BackendCompatible b s, PersistQueryRead b) => PersistQueryRead (Compatible b s)Defined in persistent-2.14.6.3 · Database.Persist.Compatible.Types
Instances3Read, Show, Lift
Read PersistFilterDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseShow PersistFilterDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseLift PersistFilterDefined in persistent-2.14.6.3 · Database.Persist.Types.Base
class (PersistField (Key record), ToJSON (Key record), FromJSON (Key record), Show (Key record), Read (Key record), Eq (Key record), Ord (Key record)) => PersistEntity record wherePersistent serialized Haskell records to the database. A Database Entity (A row in SQL, a document in MongoDB, etc) corresponds to a Key plus a Haskell record.
For every Haskell record type stored in the database there is a corresponding PersistEntity instance. An instance of PersistEntity contains meta-data for the record. PersistEntity also helps abstract over different record types. That way the same query interface can return a PersistEntity, with each query returning different types of Haskell records.
Some advanced type system capabilities are used to make this process type-safe. Persistent users usually don't need to understand the class associated data and functions.
Associated types
type family PersistEntityBackend recordPersistent allows multiple different backends (databases).
data family Key recordBy default, a backend will automatically generate the key Instead you can specify a Primary key made up of unique values.
data family EntityField record :: Type -> TypeAn EntityField is parameterised by the Haskell record it belongs to and the additional type of that field.
As of
persistent-2.11.0.0, it's possible to use theOverloadedLabelslanguage extension to refer to EntityField values polymorphically. See the documentation on SymbolToField for more information.data family Unique recordUnique keys besides the Key.
Methods
keyToValues :: Key record -> [PersistValue]A lower-level key operation.
keyFromValues :: [PersistValue] -> Either Text (Key record)A lower-level key operation.
persistIdField :: EntityField record (Key record)A meta-operation to retrieve the Key EntityField.
entityDef :: proxy record -> EntityDefRetrieve the EntityDef meta-data for the record.
persistFieldDef :: EntityField record typ -> FieldDefReturn meta-data for a given EntityField.
toPersistFields :: record -> [PersistValue]A meta-operation to get the database fields of a record.
fromPersistValues :: [PersistValue] -> Either Text recordA lower-level operation to convert from database values to a Haskell record.
tabulateEntityA :: Applicative f => (forall a. EntityField record a -> f a) -> f (Entity record)This function allows you to build an
Entity aby specifying an action that returns a value for the field in the callback function. Let's look at an example.parseFromEnvironmentVariables :: IO (Entity User) parseFromEnvironmentVariables = tabulateEntityA $ \userField -> case userField of UserName -> getEnvUSER_NAMEUserAge -> do ageVar <- getEnvUSER_AGEcase readMaybe ageVar of Just age -> pure age Nothing -> error $ "Failed to parse Age from: " <> ageVar UserAddressId -> do addressVar <- getEnvUSER_ADDRESS_IDpure $ AddressKey addressVarpersistUniqueKeys :: record -> [Unique record]A meta operation to retrieve all the Unique keys.
persistUniqueToFieldNames :: Unique record -> NonEmpty (FieldNameHS, FieldNameDB)A lower level operation.
persistUniqueToValues :: Unique record -> [PersistValue]A lower level operation.
fieldLens :: EntityField record field -> forall (f :: Type -> Type). Functor f => (field -> f field) -> Entity record -> f (Entity record)Use a PersistField as a lens.
keyFromRecordM :: Maybe (record -> Key record)Extract a
Key recordfrom arecordvalue. Currently, this is only defined for entities using thePrimarysyntax for natural/composite keys. In a future version ofpersistentwhich incorporates the ID directly into the entity, this will always be Just.
By default, a backend will automatically generate the key Instead you can specify a Primary key made up of unique values.
Instances1RawSql
(PersistEntity a, PersistEntityBackend a ~ backend, IsPersistBackend backend) => RawSql (Key a)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Class
class (Show (BackendKey backend), Read (BackendKey backend), Eq (BackendKey backend), Ord (BackendKey backend), PersistStoreRead backend, PersistField (BackendKey backend), ToJSON (BackendKey backend), FromJSON (BackendKey backend)) => PersistStoreWrite backend whereMethods
insert :: (MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => record -> ReaderT backend m (Key record)Create a new record in the database, returning an automatically created key (in SQL an auto-increment id).
Example usage
Using schema-1 and dataset-1, let's insert a new user
John.insertJohn :: MonadIO m => ReaderT SqlBackend m (Key User) insertJohn = insert $ User "John" 30johnId <- insertJohnThe above query when applied on dataset-1, will produce this:
+-----+------+-----+ |id |name |age | +-----+------+-----+ |1 |SPJ |40 | +-----+------+-----+ |2 |Simon |41 | +-----+------+-----+ |3 |John |30 | +-----+------+-----+insert_ :: (MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => record -> ReaderT backend m ()Same as insert, but doesn't return a
Key.Example usage
insertJohn :: MonadIO m => ReaderT SqlBackend m (Key User) insertJohn = insert_ $ User "John" 30The above query when applied on dataset-1, will produce this:
+-----+------+-----+ |id |name |age | +-----+------+-----+ |1 |SPJ |40 | +-----+------+-----+ |2 |Simon |41 | +-----+------+-----+ |3 |John |30 | +-----+------+-----+insertMany :: (MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => [record] -> ReaderT backend m [Key record]Create multiple records in the database and return their Keys.
If you don't need the inserted Keys, use insertMany_.
The MongoDB and PostgreSQL backends insert all records and retrieve their keys in one database query.
The SQLite and MySQL backends use the slow, default implementation of
mapM insert.Example usage
insertUsers :: MonadIO m => ReaderT SqlBackend m [Key User] insertUsers = insertMany [User "John" 30, User "Nick" 32, User "Jane" 20]userIds <- insertUsersThe above query when applied on dataset-1, will produce this:
+-----+------+-----+ |id |name |age | +-----+------+-----+ |1 |SPJ |40 | +-----+------+-----+ |2 |Simon |41 | +-----+------+-----+ |3 |John |30 | +-----+------+-----+ |4 |Nick |32 | +-----+------+-----+ |5 |Jane |20 | +-----+------+-----+insertMany_ :: (MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => [record] -> ReaderT backend m ()Same as insertMany, but doesn't return any Keys.
The MongoDB, PostgreSQL, SQLite and MySQL backends insert all records in one database query.
Example usage
insertUsers_ :: MonadIO m => ReaderT SqlBackend m () insertUsers_ = insertMany_ [User "John" 30, User "Nick" 32, User "Jane" 20]The above query when applied on dataset-1, will produce this:
+-----+------+-----+ |id |name |age | +-----+------+-----+ |1 |SPJ |40 | +-----+------+-----+ |2 |Simon |41 | +-----+------+-----+ |3 |John |30 | +-----+------+-----+ |4 |Nick |32 | +-----+------+-----+ |5 |Jane |20 | +-----+------+-----+insertEntityMany :: (MonadIO m, PersistRecordBackend record backend) => [Entity record] -> ReaderT backend m ()Same as insertMany_, but takes an Entity instead of just a record.
Useful when migrating data from one entity to another and want to preserve ids.
The MongoDB, PostgreSQL, SQLite and MySQL backends insert all records in one database query.
Example usage
insertUserEntityMany :: MonadIO m => ReaderT SqlBackend m () insertUserEntityMany = insertEntityMany [SnakeEntity, EvaEntity]The above query when applied on dataset-1, will produce this:
+-----+------+-----+ |id |name |age | +-----+------+-----+ |1 |SPJ |40 | +-----+------+-----+ |2 |Simon |41 | +-----+------+-----+ |3 |Snake |38 | +-----+------+-----+ |4 |Eva |38 | +-----+------+-----+insertKey :: (MonadIO m, PersistRecordBackend record backend) => Key record -> record -> ReaderT backend m ()Create a new record in the database using the given key.
Example usage
insertAliceKey :: MonadIO m => Key User -> ReaderT SqlBackend m () insertAliceKey key = insertKey key $ User "Alice" 20insertAliceKey $ UserKey {unUserKey = SqlBackendKey {unSqlBackendKey = 3}}The above query when applied on dataset-1, will produce this:
+-----+------+-----+ |id |name |age | +-----+------+-----+ |1 |SPJ |40 | +-----+------+-----+ |2 |Simon |41 | +-----+------+-----+ |3 |Alice |20 | +-----+------+-----+repsert :: (MonadIO m, PersistRecordBackend record backend) => Key record -> record -> ReaderT backend m ()Put the record in the database with the given key. Unlike replace, if a record with the given key does not exist then a new record will be inserted.
Example usage
We try to explain
upsertByusing schema-1 and dataset-1.First, we insert Philip to dataset-1.
insertPhilip :: MonadIO m => ReaderT SqlBackend m (Key User) insertPhilip = insert $ User "Philip" 42philipId <- 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" 81repsertHaskell philipIdThis query will replace Philip's record with Haskell's one:
+-----+-----------------+--------+ |id |name |age | +-----+-----------------+--------+ |1 |SPJ |40 | +-----+-----------------+--------+ |2 |Simon |41 | +-----+-----------------+--------+ |3 |Philip -> Haskell|42 -> 81| +-----+-----------------+--------+repsert inserts the given record if the key doesn't exist.
repsertXToUnknown :: MonadIO m => ReaderT SqlBackend m () repsertXToUnknown = repsert unknownId $ User "X" 999For example, applying the above query to dataset-1 will produce this:
+-----+------+-----+ |id |name |age | +-----+------+-----+ |1 |SPJ |40 | +-----+------+-----+ |2 |Simon |41 | +-----+------+-----+ |3 |X |999 | +-----+------+-----+repsertMany :: (MonadIO m, PersistRecordBackend record backend) => [(Key record, record)] -> ReaderT backend m ()Put many entities into the database.
Batch version of repsert for SQL backends.
Useful when migrating data from one entity to another and want to preserve ids.
Example usage
repsertManyUsers :: MonadIO m =>ReaderT SqlBackend m () repsertManyusers = repsertMany [(simonId, User "Philip" 20), (unknownId999, User "Mr. X" 999)]The above query when applied on dataset-1, will produce this:
+-----+----------------+---------+ |id |name |age | +-----+----------------+---------+ |1 |SPJ |40 | +-----+----------------+---------+ |2 |Simon -> Philip |41 -> 20 | +-----+----------------+---------+ |999 |Mr. X |999 | +-----+----------------+---------+replace :: (MonadIO m, PersistRecordBackend record backend) => Key record -> record -> ReaderT backend m ()Replace the record in the database with the given key. Note that the result is undefined if such record does not exist, so you must use insertKey or repsert in these cases.
Example usage
With schema-1 schama-1 and dataset-1,
replaceSpj :: MonadIO m => User -> ReaderT SqlBackend m () replaceSpj record = replace spjId recordThe above query when applied on dataset-1, will produce this:
+-----+------+-----+ |id |name |age | +-----+------+-----+ |1 |Mike |45 | +-----+------+-----+ |2 |Simon |41 | +-----+------+-----+delete :: (MonadIO m, PersistRecordBackend record backend) => Key record -> ReaderT backend m ()Delete a specific record by identifier. Does nothing if record does not exist.
Example usage
deleteSpj :: MonadIO m => ReaderT SqlBackend m () deleteSpj = delete spjIdThe above query when applied on dataset-1, will produce this:
+-----+------+-----+ |id |name |age | +-----+------+-----+ |2 |Simon |41 | +-----+------+-----+update :: (MonadIO m, PersistRecordBackend record backend) => Key record -> [Update record] -> ReaderT backend m ()Update individual fields on a specific record.
Example usage
updateSpj :: MonadIO m => [Update User] -> ReaderT SqlBackend m () updateSpj updates = update spjId updatesupdateSpj [UserAge +=. 100]The above query when applied on dataset-1, will produce this:
+-----+------+-----+ |id |name |age | +-----+------+-----+ |1 |SPJ |140 | +-----+------+-----+ |2 |Simon |41 | +-----+------+-----+updateGet :: (MonadIO m, PersistRecordBackend record backend) => Key record -> [Update record] -> ReaderT backend m recordUpdate individual fields on a specific record, and retrieve the updated value from the database.
Note that this function will throw an exception if the given key is not found in the database.
Example usage
updateGetSpj :: MonadIO m => [Update User] -> ReaderT SqlBackend m User updateGetSpj updates = updateGet spjId updatesspj <- updateGetSpj [UserAge +=. 100]The above query when applied on dataset-1, will produce this:
+-----+------+-----+ |id |name |age | +-----+------+-----+ |1 |SPJ |140 | +-----+------+-----+ |2 |Simon |41 | +-----+------+-----+
Instances3PersistStoreWrite
PersistStoreWrite SqlWriteBackendDefined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanPersistStoreWrite SqlBackendDefined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphan(HasPersistBackend b, BackendCompatible b s, PersistStoreWrite b) => PersistStoreWrite (Compatible b s)Defined in persistent-2.14.6.3 · Database.Persist.Compatible.Types
Constructors
DBRunnerrunDBRunner :: forall a. YesodDB site a -> HandlerFor site a
Associated types
type family YesodPersistBackend site
Methods
runDB :: YesodDB site a -> HandlerFor site aAllows you to execute database actions within Yesod Handlers. For databases that support it, code inside the action will run as an atomic transaction.
Example Usage
userId <- runDB $ do userId <- insert $ User "username" "email@example.com" insert_ $ UserPreferences userId True pure userId
Since 1.2.0
Methods
getDBRunner :: HandlerFor site (DBRunner site, HandlerFor site ())This function differs from runDB in that it returns a database runner function, as opposed to simply running a single action. This will usually mean that a connection is taken from a pool and then reused for each invocation. This can be useful for creating streaming responses; see runDBSource.
It additionally returns a cleanup function to free the connection. If your code finishes successfully, you must call this cleanup to indicate changes should be committed. Otherwise, for SQL backends at least, a rollback will be used instead.
Since 1.2.0
Helper for implementing getDBRunner.
Since 1.2.0
Helper for creating runDB.
Since 1.2.0
Get the given entity by ID, or return a 404 not found if it doesn't exist.
Get the given entity by unique key, or return a 404 not found if it doesn't exist.
Create a new record in the database, returning an automatically created key, or raise a 400 bad request if a uniqueness constraint is violated.
Same as insert400, but doesn’t return a key.
Extends respondSource to create a streaming database response body.
Like runDB, but transforms a Source. See respondSourceDB for an
example, practical use case.
Since 1.2.0
Non-equality check.
Examples
selectSimon :: MonadIO m => ReaderT SqlBackend m [Entity User]
selectSimon = selectList [UserName !=. "SPJ" ] []
The above query when applied on dataset-1, will produce this:
+-----+-----+-----+
|id |name |age |
+-----+-----+-----+
|2 |Simon|41 |
+-----+-----+-----+Assign a field by multiplication (*=).
Examples
multiplyAge :: MonadIO m => ReaderT SqlBackend m ()
multiplyAge = updateWhere [UserName ==. "SPJ" ] [UserAge *=. 2]
The above query when applied on dataset-1, will produce this:
+-----+-----+--------+
|id |name |age |
+-----+-----+--------+
|1 |SPJ |40 -> 80|
+-----+-----+--------+
|2 |Simon|41 |
+-----+-----+--------+Assign a field by addition (+=).
Examples
addAge :: MonadIO m => ReaderT SqlBackend m ()
addAge = updateWhere [UserName ==. "SPJ" ] [UserAge +=. 1]
The above query when applied on dataset-1, will produce this:
+-----+-----+---------+
|id |name |age |
+-----+-----+---------+
|1 |SPJ |40 -> 41 |
+-----+-----+---------+
|2 |Simon|41 |
+-----+-----+---------+Assign a field by subtraction (-=).
Examples
subtractAge :: MonadIO m => ReaderT SqlBackend m ()
subtractAge = updateWhere [UserName ==. "SPJ" ] [UserAge -=. 1]
The above query when applied on dataset-1, will produce this:
+-----+-----+---------+
|id |name |age |
+-----+-----+---------+
|1 |SPJ |40 -> 39 |
+-----+-----+---------+
|2 |Simon|41 |
+-----+-----+---------+Check if value is not in given list.
Examples
selectSimon :: MonadIO m => ReaderT SqlBackend m [Entity User]
selectSimon = selectList [UserAge /<-. [40]] []
The above query when applied on dataset-1, will produce this:
+-----+-----+-----+
|id |name |age |
+-----+-----+-----+
|2 |Simon|41 |
+-----+-----+-----+Assign a field by division (/=).
Examples
divideAge :: MonadIO m => ReaderT SqlBackend m ()
divideAge = updateWhere [UserName ==. "SPJ" ] [UserAge /=. 2]
The above query when applied on dataset-1, will produce this:
+-----+-----+---------+
|id |name |age |
+-----+-----+---------+
|1 |SPJ |40 -> 20 |
+-----+-----+---------+
|2 |Simon|41 |
+-----+-----+---------+Check if value is in given list.
Examples
selectUsers :: MonadIO m => ReaderT SqlBackend m [Entity User]
selectUsers = selectList [UserAge <-. [40, 41]] []
The above query when applied on 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-1, will produce this:
+-----+-----+-----+
|id |name |age |
+-----+-----+-----+
|1 |SPJ |40 |
+-----+-----+-----+Less-than check.
Examples
selectLessAge :: MonadIO m => ReaderT SqlBackend m [Entity User]
selectLessAge = selectList [UserAge <. 41 ] []
The above query when applied on dataset-1, will produce this:
+-----+-----+-----+
|id |name |age |
+-----+-----+-----+
|1 |SPJ |40 |
+-----+-----+-----+Less-than or equal check.
Examples
selectLessEqualAge :: MonadIO m => ReaderT SqlBackend m [Entity User]
selectLessEqualAge = selectList [UserAge <=. 40 ] []
The above query when applied on dataset-1, will produce this:
+-----+-----+-----+
|id |name |age |
+-----+-----+-----+
|1 |SPJ |40 |
+-----+-----+-----+Assign a field a value.
Examples
updateAge :: MonadIO m => ReaderT SqlBackend m ()
updateAge = updateWhere [UserName ==. "SPJ" ] [UserAge =. 45]
Similar to updateWhere 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 updateWhere is [Filter val] and second parameter is [Update val]. By comparing this with the type of ==. and =., you can see that they match up in the above usage.
The above query when applied on dataset-1, will produce this:
+-----+-----+--------+
|id |name |age |
+-----+-----+--------+
|1 |SPJ |40 -> 45|
+-----+-----+--------+
|2 |Simon|41 |
+-----+-----+--------+Check for equality.
Examples
selectSPJ :: MonadIO m => ReaderT SqlBackend m [Entity User]
selectSPJ = selectList [UserName ==. "SPJ" ] []
The above query when applied on dataset-1, will produce this:
+-----+-----+-----+
|id |name |age |
+-----+-----+-----+
|1 |SPJ |40 |
+-----+-----+-----+Greater-than check.
Examples
selectGreaterAge :: MonadIO m => ReaderT SqlBackend m [Entity User]
selectGreaterAge = selectList [UserAge >. 40 ] []
The above query when applied on dataset-1, will produce this:
+-----+-----+-----+
|id |name |age |
+-----+-----+-----+
|2 |Simon|41 |
+-----+-----+-----+Greater-than or equal check.
Examples
selectGreaterEqualAge :: MonadIO m => ReaderT SqlBackend m [Entity User]
selectGreaterEqualAge = selectList [UserAge >=. 41 ] []
The above query when applied on dataset-1, will produce this:
+-----+-----+-----+
|id |name |age |
+-----+-----+-----+
|2 |Simon|41 |
+-----+-----+-----+FIXME What's this exactly?
Convert list of PersistValues into textual representation of JSON object. This is a type-constrained synonym for toJsonText.
Convert map (list of tuples) into textual representation of JSON object. This is a type-constrained synonym for toJsonText.
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 or 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).
Predefined parseJSON. The input JSON looks like
{"id": 1, "name": ...}.
The typical usage is:
instance FromJSON (Entity User) where
parseJSON = entityIdFromJSON
Predefined toJSON. The resulting JSON looks like
{"id": 1, "name": ...}.
The typical usage is:
instance ToJSON (Entity User) where
toJSON = entityIdToJSON
Get list of values corresponding to given entity.
Convenience function for getting a free PersistField instance from a type with JSON instances. The JSON parser used will accept JSON values other that object and arrays. So, if your instance serializes the data to a JSON string, this will still work.
Example usage in combination with toPersistValueJSON:
instance PersistField MyData where
fromPersistValue = fromPersistValueJSON
toPersistValue = toPersistValueJSON
Predefined parseJSON. The input JSON looks like
{"key": 1, "value": {"name": ...}}.
The typical usage is:
instance FromJSON (Entity User) where
parseJSON = keyValueEntityFromJSON
Predefined toJSON. The resulting JSON looks like
{"key": 1, "value": {"name": ...}}.
The typical usage is:
instance ToJSON (Entity User) where
toJSON = keyValueEntityToJSON
Construct an Entity record by providing a value for each of the
record's fields.
These constructions are equivalent:
entityMattConstructor, entityMattTabulate :: Entity User
entityMattConstructor =
Entity
{ entityKey = toSqlKey 123
, entityVal =
User
{ userName = Matt
, userAge = 33
}
}
entityMattTabulate =
tabulateEntity $ \case
UserId ->
toSqlKey 123
UserName ->
Matt
UserAge ->
33
This is a specialization of tabulateEntityA, which allows you to construct an Entity by providing an Applicative action for each field instead of a regular function.
Convenience function for getting a free PersistField instance from a type with JSON instances.
Example usage in combination with fromPersistValueJSON:
instance PersistField MyData where
fromPersistValue = fromPersistValueJSON
toPersistValue = toPersistValueJSON
FIXME Add documentation to that.
Get the Keys of all records matching the given criterion.
For an example, see selectList.
Call selectKeys but return the result as a list.
Returns a [Entity record] corresponding to the filters and options
provided.
Filters are constructed using the operators defined in Database.Persist (and re-exported from Database.Persist.Sql). Let's look at some examples:
usersWithAgeOver40 :: SqlPersistT IO [Entity User]
usersWithAgeOver40 =
selectList [UserAge >=. 40] []
If you provide multiple values in the list, the conditions are ANDed
together.
usersWithAgeBetween30And50 :: SqlPersistT IO [Entity User]
usersWithAgeBetween30And50 =
selectList
[ UserAge >=. 30
, UserAge <=. 50
]
[]
The second list contains the SelectOpt for a record. We can select the first ten records with LimitTo
firstTenUsers =
selectList [] [LimitTo 10]
And we can select the second ten users with OffsetBy.
secondTenUsers =
selectList [] [LimitTo 10, OffsetBy 10]
Warning that LIMIT/OFFSET is bad for pagination!
The type of record can usually be infered from the types of the provided filters and select options. In the previous two examples, though, you'll notice that the select options are polymorphic, applying to any record type. In order to help type inference in such situations, or simply as an enhancement to readability, you might find type application useful, illustrated below.
{-# LANGUAGE TypeApplications #-}
...
firstTenUsers =
selectList User [] [LimitTo 10]
secondTenUsers =
selectList User [] [LimitTo 10, OffsetBy 10]
With Asc and Desc, we can provide the field we want to sort on. We can provide multiple sort orders - later ones are used to sort records that are equal on the first field.
newestUsers =
selectList [] [Desc UserCreatedAt, LimitTo 10]
oldestUsers =
selectList [] [Asc UserCreatedAt, LimitTo 10]
Get all records matching the given criterion in the specified order. Returns also the identifiers.
WARNING: This function returns a ConduitM, which suggests that it streams
the results. It does not stream results on most backends. If you need
streaming, see persistent-pagination for a means of chunking results based
on indexed ranges.
Curry this to make a convenience function that loads an associated model.
foreign = belongsTo foreignIdSame as belongsTo, but uses getJust and therefore is similarly unsafe.
Like get, but returns the complete Entity.
Example usage
getSpjEntity :: MonadIO m => ReaderT SqlBackend m (Maybe (Entity User))
getSpjEntity = getEntity spjIdmSpjEnt <- getSpjEntityThe above query when applied on dataset-1, will get this entity:
+----+------+-----+
| id | name | age |
+----+------+-----+
| 1 | SPJ | 40 |
+----+------+-----+Same as get, but for a non-null (not Maybe) foreign key. Unsafe unless your database is enforcing that the foreign key is valid.
Example usage
getJustSpj :: MonadIO m => ReaderT SqlBackend m User
getJustSpj = getJust spjIdspj <- getJust spjIdThe above query when applied on dataset-1, will get this record:
+----+------+-----+
| id | name | age |
+----+------+-----+
| 1 | SPJ | 40 |
+----+------+-----+getJustUnknown :: MonadIO m => ReaderT SqlBackend m User
getJustUnknown = getJust unknownIdmrx <- getJustUnknown
This just throws an error.
Same as getJust, but returns an Entity instead of just the record.
Example usage
getJustEntitySpj :: MonadIO m => ReaderT SqlBackend m (Entity User)
getJustEntitySpj = getJustEntity spjIdspjEnt <- getJustEntitySpjThe above query when applied on dataset-1, will get this entity:
+----+------+-----+
| id | name | age |
+----+------+-----+
| 1 | SPJ | 40 |
+----+------+-----+Like insert, but returns the complete Entity.
Example usage
insertHaskellEntity :: MonadIO m => ReaderT SqlBackend m (Entity User)
insertHaskellEntity = insertEntity $ User "Haskell" 81haskellEnt <- insertHaskellEntityThe above query when applied on dataset-1, will produce this:
+----+---------+-----+
| id | name | age |
+----+---------+-----+
| 1 | SPJ | 40 |
+----+---------+-----+
| 2 | Simon | 41 |
+----+---------+-----+
| 3 | Haskell | 81 |
+----+---------+-----+Like insertEntity but just returns the record instead of Entity.
Example usage
insertDaveRecord :: MonadIO m => ReaderT SqlBackend m User
insertDaveRecord = insertRecord $ User "Dave" 50dave <- insertDaveRecordThe above query when applied on dataset-1, will produce this:
+-----+------+-----+
|id |name |age |
+-----+------+-----+
|1 |SPJ |40 |
+-----+------+-----+
|2 |Simon |41 |
+-----+------+-----+
|3 |Dave |50 |
+-----+------+-----+Run a query against a larger backend by plucking out BaseBackend backend
This is a helper for reusing existing queries when expanding the backend type.
Run a query against a compatible backend, by projecting the backend
This is a helper for using queries which run against a specific backend type that your backend is compatible with.
Check whether there are any conflicts for unique keys with this entity and existing entities in the database.
Returns Nothing if the entity would be unique, and could thus safely be inserted. on a conflict returns the conflicting key
Example usage
We use schema-1 and dataset-1 here.
This would be Nothing:
mAlanConst <- checkUnique $ User "Alan" 70While this would be Just because SPJ already exists:
mSpjConst <- checkUnique $ User "SPJ" 60Check whether there are any conflicts for unique keys with this entity and existing entities in the database.
Returns Nothing if the entity would stay unique, and could thus safely be updated. on a conflict returns the conflicting key
This is similar to checkUnique, except it's useful for updating - when the particular entity already exists, it would normally conflict with itself. This variant ignores those conflicts
Example usage
We use schema-1 and dataset-1 here.
This would be Nothing:
mAlanConst <- checkUnique $ User "Alan" 70While this would be Just because SPJ already exists:
mSpjConst <- checkUnique $ User "SPJ" 60A modification of getBy, which takes the PersistEntity itself instead of a Unique record. Returns a record matching one of the unique keys. This function makes the most sense on entities with a single Unique constructor.
Example usage
getBySpjValue :: MonadIO m => ReaderT SqlBackend m (Maybe (Entity User))
getBySpjValue = getByValue $ User SPJ 999
mSpjEnt <- getBySpjValueThe above query when applied on dataset-1, will get this record:
+----+------+-----+
| id | name | age |
+----+------+-----+
| 1 | SPJ | 40 |
+----+------+-----+Insert a value, checking for conflicts with any unique constraints. If a duplicate exists in the database, it is returned as Left. Otherwise, the new 'Key is returned as Right.
Example usage
With schema-2 and dataset-1, we have following lines of code:
l1 <- insertBy $ User "SPJ" 20
l2 <- insertBy $ User "XXX" 41
l3 <- insertBy $ User "SPJ" 40
r1 <- insertBy $ User "XXX" 100First three lines return Left because there're duplicates in given record's uniqueness constraints. While the last line returns a new key as Right.
Like insertEntity, but returns Nothing when the record couldn't be inserted because of a uniqueness constraint.
Example usage
We use schema-2 and dataset-1 here.
insertUniqueSpjEntity :: MonadIO m => ReaderT SqlBackend m (Maybe (Entity User))
insertUniqueSpjEntity = insertUniqueEntity $ User "SPJ" 50mSpjEnt <- insertUniqueSpjEntityThe above query results Nothing as SPJ already exists.
insertUniqueAlexaEntity :: MonadIO m => ReaderT SqlBackend m (Maybe (Entity User))
insertUniqueAlexaEntity = insertUniqueEntity $ User "Alexa" 3mAlexaEnt <- insertUniqueSpjEntityBecause there's no such unique keywords of the given record, the above query when applied on dataset-1, will produce this:
+----+-------+-----+
| id | name | age |
+----+-------+-----+
| 1 | SPJ | 40 |
+----+-------+-----+
| 2 | Simon | 41 |
+----+-------+-----+
| 3 | Alexa | 3 |
+----+-------+-----+Given a proxy for a PersistEntity record, this returns the sole UniqueDef for that entity.
Return the single unique key for a record.
Example usage
We use shcema-1 and dataset-1 here.
onlySimonConst :: MonadIO m => ReaderT SqlBackend m (Unique User)
onlySimonConst = onlyUnique $ User "Simon" 999mSimonConst <- onlySimonConstmSimonConst 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.
Return the database name for the given entity.
Retrieve the list of FieldDef that makes up the fields of the entity.
This does not return the fields for an Id column or an implicit id. 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 getEntityFieldsDatabase.
This returns all of the FieldDef defined for the EntityDef, including
those fields that are marked as MigrationOnly (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 getEntityFields.
Retrieve the Haskell name of the given entity.
Retrieve the list of UniqueDef from an EntityDef. As of version 2.14, this will also include the primary key on the entity, if one is defined. If you do not want the primary key, see getEntityUniquesNoPrimaryKey.
Perform a mapping function over all of the entity fields, as determined by getEntityFieldsDatabase.
Add an attribute to the list of field attributes.
Check if the field is `Maybe a`
Check if the field definition is nullable
Modify the list of field attributes.
Automatically creates a valid PersistField instance for any datatype that has valid Show and Read instances. Can be very convenient for Enum types.
Automatically creates a valid PersistField instance for any datatype
that has valid ToJSON and FromJSON 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
Splice in a list of all EntityDef in scope. This is useful when running mkPersist to ensure that all entity definitions are available for setting foreign keys, and for performing migrations with all entities available.
mkPersist has the type MkPersistSettings -> [EntityDef] -> DecsQ. So, to
account for entities defined elsewhere, you'll mappend $(discoverEntities).
For example,
share
[ mkPersistWith sqlSettings $(discoverEntities)
]
[persistLowerCase| ... |]
Likewise, to run migrations with all entity instances in scope, you'd write:
migrateAll = migrateModels $(discoverEntities)
Note that there is some odd behavior with Template Haskell and splicing
groups. If you call discoverEntities in the same module that defines
PersistEntity instances, you need to ensure they are in different top-level
binding groups. You can write $(pure []) at the top level to do this.
-- Foo and Bar both export an instance of PersistEntity
import Foo
import Bar
-- Since Foo and Bar are both imported, discoverEntities can find them here.
mkPersistWith sqlSettings $(discoverEntities) [persistLowerCase|
User
name Text
age Int
|]
-- onlyFooBar is defined in the same 'top level group' as the above generated
-- instance for User, so it isn't present in this list.
onlyFooBar :: [EntityDef]
onlyFooBar = $(discoverEntities)
-- We can manually create a new binding group with this, which splices an
-- empty list of declarations in.
$(pure [])
-- fooBarUser is able to see the User instance.
fooBarUser :: [EntityDef]
fooBarUser = $(discoverEntities)
Takes a list of (potentially) independently defined entities and properly links all foreign keys to reference the right EntityDef, 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 Migration.
Render an error message based on the tableName and fieldName with
the provided message.
The basic function for migrating models, no Template Haskell required.
It's probably best to use this in concert with mkEntityDefList, and then call migrateModels with the result from that function.
share [mkPersist sqlSettings, mkEntityDefList "entities"] [persistLowerCase| ... |]
migrateAll = migrateModels entities
The function mkMigrate 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 migrateModels.
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)
mkEntityDefList :: StringThe name that will be given to the EntityDef list.
-> [UnboundEntityDef]-> Q [Dec]
Creates a declaration for the [EntityDef] 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 share, much like mkMigrate.
share [mkMigrate "migrateAll", mkEntityDefList "entityDefs"] [...]
Creates 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 mkEntityDefList to get the correct entities.
This avoids problems where the QuasiQuoter is unable to know what the right
reference types are. This sets mkPersist to be the "single source of truth"
for entity definitions.
Create data types and appropriate PersistEntity instances for the given UnboundEntityDefs.
This function should be used if you are only defining a single block of Persistent models for the entire application. If you intend on defining multiple blocks in different fiels, see mkPersistWith which allows you to provide existing entity definitions so foreign key references work.
Example:
mkPersist sqlSettings [persistLowerCase|
User
name Text
age Int
Dog
name Text
owner UserId
|]
Example from a file:
mkPersist sqlSettings $(persistFileWith lowerCaseSettings "models.persistentmodels")
For full information on the QuasiQuoter syntax, see Database.Persist.Quasi documentation.
Create an MkPersistSettings with default values.
Like mkPersist, but allows you to provide a [EntityDef]
representing the predefined entities. This function will include those
EntityDef when looking for foreign key references.
You should use this if you intend on defining Persistent models in multiple files.
Suppose we define a table Foo which has no dependencies.
module DB.Foo where
mkPersistWith sqlSettings [] [persistLowerCase|
Foo
name Text
|]
Then, we define a table Bar which depends on Foo:
module DB.Bar where
import DB.Foo
mkPersistWith sqlSettings [entityDef (Proxy :: Proxy Foo)] [persistLowerCase|
Bar
fooId FooId
|]
Writing out the list of EntityDef can be annoying. The
$(discoverEntities) shortcut will work to reduce this boilerplate.
module DB.Quux where
import DB.Foo
import DB.Bar
mkPersistWith sqlSettings $(discoverEntities) [persistLowerCase|
Quux
name Text
fooId FooId
barId BarId
|]
Calls parse to Quasi.parse individual entities in isolation afterwards, sets references to other entities
In 2.13.0.0, this was changed to splice in [UnboundEntityDef]
instead of [EntityDef].
Produce code similar to the following:
instance PersistEntity e => PersistField e where
toPersistValue = entityToPersistValueHelper
fromPersistValue = entityFromPersistValueHelper ["col1", "col2"]
sqlType _ = SqlString
Same as persistWith, but uses an external file instead of a
quasiquotation. The recommended file extension is .persistentmodels.
Apply persistWith to lowerCaseSettings.
Same as persistFileWith, 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.
Examples
Split your Persistent definitions into multiple files (models1, models2),
then create a new module for each new file and run mkPersist there:
-- Model1.hs
share
[mkPersist sqlSettings]
$(persistFileWith lowerCaseSettings "models1")
-- Model2.hs
share
[mkPersist sqlSettings]
$(persistFileWith lowerCaseSettings "models2")
Use persistManyFileWith to create your migrations:
-- Migrate.hs
mkMigrate "migrateAll"
$(persistManyFileWith lowerCaseSettings ["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 persistent#778 and persistent#791 for more details.
Apply persistWith to upperCaseSettings.
Converts a quasi-quoted syntax into a list of entity definitions, to be used as input to the template haskell generation code (mkPersist).
Returns True if the key definition has less than 2 fields.
Set the ImplicitIdDef in the given MkPersistSettings. The default value is autoIncrementingInteger.
Use the SqlPersist backend.
Return the [FieldDef] for the entity keys.
A FieldCascade that does nothing.
Parse raw field attributes into structured form. Any unrecognized attributes will be preserved, identically as they are encountered, as FieldAttrOther values.
Render a CascadeAction to Text such that it can be used in a SQL command.
Renders a FieldCascade value such that it can be used in SQL migrations.
A backwards-compatible alias for those that don't care about distinguishing between read and write queries. It signifies the assumption that, by default, a backend can write as well as read.
A backwards-compatible alias for those that don't care about distinguishing between read and write queries. It signifies the assumption that, by default, a backend can write as well as read.
A backwards-compatible alias for those that don't care about distinguishing between read and write queries. It signifies the assumption that, by default, a backend can write as well as read.
Instances1PersistConfigBackend
type PersistConfigBackend (Either c1 c2) = PersistConfigBackend c1Defined in persistent-2.14.6.3 · Database.Persist.Class.PersistConfig
Instances1PersistConfigPool
type PersistConfigPool (Either c1 c2) = PersistConfigPool c1Defined in persistent-2.14.6.3 · Database.Persist.Class.PersistConfig
Instances3Read, Show, Lift
Read PersistUpdateDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseShow PersistUpdateDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseLift PersistUpdateDefined in persistent-2.14.6.3 · Database.Persist.Types.Base
Datatype that represents an entity, with both its Key and its Haskell record representation.
When using a SQL-based backend (such as SQLite or
PostgreSQL), an Entity 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 Entity, 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
rawSql (from the
Database.Persist.Sql 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.
Instances10Eq, Ord, Read, Show, Generic, SafeToInsert, …
(Eq (Key record), Eq record) => Eq (Entity record)Defined in persistent-2.14.6.3 · Database.Persist.Class.PersistEntity(Ord (Key record), Ord record) => Ord (Entity record)Defined in persistent-2.14.6.3 · Database.Persist.Class.PersistEntity(Read (Key record), Read record) => Read (Entity record)Defined in persistent-2.14.6.3 · Database.Persist.Class.PersistEntity(Show (Key record), Show record) => Show (Entity record)Defined in persistent-2.14.6.3 · Database.Persist.Class.PersistEntity(Generic (Key record), Generic record) => Generic (Entity record)Defined in persistent-2.14.6.3 · Database.Persist.Class.PersistEntityTypeError (EntityErrorMessage a) => SafeToInsert (Entity a)Defined in persistent-2.14.6.3 · Database.Persist.Class.PersistEntity(PersistEntity record, PersistField record, PersistField (Key record)) => PersistField (Entity record)Defined in persistent-2.14.6.3 · Database.Persist.Class.PersistEntity(PersistField record, PersistEntity record) => PersistFieldSql (Entity record)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Class(PersistEntity record, PersistEntityBackend record ~ backend, IsPersistBackend backend) => RawSql (Entity record)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Classtype Rep (Entity record) = D1 ('MetaDataDefined in persistent-2.14.6.3 · Database.Persist.Class.PersistEntity"Entity"
"Database.Persist.Class.PersistEntity"
"persistent-2.14.6.3-31NeHlMbZ2g6XoXmn516lt"
'False) (C1 ('MetaCons"Entity"
'PrefixI 'True) (S1 ('MetaSel ('Just"entityKey"
) 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 (Key record)) :*: S1 ('MetaSel ('Just"entityVal"
) 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 record)))
An EntityField is parameterised by the Haskell record it belongs to and the additional type of that field.
As of persistent-2.11.0.0, it's possible to use the OverloadedLabels
language extension to refer to EntityField values polymorphically. See
the documentation on SymbolToField for more information.
Instances1IsLabel
SymbolToField sym rec typ => IsLabel sym (EntityField rec typ)Defined in persistent-2.14.6.3 · Database.Persist.Class.PersistEntityThis instance delegates to SymbolToField to provide
OverloadedLabelssupport to the EntityField type.
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.
Persistent users use combinators to create these.
Note that it's important to be careful about the PersistFilter that you are using, if you use this directly. For example, using the In PersistFilter requires that you have an array- or list-shaped EntityField. It is possible to construct values using this that will create malformed runtime values.
Constructors
forall typ. PersistField typ => FilterfilterField :: EntityField record typfilterValue :: FilterValue typfilterFilter :: PersistFilter
FilterAnd [Filter record]convenient for internal use, not needed for the API
FilterOr [Filter record]BackendFilter (BackendSpecificFilter (PersistEntityBackend record) record)
Value to filter with. Highly dependant on the type of filter used.
Constructors
FilterValue :: typ -> FilterValue typFilterValues :: [typ] -> FilterValue typUnsafeValue :: PersistField a => a -> FilterValue typ
Persistent allows multiple different backends (databases).
Unique keys besides the Key.
A type class which is used to witness that a type is safe to insert into the database without providing a primary key.
The TemplateHaskell function mkPersist will generate instances of this
class for any entity that it works on. If the entity has a default primary
key, then it provides a regular instance. If the entity has a Primary
natural key, then this works fine. But if the entity has an Id column with
no default=, then this does a TypeError and forces the user to use
insertKey.
Instances2SafeToInsert
TypeError (EntityErrorMessage a) => SafeToInsert (Entity a)Defined in persistent-2.14.6.3 · Database.Persist.Class.PersistEntityTypeError (FunctionErrorMessage a b) => SafeToInsert (a -> b)Defined in persistent-2.14.6.3 · Database.Persist.Class.PersistEntity
Query options.
Persistent users use these directly.
Constructors
forall typ. Asc (EntityField record typ)forall typ. Desc (EntityField record typ)OffsetBy IntLimitTo Int
This type class is used with the OverloadedLabels extension to
provide a more convenient means of using the EntityField type.
EntityField definitions are prefixed with the type name to avoid
ambiguity, but this ambiguity can result in verbose code.
If you have a table User with a name Text field, then the
corresponding EntityField is UserName. With this, we can write
#name :: EntityField User Text.
What's more fun is that the type is more general: it's actually
#name
:: (SymbolToField "name" rec typ)
=> EntityField rec typ
Which means it is *polymorphic* over the actual record. This allows you to write code that can be generic over the tables, provided they have the right fields.
Methods
symbolToField :: EntityField rec typ
Updating a database entity.
Persistent users use combinators to create these.
Constructors
forall typ. PersistField typ => UpdateupdateField :: EntityField record typupdateValue :: typupdateUpdate :: PersistUpdate
BackendUpdate (BackendSpecificUpdate (PersistEntityBackend record) record)
Prior to persistent-2.11.0, we provided an instance of
PersistField for the Natural type. This was in error, because
Natural represents an infinite value, and databases don't have
reasonable types for this.
The instance for Natural used the Int64 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 Word 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.
Constructors
Instances6Eq, Num, Ord, Show, PersistField, PersistFieldSql
Eq OverflowNaturalDefined in persistent-2.14.6.3 · Database.Persist.Class.PersistFieldNum OverflowNaturalDefined in persistent-2.14.6.3 · Database.Persist.Class.PersistFieldOrd OverflowNaturalDefined in persistent-2.14.6.3 · Database.Persist.Class.PersistFieldShow OverflowNaturalDefined in persistent-2.14.6.3 · Database.Persist.Class.PersistFieldPersistField OverflowNaturalDefined in persistent-2.14.6.3 · Database.Persist.Class.PersistFieldPersistFieldSql OverflowNaturalDefined in persistent-2.14.6.3 · Database.Persist.Sql.ClassThis type uses the SqlInt64 version, which will exhibit overflow and underflow behavior. Additionally, it permits negative values in the database, which isn't ideal.
This class teaches Persistent how to take a custom type and marshal it to and from a PersistValue, allowing it to be stored in a database.
Examples
Simple Newtype
You can use newtype to add more type safety/readability to a basis type like ByteString. In these cases, just derive PersistField and PersistFieldSql:
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
newtype HashedPassword = HashedPassword ByteString
deriving (Eq, Show, PersistField, PersistFieldSql)
Smart Constructor Newtype
In this example, we create a PersistField instance for a newtype following the "Smart Constructor" pattern.
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
import qualified Data.Text as T
import qualified Data.Char as C
-- | An American Social Security Number
newtype SSN = SSN Text
deriving (Eq, Show, PersistFieldSql)
mkSSN :: Text -> Either Text SSN
mkSSN t = if (T.length t == 9) && (T.all C.isDigit t)
then Right $ SSN t
else Left $ "Invalid SSN: " <> t
instance PersistField SSN where
toPersistValue (SSN t) = PersistText t
fromPersistValue (PersistText t) = mkSSN t
-- Handle cases where the database does not give us PersistText
fromPersistValue x = Left $ "File.hs: When trying to deserialize an SSN: expected PersistText, received: " <> T.pack (show x)
Tips:
This file contain dozens of PersistField instances you can look at for examples.
Typically custom PersistField instances will only accept a single PersistValue constructor in fromPersistValue.
Internal PersistField instances accept a wide variety of PersistValues 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
PersistFieldSqlto specify the type of the database column.
Methods
toPersistValue :: a -> PersistValuefromPersistValue :: PersistValue -> Either Text a
Instances39PersistField, …
TypeError ((((('TextDefined in persistent-2.14.6.3 · Database.Persist.Class.PersistField"The instance of PersistField for the Natural type was removed."
':$$: 'Text"Please see the documentation for OverflowNatural if you want to "
) ':$$: 'Text"continue using the old behavior or want to see documentation on "
) ':$$: 'Text"why the instance was removed."
) ':$$: 'Text""
) ':$$: 'Text"This error instance will be removed in a future release."
) => PersistField NaturalPersistField HtmlDefined in persistent-2.14.6.3 · Database.Persist.Class.PersistFieldPersistField ByteStringDefined in persistent-2.14.6.3 · Database.Persist.Class.PersistFieldPersistField Int16Defined in persistent-2.14.6.3 · Database.Persist.Class.PersistFieldPersistField Int32Defined in persistent-2.14.6.3 · Database.Persist.Class.PersistFieldPersistField Int64Defined in persistent-2.14.6.3 · Database.Persist.Class.PersistFieldPersistField Int8Defined in persistent-2.14.6.3 · Database.Persist.Class.PersistFieldPersistField RationalDefined in persistent-2.14.6.3 · Database.Persist.Class.PersistFieldPersistField Word16Defined in persistent-2.14.6.3 · Database.Persist.Class.PersistFieldPersistField Word32Defined in persistent-2.14.6.3 · Database.Persist.Class.PersistFieldPersistField Word64Defined in persistent-2.14.6.3 · Database.Persist.Class.PersistFieldPersistField Word8Defined in persistent-2.14.6.3 · Database.Persist.Class.PersistFieldPersistField BoolDefined in persistent-2.14.6.3 · Database.Persist.Class.PersistFieldPersistField DoubleDefined in persistent-2.14.6.3 · Database.Persist.Class.PersistFieldPersistField IntDefined in persistent-2.14.6.3 · Database.Persist.Class.PersistFieldPersistField WordDefined in persistent-2.14.6.3 · Database.Persist.Class.PersistFieldPersistField OverflowNaturalDefined in persistent-2.14.6.3 · Database.Persist.Class.PersistFieldPersistField PersistValueDefined in persistent-2.14.6.3 · Database.Persist.Class.PersistFieldPersistField CheckmarkDefined in persistent-2.14.6.3 · Database.Persist.Class.PersistFieldPersistField TextDefined in persistent-2.14.6.3 · Database.Persist.Class.PersistFieldPersistField TextDefined in persistent-2.14.6.3 · Database.Persist.Class.PersistFieldPersistField DayDefined in persistent-2.14.6.3 · Database.Persist.Class.PersistFieldPersistField UTCTimeDefined in persistent-2.14.6.3 · Database.Persist.Class.PersistFieldPersistField TimeOfDayDefined in persistent-2.14.6.3 · Database.Persist.Class.PersistFieldPersistField TextareaDefined in yesod-form-1.7.9 · Yesod.Form.FieldsPersistField (BackendKey SqlReadBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanPersistField (BackendKey SqlWriteBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanPersistField (BackendKey SqlBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanPersistField [Char]Defined in persistent-2.14.6.3 · Database.Persist.Class.PersistFieldPersistField a => PersistField (Maybe a)Defined in persistent-2.14.6.3 · Database.Persist.Class.PersistFieldPersistField a => PersistField (Vector a)Defined in persistent-2.14.6.3 · Database.Persist.Class.PersistFieldPersistField a => PersistField [a]Defined in persistent-2.14.6.3 · Database.Persist.Class.PersistFieldPersistField v => PersistField (IntMap v)Defined in persistent-2.14.6.3 · Database.Persist.Class.PersistField(Ord a, PersistField a) => PersistField (Set a)Defined in persistent-2.14.6.3 · Database.Persist.Class.PersistField(PersistEntity record, PersistField record, PersistField (Key record)) => PersistField (Entity record)Defined in persistent-2.14.6.3 · Database.Persist.Class.PersistEntity(BackendCompatible b s, PersistField (BackendKey b)) => PersistField (BackendKey (Compatible b s))Defined in persistent-2.14.6.3 · Database.Persist.Compatible.TypesHasResolution a => PersistField (Fixed a)Defined in persistent-2.14.6.3 · Database.Persist.Class.PersistFieldPersistField v => PersistField (Map Text v)Defined in persistent-2.14.6.3 · Database.Persist.Class.PersistField(PersistField a, PersistField b) => PersistField (a, b)Defined in persistent-2.14.6.3 · Database.Persist.Class.PersistField
class (PersistQueryRead backend, PersistStoreWrite backend) => PersistQueryWrite backend whereBackends supporting conditional write operations
Methods
updateWhere :: (MonadIO m, PersistRecordBackend record backend) => [Filter record] -> [Update record] -> ReaderT backend m ()Update individual fields on any record matching the given criterion.
deleteWhere :: (MonadIO m, PersistRecordBackend record backend) => [Filter record] -> ReaderT backend m ()Delete all records matching the given criterion.
Instances3PersistQueryWrite
PersistQueryWrite SqlWriteBackendDefined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistQuery · orphanPersistQueryWrite SqlBackendDefined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistQuery · orphan(HasPersistBackend b, BackendCompatible b s, PersistQueryWrite b) => PersistQueryWrite (Compatible b s)Defined in persistent-2.14.6.3 · Database.Persist.Compatible.Types
This class witnesses that two backend are compatible, and that you can
convert from the sub backend into the sup backend. This is similar
to the HasPersistBackend and IsPersistBackend classes, but where you
don't want to fix the type associated with the PersistEntityBackend of
a record.
Generally speaking, where you might have:
foo ::
( PersistEntity record
, PersistEntityBackend record ~ BaseBackend backend
, IsSqlBackend backend
)
this can be replaced with:
foo ::
( PersistEntity record,
, PersistEntityBackend record ~ backend
, BackendCompatible SqlBackend backend
)
This works for SqlReadBackend because of the instance BackendCompatible , without needing to go through the BaseBackend type family.SqlBackend SqlReadBackend
Likewise, functions that are currently hardcoded to use SqlBackend can be generalized:
-- before:
asdf :: ReaderT SqlBackend m ()
asdf = pure ()
-- after:
asdf' :: BackendCompatible SqlBackend backend => ReaderT backend m ()
asdf' = withCompatibleBackend asdf
Methods
projectBackend :: sub -> sup
Instances3BackendCompatible
BackendCompatible SqlBackend SqlReadBackendDefined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanBackendCompatible SqlBackend SqlWriteBackendDefined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanBackendCompatible SqlBackend SqlBackendDefined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphan
Associated types
data family BackendKey backend
Instances4PersistCore
PersistCore SqlReadBackendDefined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanPersistCore SqlWriteBackendDefined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanPersistCore SqlBackendDefined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphan(BackendCompatible b s, PersistCore b) => PersistCore (Compatible b s)Defined in persistent-2.14.6.3 · Database.Persist.Compatible.Types
Instances71Bounded, Enum, Eq, Integral, Num, Ord, …
Bounded (BackendKey SqlReadBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanBounded (BackendKey SqlWriteBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanBounded (BackendKey SqlBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphan(BackendCompatible b s, Bounded (BackendKey b)) => Bounded (BackendKey (Compatible b s))Defined in persistent-2.14.6.3 · Database.Persist.Compatible.TypesEnum (BackendKey SqlReadBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanEnum (BackendKey SqlWriteBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanEnum (BackendKey SqlBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphan(BackendCompatible b s, Enum (BackendKey b)) => Enum (BackendKey (Compatible b s))Defined in persistent-2.14.6.3 · Database.Persist.Compatible.TypesEq (BackendKey SqlReadBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanEq (BackendKey SqlWriteBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanEq (BackendKey SqlBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphan(BackendCompatible b s, Eq (BackendKey b)) => Eq (BackendKey (Compatible b s))Defined in persistent-2.14.6.3 · Database.Persist.Compatible.TypesIntegral (BackendKey SqlReadBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanIntegral (BackendKey SqlWriteBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanIntegral (BackendKey SqlBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphan(BackendCompatible b s, Integral (BackendKey b)) => Integral (BackendKey (Compatible b s))Defined in persistent-2.14.6.3 · Database.Persist.Compatible.TypesNum (BackendKey SqlReadBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanNum (BackendKey SqlWriteBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanNum (BackendKey SqlBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphan(BackendCompatible b s, Num (BackendKey b)) => Num (BackendKey (Compatible b s))Defined in persistent-2.14.6.3 · Database.Persist.Compatible.TypesOrd (BackendKey SqlReadBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanOrd (BackendKey SqlWriteBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanOrd (BackendKey SqlBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphan(BackendCompatible b s, Ord (BackendKey b)) => Ord (BackendKey (Compatible b s))Defined in persistent-2.14.6.3 · Database.Persist.Compatible.TypesRead (BackendKey SqlReadBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanRead (BackendKey SqlWriteBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanRead (BackendKey SqlBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphan(BackendCompatible b s, Read (BackendKey b)) => Read (BackendKey (Compatible b s))Defined in persistent-2.14.6.3 · Database.Persist.Compatible.TypesReal (BackendKey SqlReadBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanReal (BackendKey SqlWriteBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanReal (BackendKey SqlBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphan(BackendCompatible b s, Real (BackendKey b)) => Real (BackendKey (Compatible b s))Defined in persistent-2.14.6.3 · Database.Persist.Compatible.TypesShow (BackendKey SqlReadBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanShow (BackendKey SqlWriteBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanShow (BackendKey SqlBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphan(BackendCompatible b s, Show (BackendKey b)) => Show (BackendKey (Compatible b s))Defined in persistent-2.14.6.3 · Database.Persist.Compatible.TypesGeneric (BackendKey SqlReadBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanGeneric (BackendKey SqlWriteBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanGeneric (BackendKey SqlBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanFromJSON (BackendKey SqlReadBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanFromJSON (BackendKey SqlWriteBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanFromJSON (BackendKey SqlBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphan(BackendCompatible b s, FromJSON (BackendKey b)) => FromJSON (BackendKey (Compatible b s))Defined in persistent-2.14.6.3 · Database.Persist.Compatible.TypesToJSON (BackendKey SqlReadBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanToJSON (BackendKey SqlWriteBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanToJSON (BackendKey SqlBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphan(BackendCompatible b s, ToJSON (BackendKey b)) => ToJSON (BackendKey (Compatible b s))Defined in persistent-2.14.6.3 · Database.Persist.Compatible.TypesFromHttpApiData (BackendKey SqlReadBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanFromHttpApiData (BackendKey SqlWriteBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanFromHttpApiData (BackendKey SqlBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanToHttpApiData (BackendKey SqlReadBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanToHttpApiData (BackendKey SqlWriteBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanToHttpApiData (BackendKey SqlBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanPathPiece (BackendKey SqlReadBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanPathPiece (BackendKey SqlWriteBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanPathPiece (BackendKey SqlBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanPersistField (BackendKey SqlReadBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanPersistField (BackendKey SqlWriteBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanPersistField (BackendKey SqlBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphan(BackendCompatible b s, PersistField (BackendKey b)) => PersistField (BackendKey (Compatible b s))Defined in persistent-2.14.6.3 · Database.Persist.Compatible.TypesPersistFieldSql (BackendKey SqlReadBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanPersistFieldSql (BackendKey SqlWriteBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanPersistFieldSql (BackendKey SqlBackend)Defined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphan(BackendCompatible b s, PersistFieldSql (BackendKey b)) => PersistFieldSql (BackendKey (Compatible b s))Defined in persistent-2.14.6.3 · Database.Persist.Compatible.Typestype Rep (BackendKey SqlReadBackend) = D1 ('MetaDataDefined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphan"BackendKey"
"Database.Persist.Sql.Orphan.PersistStore"
"persistent-2.14.6.3-31NeHlMbZ2g6XoXmn516lt"
'True) (C1 ('MetaCons"SqlReadBackendKey"
'PrefixI 'True) (S1 ('MetaSel ('Just"unSqlReadBackendKey"
) 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 Int64)))type Rep (BackendKey SqlWriteBackend) = D1 ('MetaDataDefined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphan"BackendKey"
"Database.Persist.Sql.Orphan.PersistStore"
"persistent-2.14.6.3-31NeHlMbZ2g6XoXmn516lt"
'True) (C1 ('MetaCons"SqlWriteBackendKey"
'PrefixI 'True) (S1 ('MetaSel ('Just"unSqlWriteBackendKey"
) 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 Int64)))type Rep (BackendKey SqlBackend) = D1 ('MetaDataDefined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphan"BackendKey"
"Database.Persist.Sql.Orphan.PersistStore"
"persistent-2.14.6.3-31NeHlMbZ2g6XoXmn516lt"
'True) (C1 ('MetaCons"SqlBackendKey"
'PrefixI 'True) (S1 ('MetaSel ('Just"unSqlBackendKey"
) 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 Int64)))data BackendKey SqlReadBackendDefined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphandata BackendKey SqlWriteBackendDefined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphandata BackendKey SqlBackendDefined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphandata BackendKey (Compatible b s)CompatibleKeyunCompatibleKey :: BackendKey b
Class which allows the plucking of a BaseBackend backend from some larger type.
For example,
instance HasPersistBackend (SqlReadBackend, Int) where
type BaseBackend (SqlReadBackend, Int) = SqlBackend
persistBackend = unSqlReadBackend . fst
Associated types
type family BaseBackend backend
Methods
persistBackend :: backend -> BaseBackend backend
Instances4HasPersistBackend
HasPersistBackend SqlReadBackendDefined in persistent-2.14.6.3 · Database.Persist.Sql.Types.InternalHasPersistBackend SqlWriteBackendDefined in persistent-2.14.6.3 · Database.Persist.Sql.Types.InternalHasPersistBackend SqlBackendDefined in persistent-2.14.6.3 · Database.Persist.SqlBackend.Internal(BackendCompatible b s, HasPersistBackend b) => HasPersistBackend (Compatible b s)Defined in persistent-2.14.6.3 · Database.Persist.Compatible.Types
Instances4BaseBackend
type BaseBackend SqlReadBackend = SqlBackendDefined in persistent-2.14.6.3 · Database.Persist.Sql.Types.Internaltype BaseBackend SqlWriteBackend = SqlBackendDefined in persistent-2.14.6.3 · Database.Persist.Sql.Types.Internaltype BaseBackend SqlBackend = SqlBackendDefined in persistent-2.14.6.3 · Database.Persist.SqlBackend.Internaltype BaseBackend (Compatible b s) = BaseBackend bDefined in persistent-2.14.6.3 · Database.Persist.Compatible.Types
Class which witnesses that backend is essentially the same as BaseBackend backend.
That is, they're isomorphic and backend is just some wrapper over BaseBackend backend.
Instances3IsPersistBackend
IsPersistBackend SqlReadBackendDefined in persistent-2.14.6.3 · Database.Persist.Sql.Types.InternalIsPersistBackend SqlWriteBackendDefined in persistent-2.14.6.3 · Database.Persist.Sql.Types.InternalIsPersistBackend SqlBackendDefined in persistent-2.14.6.3 · Database.Persist.SqlBackend.Internal
type PersistRecordBackend record backend = (PersistEntity record, PersistEntityBackend record ~ BaseBackend backend)A convenient alias for common type signatures
class (Show (BackendKey backend), Read (BackendKey backend), Eq (BackendKey backend), Ord (BackendKey backend), PersistCore backend, PersistField (BackendKey backend), ToJSON (BackendKey backend), FromJSON (BackendKey backend)) => PersistStoreRead backend whereMethods
get :: (MonadIO m, PersistRecordBackend record backend) => Key record -> ReaderT backend m (Maybe record)Get a record by identifier, if available.
Example usage
getSpj :: MonadIO m => ReaderT SqlBackend m (Maybe User) getSpj = get spjIdmspj <- getSpjThe above query when applied on dataset-1, will get this:
+------+-----+ | name | age | +------+-----+ | SPJ | 40 | +------+-----+getMany :: (MonadIO m, PersistRecordBackend record backend) => [Key record] -> ReaderT backend m (Map (Key record) record)Get many records by their respective identifiers, if available.
Example usage
getUsers :: MonadIO m => ReaderT SqlBackend m (Map (Key User) User) getUsers = getMany allkeysmusers <- getUsersThe above query when applied on dataset-1, will get these records:
+----+-------+-----+ | id | name | age | +----+-------+-----+ | 1 | SPJ | 40 | +----+-------+-----+ | 2 | Simon | 41 | +----+-------+-----+
Instances4PersistStoreRead
PersistStoreRead SqlReadBackendDefined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanPersistStoreRead SqlWriteBackendDefined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphanPersistStoreRead SqlBackendDefined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistStore · orphan(HasPersistBackend b, BackendCompatible b s, PersistStoreRead b) => PersistStoreRead (Compatible b s)Defined in persistent-2.14.6.3 · Database.Persist.Compatible.Types
class (PersistEntity record, PersistEntityBackend record ~ backend, PersistCore backend) => ToBackendKey backend record whereToBackendKey converts a PersistEntity Key into a BackendKey
This can be used by each backend to convert between a Key and a plain
Haskell type. For Sql, that is done with toSqlKey and fromSqlKey.
By default, a PersistEntity uses the default BackendKey for its Key and is an instance of ToBackendKey
A Key that instead uses a custom type will not be an instance of ToBackendKey.
Methods
toBackendKey :: Key record -> BackendKey backendfromBackendKey :: BackendKey backend -> Key record
This class is used to ensure that functions requring at least one
unique key are not called with records that have 0 unique keys. The
quasiquoter automatically writes working instances for appropriate
entities, and generates TypeError instances for records that have
0 unique keys.
Methods
requireUniquesP :: record -> NonEmpty (Unique record)
type MultipleUniqueKeysError ty = ((('Text "The entity "
':<>: 'ShowType ty) ':<>: 'Text " has multiple unique keys."
) ':$$: ('Text "The function you are trying to call requires only a single "
':<>: 'Text "unique key."
)) ':$$: (('Text "There is probably a variant of the function with 'By' "
':<>: 'Text "appended that will allow you to select a unique key "
) ':<>: 'Text "for the operation."
)This is an error message. It is used when an entity has multiple unique keys, and the function expects a single unique key.
type NoUniqueKeysError ty = (('Text "The entity "
':<>: 'ShowType ty) ':<>: 'Text " does not have any unique keys."
) ':$$: ('Text "The function you are trying to call requires a unique key "
':<>: 'Text "to be defined on the entity."
)This is an error message. It is used when writing instances of OnlyOneUniqueKey for an entity that has no unique keys.
This class is used to ensure that upsert is only called on records
that have a single Unique key. The quasiquoter automatically generates
working instances for appropriate records, and generates TypeError
instances for records that have 0 or multiple unique keys.
Methods
onlyUniqueP :: record -> Unique record
Queries against Unique keys (other than the id Key).
Please read the general Persistent documentation to learn how to create Unique keys.
Using this with an Entity without a Unique key leads to undefined behavior. A few of these functions require a single Unique, so using an Entity with multiple Uniques is also undefined. In these cases persistent's goal is to throw an exception as soon as possible, but persistent is still transitioning to that.
SQL backends automatically create uniqueness constraints, but for MongoDB you must manually place a unique index on a field to have a uniqueness constraint.
Methods
getBy :: (MonadIO m, PersistRecordBackend record backend) => Unique record -> ReaderT backend m (Maybe (Entity record))Get a record by unique key, if available. Returns also the identifier.
Example usage
getBySpjName :: MonadIO m => ReaderT SqlBackend m (Maybe (Entity User)) getBySpjName = getBy $ UniqueUserName "SPJ"mSpjEnt <- getBySpjNameThe above query when applied on dataset-1, will get this entity:
+----+------+-----+ | id | name | age | +----+------+-----+ | 1 | SPJ | 40 | +----+------+-----+existsBy :: (MonadIO m, PersistRecordBackend record backend) => Unique record -> ReaderT backend m BoolReturns True if a record with this unique key exists, otherwise False.
Example usage
existsBySpjName :: MonadIO m => ReaderT SqlBackend m Bool existsBySpjName = existsBy $ UniqueUserName "SPJ"spjEntExists <- existsBySpjNameThe above query when applied on dataset-1, will return the value True.
Instances4PersistUniqueRead
PersistUniqueRead SqlReadBackendDefined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistUnique · orphanPersistUniqueRead SqlWriteBackendDefined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistUnique · orphanPersistUniqueRead SqlBackendDefined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistUnique · orphan(HasPersistBackend b, BackendCompatible b s, PersistUniqueRead b) => PersistUniqueRead (Compatible b s)Defined in persistent-2.14.6.3 · Database.Persist.Compatible.Types
class (PersistUniqueRead backend, PersistStoreWrite backend) => PersistUniqueWrite backend whereSome functions in this module (insertUnique, insertBy, and replaceUnique) first query the unique indexes to check for conflicts. You could instead optimistically attempt to perform the operation (e.g. replace instead of replaceUnique). However,
there is some fragility to trying to catch the correct exception and determing the column of failure;
an exception will automatically abort the current SQL transaction.
Methods
deleteBy :: (MonadIO m, PersistRecordBackend record backend) => Unique record -> ReaderT backend m ()Delete a specific record by unique key. Does nothing if no record matches.
Example usage
deleteBySpjName :: MonadIO m => ReaderT SqlBackend m () deleteBySpjName = deleteBy UniqueUserName "SPJ"The above query when applied on dataset-1, will produce this:
+-----+------+-----+ |id |name |age | +-----+------+-----+ |2 |Simon |41 | +-----+------+-----+insertUnique :: (MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => record -> ReaderT backend m (Maybe (Key record))Like insert, but returns Nothing when the record couldn't be inserted because of a uniqueness constraint.
Example usage
With schema-1 and dataset-1, we try to insert the following two records:
linusId <- insertUnique $ User "Linus" 48 spjId <- insertUnique $ User "SPJ" 90+-----+------+-----+ |id |name |age | +-----+------+-----+ |1 |SPJ |40 | +-----+------+-----+ |2 |Simon |41 | +-----+------+-----+ |3 |Linus |48 | +-----+------+-----+Linus's record was inserted to dataset-1, while SPJ wasn't because SPJ already exists in dataset-1.
insertUnique_ :: (MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => record -> ReaderT backend m (Maybe ())Same as insertUnique but doesn't return a
Key.Example usage
With schema-1 and dataset-1, we try to insert the following two records:
linusId <- insertUnique_ $ User "Linus" 48 spjId <- insertUnique_ $ User "SPJ" 90+-----+------+-----+ |id |name |age | +-----+------+-----+ |1 |SPJ |40 | +-----+------+-----+ |2 |Simon |41 | +-----+------+-----+ |3 |Linus |48 | +-----+------+-----+Linus's record was inserted to dataset-1, while SPJ wasn't because SPJ already exists in dataset-1.
upsert :: (MonadIO m, PersistRecordBackend record backend, OnlyOneUniqueKey record, SafeToInsert record) => record -> [Update record] -> ReaderT backend m (Entity record)Update based on a uniqueness constraint or insert:
insert the new record if it does not exist;
If the record exists (matched via it's uniqueness constraint), then update the existing record with the parameters which is passed on as list to the function.
Example usage
First, we try to explain upsert using schema-1 and dataset-1.
upsertSpj :: MonadIO m => [Update User] -> ReaderT SqlBackend m (Maybe (Entity User)) upsertSpj updates = upsert (User "SPJ" 999) updatesmSpjEnt <- upsertSpj [UserAge +=. 15]The above query when applied on dataset-1, will produce this:
+-----+-----+--------+ |id |name |age | +-----+-----+--------+ |1 |SPJ |40 -> 55| +-----+-----+--------+ |2 |Simon|41 | +-----+-----+--------+upsertX :: MonadIO m => [Update User] -> ReaderT SqlBackend m (Maybe (Entity User)) upsertX updates = upsert (User "X" 999) updatesmXEnt <- upsertX [UserAge +=. 15]The above query when applied on dataset-1, will produce this:
+-----+-----+--------+ |id |name |age | +-----+-----+--------+ |1 |SPJ |40 | +-----+-----+--------+ |2 |Simon|41 | +-----+-----+--------+ |3 |X |999 | +-----+-----+--------+Next, what if the schema has two uniqueness constraints? Let's check it out using schema-2:
mSpjEnt <- upsertSpj [UserAge +=. 15]This fails with a compile-time type error alerting us to the fact that this record has multiple unique keys, and suggests that we look for upsertBy to select the unique key we want.
upsertBy :: (MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => Unique record -> record -> [Update record] -> ReaderT backend m (Entity record)Update based on a given uniqueness constraint or insert:
insert the new record if it does not exist;
update the existing record that matches the given uniqueness constraint.
Example usage
We try to explain upsertBy using schema-2 and dataset-1.
upsertBySpjName :: MonadIO m => User -> [Update User] -> ReaderT SqlBackend m (Entity User) upsertBySpjName record updates = upsertBy (UniqueUserName "SPJ") record updatesmSpjEnt <- upsertBySpjName (Person "X" 999) [PersonAge += .15]The above query will alter dataset-1 to:
+-----+-----+--------+ |id |name |age | +-----+-----+--------+ |1 |SPJ |40 -> 55| +-----+-----+--------+ |2 |Simon|41 | +-----+-----+--------+upsertBySimonAge :: MonadIO m => User -> [Update User] -> ReaderT SqlBackend m (Entity User) upsertBySimonAge record updates = upsertBy (UniqueUserName "SPJ") record updatesmPhilipEnt <- upsertBySimonAge (User "X" 999) [UserName =. "Philip"]The above query will alter dataset-1 to:
+----+-----------------+-----+ | id | name | age | +----+-----------------+-----+ | 1 | SPJ | 40 | +----+-----------------+-----+ | 2 | Simon -> Philip | 41 | +----+-----------------+-----+upsertByUnknownName :: MonadIO m => User -> [Update User] -> ReaderT SqlBackend m (Entity User) upsertByUnknownName record updates = upsertBy (UniqueUserName "Unknown") record updatesmXEnt <- upsertByUnknownName (User "X" 999) [UserAge +=. 15]This query will alter dataset-1 to:
+-----+-----+-----+ |id |name |age | +-----+-----+-----+ |1 |SPJ |40 | +-----+-----+-----+ |2 |Simon|41 | +-----+-----+-----+ |3 |X |999 | +-----+-----+-----+putMany :: (MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => [record] -> ReaderT backend m ()Put many records into db
insert new records that do not exist (or violate any unique constraints)
replace existing records (matching any unique constraint)
Instances3PersistUniqueWrite
PersistUniqueWrite SqlWriteBackendDefined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistUnique · orphanPersistUniqueWrite SqlBackendDefined in persistent-2.14.6.3 · Database.Persist.Sql.Orphan.PersistUnique · orphan(HasPersistBackend b, BackendCompatible b s, PersistUniqueWrite b) => PersistUniqueWrite (Compatible b s)Defined in persistent-2.14.6.3 · Database.Persist.Compatible.Types
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 . For The BackendKey yourBackendTypeSqlBackend 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 ImplicitIdDef that corresponds to this declaration.
newtype UUID = UUID ByteString
instance PersistField UUID where
toPersistValue (UUID bs) =
PersistLiteral_ Escaped bs
fromPersistValue pv =
case pv of
PersistLiteral_ Escaped bs ->
Right (UUID bs)
_ ->
Left "nope"
instance PersistFieldSql UUID where
sqlType _ = SqlOther 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.
A ConstraintNameDB represents the datastore-side name that persistent
will use for a constraint.
Constructors
Instances6Eq, Ord, Read, Show, DatabaseName, Lift
Eq ConstraintNameDBDefined in persistent-2.14.6.3 · Database.Persist.NamesOrd ConstraintNameDBDefined in persistent-2.14.6.3 · Database.Persist.NamesRead ConstraintNameDBDefined in persistent-2.14.6.3 · Database.Persist.NamesShow ConstraintNameDBDefined in persistent-2.14.6.3 · Database.Persist.NamesDatabaseName ConstraintNameDBDefined in persistent-2.14.6.3 · Database.Persist.NamesLift ConstraintNameDBDefined in persistent-2.14.6.3 · Database.Persist.Names
An ConstraintNameHS represents the Haskell-side name that persistent
will use for a constraint.
Constructors
Instances5Eq, Ord, Read, Show, Lift
Eq ConstraintNameHSDefined in persistent-2.14.6.3 · Database.Persist.NamesOrd ConstraintNameHSDefined in persistent-2.14.6.3 · Database.Persist.NamesRead ConstraintNameHSDefined in persistent-2.14.6.3 · Database.Persist.NamesShow ConstraintNameHSDefined in persistent-2.14.6.3 · Database.Persist.NamesLift ConstraintNameHSDefined in persistent-2.14.6.3 · Database.Persist.Names
Convenience operations for working with '-NameDB' types.
Methods
escapeWith :: (Text -> str) -> a -> str
Instances3DatabaseName
DatabaseName ConstraintNameDBDefined in persistent-2.14.6.3 · Database.Persist.NamesDatabaseName EntityNameDBDefined in persistent-2.14.6.3 · Database.Persist.NamesDatabaseName FieldNameDBDefined in persistent-2.14.6.3 · Database.Persist.Names
An EntityNameDB represents the datastore-side name that persistent
will use for an entity.
Constructors
Instances6Eq, Ord, Read, Show, DatabaseName, Lift
Eq EntityNameDBDefined in persistent-2.14.6.3 · Database.Persist.NamesOrd EntityNameDBDefined in persistent-2.14.6.3 · Database.Persist.NamesRead EntityNameDBDefined in persistent-2.14.6.3 · Database.Persist.NamesShow EntityNameDBDefined in persistent-2.14.6.3 · Database.Persist.NamesDatabaseName EntityNameDBDefined in persistent-2.14.6.3 · Database.Persist.NamesLift EntityNameDBDefined in persistent-2.14.6.3 · Database.Persist.Names
An EntityNameHS represents the Haskell-side name that persistent
will use for an entity.
Constructors
Instances5Eq, Ord, Read, Show, Lift
Eq EntityNameHSDefined in persistent-2.14.6.3 · Database.Persist.NamesOrd EntityNameHSDefined in persistent-2.14.6.3 · Database.Persist.NamesRead EntityNameHSDefined in persistent-2.14.6.3 · Database.Persist.NamesShow EntityNameHSDefined in persistent-2.14.6.3 · Database.Persist.NamesLift EntityNameHSDefined in persistent-2.14.6.3 · Database.Persist.Names
A FieldNameDB represents the datastore-side name that persistent
will use for a field.
Constructors
Instances6Eq, Ord, Read, Show, DatabaseName, Lift
Eq FieldNameDBDefined in persistent-2.14.6.3 · Database.Persist.NamesOrd FieldNameDBDefined in persistent-2.14.6.3 · Database.Persist.NamesRead FieldNameDBDefined in persistent-2.14.6.3 · Database.Persist.NamesShow FieldNameDBDefined in persistent-2.14.6.3 · Database.Persist.NamesDatabaseName FieldNameDBDefined in persistent-2.14.6.3 · Database.Persist.NamesLift FieldNameDBDefined in persistent-2.14.6.3 · Database.Persist.Names
A FieldNameHS represents the Haskell-side name that persistent
will use for a field.
Constructors
Instances5Eq, Ord, Read, Show, Lift
Eq FieldNameHSDefined in persistent-2.14.6.3 · Database.Persist.NamesOrd FieldNameHSDefined in persistent-2.14.6.3 · Database.Persist.NamesRead FieldNameHSDefined in persistent-2.14.6.3 · Database.Persist.NamesShow FieldNameHSDefined in persistent-2.14.6.3 · Database.Persist.NamesLift FieldNameHSDefined in persistent-2.14.6.3 · Database.Persist.Names
A type that determines how a backend should handle the literal.
Constructors
EscapedThe accompanying value will be escaped before inserting into the database. This is the correct default choice to use.
UnescapedThe accompanying value will not be escaped when inserting into the database. This is potentially dangerous - use this with care.
DbSpecificThe DbSpecific constructor corresponds to the legacy PersistDbSpecific 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.
Instances4Eq, Ord, Read, Show
Eq LiteralTypeDefined in persistent-2.14.6.3 · Database.Persist.PersistValueOrd LiteralTypeDefined in persistent-2.14.6.3 · Database.Persist.PersistValueRead LiteralTypeDefined in persistent-2.14.6.3 · Database.Persist.PersistValueShow LiteralTypeDefined in persistent-2.14.6.3 · Database.Persist.PersistValue
A raw value which can be stored in any backend and can be marshalled to
and from a PersistField.
Constructors
PersistText TextPersistByteString ByteStringPersistInt64 Int64PersistDouble DoublePersistRational RationalPersistBool BoolPersistDay DayPersistTimeOfDay TimeOfDayPersistUTCTime UTCTimePersistNullPersistList [PersistValue]PersistMap [(Text, PersistValue)]PersistObjectId ByteStringIntended especially for MongoDB backend
PersistArray [PersistValue]Intended especially for PostgreSQL backend for text arrays
PersistLiteral_ LiteralType ByteStringThis constructor is used to specify some raw literal value for the backend. The LiteralType value specifies how the value should be escaped. This can be used to make special, custom types avaialable in the back end.
Instances12Eq, Ord, Read, Show, NFData, FromJSON, …
Eq PersistValueDefined in persistent-2.14.6.3 · Database.Persist.PersistValueOrd PersistValueDefined in persistent-2.14.6.3 · Database.Persist.PersistValueRead PersistValueDefined in persistent-2.14.6.3 · Database.Persist.PersistValueShow PersistValueDefined in persistent-2.14.6.3 · Database.Persist.PersistValueNFData PersistValueDefined in persistent-2.14.6.3 · Database.Persist.PersistValueFromJSON PersistValueDefined in persistent-2.14.6.3 · Database.Persist.PersistValueToJSON PersistValueDefined in persistent-2.14.6.3 · Database.Persist.PersistValueFromHttpApiData PersistValueDefined in persistent-2.14.6.3 · Database.Persist.PersistValueToHttpApiData PersistValueDefined in persistent-2.14.6.3 · Database.Persist.PersistValuePathPiece PersistValueDefined in persistent-2.14.6.3 · Database.Persist.PersistValuePersistField PersistValueDefined in persistent-2.14.6.3 · Database.Persist.Class.PersistFieldPersistFieldSql PersistValueDefined in persistent-2.14.6.3 · Database.Persist.Sql.Class
Deprecated. Deprecated since 2.11 because of inconsistent escaping behavior across backends. The Postgres backend escapes these values, while the MySQL backend does not. If you are using this, please switch to PersistLiteral_ and provide a relevant LiteralType for your conversion.
This pattern synonym used to be a data constructor for the PersistValue type. It was changed to be a pattern so that JSON-encoded database values could be parsed into their corresponding values. You should not use this, and instead prefer to pattern match on PersistLiteral_ directly.
If you use this, it will overlap a patern match on the 'PersistLiteral_, PersistLiteral, and PersistLiteralEscaped patterns. If you need to disambiguate between these constructors, pattern match on PersistLiteral_ directly.
This pattern synonym used to be a data constructor on PersistValue, but was changed into a catch-all pattern synonym to allow backwards compatiblity with database types. See the documentation on PersistDbSpecific for more details.
This pattern synonym used to be a data constructor on PersistValue, but was changed into a catch-all pattern synonym to allow backwards compatiblity with database types. See the documentation on PersistDbSpecific for more details.
Constructors
EntityJSONentityToJSON :: NameName of the
toJSONimplementation forEntity a.entityFromJSON :: NameName of the
fromJSONimplementation forEntity a.
Settings to be passed to the mkPersist function.
Customise function for field accessors applied only when the field name matches any of Haskell keywords.
Default: suffix "_".
Which database backend we're using. This type is used for the PersistEntityBackend associated type in the entities that are generated.
If the mpsGeneric value is set to True, then this type is used for the non-Generic type alias. The data and type will be named:
data ModelGeneric backend = Model { ... }
And, for convenience's sake, we provide a type alias:
type Model = ModelGeneric $(the type you give here)
Should we generate composite key accessors in the correct CamelCase style.
If the mpsCamelCaseCompositeKeySelector value is set to False, then the field part of the accessor starts with the lowercase. This is a legacy style.
data Key CompanyUser = CompanyUserKey
{ companyUserKeycompanyId :: CompanyId
, companyUserKeyuserId :: UserId
}
If the mpsCamelCaseCompositeKeySelector value is set to True, then field accessors are generated in CamelCase style.
data Key CompanyUser = CompanyUserKey
{ companyUserKeyCompanyId :: CompanyId
, companyUserKeyUserId :: UserId
}
Customise 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 field
Note: this setting is ignored if mpsPrefixFields is set to False.
Automatically derive these typeclass instances for all record and key types.
Default: []
Generate Haddocks from entity documentation comments. Default: False.
Generate ToJSON/FromJSON instances for each model types. If it's
Nothing, no instances will be generated. Default:
Just EntityJSON
{ entityToJSON = 'entityIdToJSON
, entityFromJSON = 'entityIdFromJSON
}
Customise 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.
Instead of generating normal field accessors, generator lens-style accessors.
Default: False
Deprecated. The mpsGeneric function adds a considerable amount of overhead and complexity to the library without bringing significant benefit. We would like to remove it. If you require this feature, please comment on the linked GitHub issue, and we'll either keep it around, or we can figure out a nicer way to solve your problem.Github: https://github.com/yesodweb/persistent/issues/1204
Create generic types that can be used with multiple backends. Good for reusable code, but makes error messages harder to understand. Default: False.
Prefix field names with the model name. Default: True.
Note: this field is deprecated. Use the mpsFieldLabelModifier and mpsConstraintLabelModifier instead.
An action that might happen on a deletion or update on a foreign key change.
Instances5Eq, Ord, Read, Show, Lift
Eq CascadeActionDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseOrd CascadeActionDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseRead CascadeActionDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseShow CascadeActionDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseLift CascadeActionDefined in persistent-2.14.6.3 · Database.Persist.Types.Base
A Checkmark 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 Location 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
Inactive Locations to be current. However, there may be
at most one current Location per user (i.e., either zero
or one per user).
This data type works because of the way that SQL treats
NULLable fields within uniqueness constraints. The SQL
standard says that NULL values should be considered
different, so we represent Inactive as SQL NULL, thus
allowing any number of Inactive records. On the other hand,
we represent Active as TRUE, so the uniqueness constraint
will disallow more than one Active 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.
Instances11Bounded, Enum, Eq, Ord, Read, Show, …
Bounded CheckmarkDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseEnum CheckmarkDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseEq CheckmarkDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseOrd CheckmarkDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseRead CheckmarkDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseShow CheckmarkDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseFromHttpApiData CheckmarkDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseToHttpApiData CheckmarkDefined in persistent-2.14.6.3 · Database.Persist.Types.BasePathPiece CheckmarkDefined in persistent-2.14.6.3 · Database.Persist.Types.BasePersistField CheckmarkDefined in persistent-2.14.6.3 · Database.Persist.Class.PersistFieldPersistFieldSql CheckmarkDefined in persistent-2.14.6.3 · Database.Persist.Sql.Class
Constructors
Instances5Eq, Ord, Read, Show, Lift
Eq CompositeDefDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseOrd CompositeDefDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseRead CompositeDefDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseShow CompositeDefDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseLift CompositeDefDefined in persistent-2.14.6.3 · Database.Persist.Types.Base
An EmbedEntityDef is the same as an EntityDef But it is only used for fieldReference so it only has data needed for embedding
Constructors
Instances5Eq, Ord, Read, Show, Lift
Eq EmbedEntityDefDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseOrd EmbedEntityDefDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseRead EmbedEntityDefDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseShow EmbedEntityDefDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseLift EmbedEntityDefDefined in persistent-2.14.6.3 · Database.Persist.Types.Base
An EmbedFieldDef is the same as a FieldDef But it is only used for embeddedFields so it only has data needed for embedding
Constructors
EmbedFieldDefemFieldDB :: FieldNameDBemFieldEmbed :: Maybe (Either SelfEmbed EntityNameHS)
Instances5Eq, Ord, Read, Show, Lift
Eq EmbedFieldDefDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseOrd EmbedFieldDefDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseRead EmbedFieldDefDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseShow EmbedFieldDefDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseLift EmbedFieldDefDefined in persistent-2.14.6.3 · Database.Persist.Types.Base
An EntityDef 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.
Instances5Eq, Ord, Read, Show, Lift
Eq EntityDefDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseOrd EntityDefDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseRead EntityDefDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseShow EntityDefDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseLift EntityDefDefined in persistent-2.14.6.3 · Database.Persist.Types.Base
The definition for the entity's primary key ID.
Constructors
EntityIdField !FieldDefThe entity has a single key column, and it is a surrogate key - that is, you can't go from
rec -> Key rec.EntityIdNaturalKey !CompositeDefThe entity has a natural key. This means you can write
rec -> Key recbecause all the key fields are present on the datatype.A natural key can have one or more columns.
Instances5Eq, Ord, Read, Show, Lift
Eq EntityIdDefDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseOrd EntityIdDefDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseRead EntityIdDefDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseShow EntityIdDefDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseLift EntityIdDefDefined in persistent-2.14.6.3 · Database.Persist.Types.Base
Attributes 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 FieldAttr is extensible through its constructor FieldAttrOther.
Constructors
FieldAttrMaybeFieldAttrNullableThis indicates that the column is nullable, but should not have a Maybe type. For this to work out, you need to ensure that the
PersistFieldinstance for the type in question can support a PersistNull 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 nullableFieldAttrMigrationOnlyThis 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.
User oldName Text MigrationOnly newName TextFieldAttrSafeToRemoveA
SafeToRemoveattribute 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
MigrationOnlyto remove a column from the database in phases.User oldName Text SafeToRemove newName TextFieldAttrNoreferenceThis attribute indicates that we should not create a foreign key reference from a column. By default,
persistentwill try and create a foreign key reference for a column if it can determine that the type of the column is aor anKeyentityEntityIdand theEntity's name was present inmkPersist.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 postIdFieldAttrReference TextThis 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 -
persistentshould be capable of correctly determining the target table's name. If you do need this, please file an issue describing why.FieldAttrConstraint TextSpecify a name for the constraint on the foreign key reference for this table.
Post title Text Comment postId PostId constraint="my_cool_constraint_name"FieldAttrDefault TextSpecify the default value for a column.
User createdAt UTCTime default="NOW()"Note that a
default=attribute does not mean you can omit the value while inserting.FieldAttrSqltype TextSpecify a custom SQL type for the column. Generally, you should define a custom datatype with a custom
PersistFieldSqlinstance instead of using this.User uuid Text sqltype=UUIDFieldAttrMaxlen IntegerSet a maximum length for a column. Useful for VARCHAR and indexes.
User name Text maxlen=200 UniqueName nameFieldAttrSql TextSpecify the database name of the column.
User 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.
FieldAttrOther TextA grab bag of random attributes that were unrecognized by the parser.
Instances5Eq, Ord, Read, Show, Lift
Eq FieldAttrDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseOrd FieldAttrDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseRead FieldAttrDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseShow FieldAttrDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseLift FieldAttrDefined in persistent-2.14.6.3 · Database.Persist.Types.Base
This 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 Nothing in either of the field values means that the user has not specified a CascadeAction. An unspecified CascadeAction is defaulted to Restrict when doing migrations.
Constructors
Instances5Eq, Ord, Read, Show, Lift
Eq FieldCascadeDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseOrd FieldCascadeDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseRead FieldCascadeDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseShow FieldCascadeDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseLift FieldCascadeDefined in persistent-2.14.6.3 · Database.Persist.Types.Base
A FieldDef 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.
Constructors
FieldDeffieldHaskell :: !FieldNameHSThe 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 FieldDef that contains a
FieldNameHS "name"for a typeUserwill have a record fielduserName.fieldDB :: !FieldNameDBThe name of the field in the database. For SQL databases, this corresponds to the column name.
fieldType :: !FieldTypeThe type of the field in Haskell.
fieldSqlType :: !SqlTypeThe type of the field in a SQL database.
fieldAttrs :: ![FieldAttr]User annotations for a field. These are provided with the
!operator.fieldStrict :: !BoolfieldReference :: !ReferenceDeffieldCascade :: !FieldCascadeDefines how operations on the field cascade on to the referenced tables. This doesn't have any meaning if the fieldReference is set to NoReference or SelfReference. The cascade option here should be the same as the one obtained in the fieldReference.
fieldComments :: !Maybe TextOptional comments for a
Field.fieldGenerated :: !Maybe TextWhether or not the field is a
GENERATEDcolumn, and additionally the expression to use for generation.fieldIsImplicitIdColumn :: !Bool
Instances5Eq, Ord, Read, Show, Lift
Eq FieldDefDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseOrd FieldDefDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseRead FieldDefDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseShow FieldDefDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseLift FieldDefDefined in persistent-2.14.6.3 · Database.Persist.Types.Base
A FieldType 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)
Instances5Eq, Ord, Read, Show, Lift
Eq FieldTypeDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseOrd FieldTypeDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseRead FieldTypeDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseShow FieldTypeDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseLift FieldTypeDefined in persistent-2.14.6.3 · Database.Persist.Types.Base
Constructors
ForeignDefforeignRefTableHaskell :: !EntityNameHSforeignRefTableDBName :: !EntityNameDBforeignConstraintNameHaskell :: !ConstraintNameHSforeignConstraintNameDBName :: !ConstraintNameDBforeignFieldCascade :: !FieldCascadeDetermine how the field will cascade on updates and deletions.
foreignFields :: ![(ForeignFieldDef, ForeignFieldDef)]foreignAttrs :: ![Attr]foreignNullable :: BoolforeignToPrimary :: BoolDetermines if the reference is towards a Primary Key or not.
Instances5Eq, Ord, Read, Show, Lift
Eq ForeignDefDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseOrd ForeignDefDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseRead ForeignDefDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseShow ForeignDefDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseLift ForeignDefDefined in persistent-2.14.6.3 · Database.Persist.Types.Base
Used instead of FieldDef to generate a smaller amount of code
Constructors
Instances2Eq, Show
Eq IsNullableDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseShow IsNullableDefined in persistent-2.14.6.3 · Database.Persist.Types.Base
Instances2Show, Exception
Show PersistExceptionDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseException PersistExceptionDefined in persistent-2.14.6.3 · Database.Persist.Types.Base
There are 3 kinds of references 1) composite (to fields that exist in the record) 2) single field 3) embedded
Constructors
NoReferenceForeignRef !EntityNameHSA 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
EmbedRef EntityNameHSSelfReferenceA SelfReference stops an immediate cycle which causes non-termination at compile-time (issue #311).
Instances5Eq, Ord, Read, Show, Lift
Eq ReferenceDefDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseOrd ReferenceDefDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseRead ReferenceDefDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseShow ReferenceDefDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseLift ReferenceDefDefined in persistent-2.14.6.3 · Database.Persist.Types.Base
A 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.
Instances5Eq, Ord, Read, Show, Lift
Eq SqlTypeDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseOrd SqlTypeDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseRead SqlTypeDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseShow SqlTypeDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseLift SqlTypeDefined in persistent-2.14.6.3 · Database.Persist.Types.Base
Type 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 = []
}
Constructors
Instances5Eq, Ord, Read, Show, Lift
Eq UniqueDefDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseOrd UniqueDefDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseRead UniqueDefDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseShow UniqueDefDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseLift UniqueDefDefined in persistent-2.14.6.3 · Database.Persist.Types.Base
Constructors
Instances2Show, Exception
Show UpdateExceptionDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseException UpdateExceptionDefined in persistent-2.14.6.3 · Database.Persist.Types.Base
The 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 A. OTOH, a field that is
nullable because of a nullable tag will remain with the same
type.
Instances2Eq, Show
Eq WhyNullableDefined in persistent-2.14.6.3 · Database.Persist.Types.BaseShow WhyNullableDefined in persistent-2.14.6.3 · Database.Persist.Types.Base