-- Hoogle documentation, generated by Haddock
-- See Hoogle, http://www.haskell.org/hoogle/


-- | Type-safe EDSL for SQL queries on persistent backends.
--   
--   <tt>esqueleto</tt> is a bare bones, type-safe EDSL for SQL queries
--   that works with unmodified <tt>persistent</tt> SQL backends. Its
--   language closely resembles SQL, so you don't have to learn new
--   concepts, just new syntax, and it's fairly easy to predict the
--   generated SQL and optimize it for your backend. Most kinds of errors
--   committed when writing SQL are caught as compile-time
--   errors---although it is possible to write type-checked
--   <tt>esqueleto</tt> queries that fail at runtime.
--   
--   <tt>persistent</tt> is a library for type-safe data serialization. It
--   has many kinds of backends, such as SQL backends
--   (<tt>persistent-mysql</tt>, <tt>persistent-postgresql</tt>,
--   <tt>persistent-sqlite</tt>) and NoSQL backends
--   (<tt>persistent-mongoDB</tt>). While <tt>persistent</tt> is a nice
--   library for storing and retrieving records, including with filters, it
--   does not try to support some of the features that are specific to SQL
--   backends. In particular, <tt>esqueleto</tt> is the recommended library
--   for type-safe <tt>JOIN</tt>s on <tt>persistent</tt> SQL backends. (The
--   alternative is using raw SQL, but that's error prone and does not
--   offer any composability.)
--   
--   Currently, <tt>SELECT</tt>s, <tt>UPDATE</tt>s, <tt>INSERT</tt>s and
--   <tt>DELETE</tt>s are supported. Not all SQL features are available,
--   but most of them can be easily added (especially functions), so please
--   open an issue or send a pull request if you need anything that is not
--   covered by <tt>esqueleto</tt> on
--   <a>https://github.com/bitemyapp/esqueleto</a>.
--   
--   The name of this library means "skeleton" in Portuguese and contains
--   all three SQL letters in the correct order =). It was inspired by
--   Scala's Squeryl but created from scratch.
@package esqueleto
@version 3.6.0.0


-- | This is an internal module. This module may have breaking changes
--   without a corresponding major version bump. If you use this module,
--   please open an issue with your use-case so we can safely support it.
module Database.Esqueleto.Internal.ExprParser

-- | A type representing the access of a table value. In Esqueleto, we get
--   a guarantee that the access will look something like:
--   
--   <pre>
--   escape-char [character] escape-char . escape-char [character] escape-char
--               ^^^^^^^^^^^                           ^^^^^^^^^^^
--               table name                            column name
--   </pre>
data TableAccess
TableAccess :: Text -> Text -> TableAccess
[tableAccessTable] :: TableAccess -> Text
[tableAccessColumn] :: TableAccess -> Text

-- | Parse a <tt>SqlExpr (Value Bool)</tt>'s textual representation into a
--   list of <a>TableAccess</a>
parseOnExpr :: SqlBackend -> Text -> Either String (Set TableAccess)

-- | This function uses the <tt>connEscapeName</tt> function in the
--   <a>SqlBackend</a> with an empty identifier to pull out an escape
--   character. This implementation works with postgresql, mysql, and
--   sqlite backends.
mkEscapeChar :: SqlBackend -> Either String Char
type ExprParser a = Char -> Parser a
onExpr :: ExprParser (Set TableAccess)
skipToEscape :: ExprParser ()
parseEscapedIdentifier :: ExprParser [Char]
parseTableAccess :: ExprParser TableAccess
parseEscapedChars :: ExprParser [Char]
instance GHC.Classes.Eq Database.Esqueleto.Internal.ExprParser.TableAccess
instance GHC.Classes.Ord Database.Esqueleto.Internal.ExprParser.TableAccess
instance GHC.Internal.Show.Show Database.Esqueleto.Internal.ExprParser.TableAccess


-- | This is an internal module, anything exported by this module may
--   change without a major version bump. Please use only
--   <a>Database.Esqueleto</a> if possible.
--   
--   If you use this module, please report what your use case is on the
--   issue tracker so we can safely support it.
module Database.Esqueleto.Internal.Internal

-- | (Internal) Start a <a>from</a> query with an entity. <a>from</a> does
--   two kinds of magic using <a>fromStart</a>, <a>fromJoin</a> and
--   <a>fromFinish</a>:
--   
--   <ol>
--   <li>The simple but tedious magic of allowing tuples to be used.</li>
--   <li>The more advanced magic of creating <tt>JOIN</tt>s. The
--   <tt>JOIN</tt> is processed from right to left. The rightmost entity of
--   the <tt>JOIN</tt> is created with <a>fromStart</a>. Each <tt>JOIN</tt>
--   step is then translated into a call to <a>fromJoin</a>. In the end,
--   <a>fromFinish</a> is called to materialize the <tt>JOIN</tt>.</li>
--   </ol>
fromStart :: (PersistEntity a, BackendCompatible SqlBackend (PersistEntityBackend a)) => SqlQuery (PreprocessedFrom (SqlExpr (Entity a)))

-- | Copied from <tt>persistent</tt>
newtype DBName
DBName :: Text -> DBName
[unDBName] :: DBName -> Text

-- | (Internal) Same as <a>fromStart</a>, but entity may be missing.
fromStartMaybe :: (PersistEntity a, BackendCompatible SqlBackend (PersistEntityBackend a)) => SqlQuery (PreprocessedFrom (SqlExpr (Maybe (Entity a))))

-- | (Internal) Do a <tt>JOIN</tt>.
fromJoin :: IsJoinKind join => PreprocessedFrom a -> PreprocessedFrom b -> SqlQuery (PreprocessedFrom (join a b))

-- | (Internal) Finish a <tt>JOIN</tt>.
fromFinish :: PreprocessedFrom a -> SqlQuery a

-- | <tt>WHERE</tt> clause: restrict the query's result.
where_ :: SqlExpr (Value Bool) -> SqlQuery ()

-- | An <tt>ON</tt> clause, useful to describe how two tables are related.
--   Cross joins and tuple-joins do not need an <a>on</a> clause, but
--   <a>InnerJoin</a> and the various outer joins do.
--   
--   <a>Database.Esqueleto.Experimental</a> in version 4.0.0.0 of the
--   library. The <tt>Experimental</tt> module has a dramatically improved
--   means for introducing tables and entities that provides more power and
--   less potential for runtime errors.
--   
--   If you don't include an <a>on</a> clause (or include too many!) then a
--   runtime exception will be thrown.
--   
--   As an example, consider this simple join:
--   
--   <pre>
--   <a>select</a> $
--   <a>from</a> $ \(foo `<a>InnerJoin</a>` bar) -&gt; do
--     <a>on</a> (foo <a>^.</a> FooId <a>==.</a> bar <a>^.</a> BarFooId)
--     ...
--   </pre>
--   
--   We need to specify the clause for joining the two columns together. If
--   we had this:
--   
--   <pre>
--   <a>select</a> $
--   <a>from</a> $ \(foo `<tt>CrossJoin</tt>` bar) -&gt; do
--     ...
--   </pre>
--   
--   Then we can safely omit the <a>on</a> clause, because the cross join
--   will make pairs of all records possible.
--   
--   You can do multiple <a>on</a> clauses in a query. This query joins
--   three tables, and has two <a>on</a> clauses:
--   
--   <pre>
--   <a>select</a> $
--   <a>from</a> $ \(foo `<a>InnerJoin</a>` bar `<a>InnerJoin</a>` baz) -&gt; do
--     <a>on</a> (baz <a>^.</a> BazId <a>==.</a> bar <a>^.</a> BarBazId)
--     <a>on</a> (foo <a>^.</a> FooId <a>==.</a> bar <a>^.</a> BarFooId)
--     ...
--   </pre>
--   
--   Old versions of esqueleto required that you provide the <a>on</a>
--   clauses in reverse order. This restriction has been lifted - you can
--   now provide <a>on</a> clauses in any order, and the SQL should work
--   itself out. The above query is now totally equivalent to this:
--   
--   <pre>
--   <a>select</a> $
--   <a>from</a> $ \(foo `<a>InnerJoin</a>` bar `<a>InnerJoin</a>` baz) -&gt; do
--     <a>on</a> (foo <a>^.</a> FooId <a>==.</a> bar <a>^.</a> BarFooId)
--     <a>on</a> (baz <a>^.</a> BazId <a>==.</a> bar <a>^.</a> BarBazId)
--     ...
--   </pre>
on :: SqlExpr (Value Bool) -> SqlQuery ()

-- | <tt>GROUP BY</tt> clause. You can enclose multiple columns in a tuple.
--   
--   <pre>
--   select $ <a>from</a> \(foo `<tt>InnerJoin</tt>` bar) -&gt; do
--     <a>on</a> (foo <a>^.</a> FooBarId <a>==.</a> bar <a>^.</a> BarId)
--     <a>groupBy</a> (bar <a>^.</a> BarId, bar <a>^.</a> BarName)
--     return (bar <a>^.</a> BarId, bar <a>^.</a> BarName, countRows)
--   </pre>
--   
--   With groupBy you can sort by aggregate functions, like so (we used
--   <tt>let</tt> to restrict the more general <a>countRows</a> to
--   <tt>SqlSqlExpr (Value Int)</tt> to avoid ambiguity---the second use of
--   <a>countRows</a> has its type restricted by the <tt>:: Int</tt>
--   below):
--   
--   <pre>
--   r &lt;- select $ <a>from</a> \(foo `<tt>InnerJoin</tt>` bar) -&gt; do
--     <a>on</a> (foo <a>^.</a> FooBarId <a>==.</a> bar <a>^.</a> BarId)
--     <a>groupBy</a> $ bar <a>^.</a> BarName
--     let countRows' = <a>countRows</a>
--     <a>orderBy</a> [<a>asc</a> countRows']
--     return (bar <a>^.</a> BarName, countRows')
--   forM_ r $ \(<a>Value</a> name, <a>Value</a> count) -&gt; do
--     print name
--     print (count :: Int)
--   </pre>
--   
--   <h3>Need more columns?</h3>
--   
--   The <a>ToSomeValues</a> class is defined for <a>SqlExpr</a> and tuples
--   of <a>SqlExpr</a>s. We only have definitions for up to 8 elements in a
--   tuple right now, so it's possible that you may need to have more than
--   8 elements.
--   
--   For example, consider a query with a <a>groupBy</a> call like this:
--   
--   <pre>
--   groupBy (e0, e1, e2, e3, e4, e5, e6, e7)
--   </pre>
--   
--   This is the biggest you can get with a single tuple. However, you can
--   easily nest the tuples to add more:
--   
--   <pre>
--   groupBy ((e0, e1, e2, e3, e4, e5, e6, e7), e8, e9)
--   </pre>
groupBy :: ToSomeValues a => a -> SqlQuery ()

-- | An alias for <a>groupBy</a> that avoids conflict with the term from
--   <a>Data.List</a> <a>groupBy</a>.
groupBy_ :: ToSomeValues a => a -> SqlQuery ()

-- | <tt>ORDER BY</tt> clause. See also <a>asc</a> and <a>desc</a>.
--   
--   Multiple calls to <a>orderBy</a> get concatenated on the final query,
--   including <a>distinctOnOrderBy</a>.
orderBy :: [SqlExpr OrderBy] -> SqlQuery ()

-- | Ascending order of this field or SqlExpression.
asc :: PersistField a => SqlExpr (Value a) -> SqlExpr OrderBy

-- | Descending order of this field or SqlExpression.
desc :: PersistField a => SqlExpr (Value a) -> SqlExpr OrderBy
orderByExpr :: Builder -> SqlExpr (Value a) -> SqlExpr OrderBy

-- | <tt>LIMIT</tt>. Limit the number of returned rows.
limit :: Int64 -> SqlQuery ()

-- | <tt>OFFSET</tt>. Usually used with <a>limit</a>.
offset :: Int64 -> SqlQuery ()

-- | <tt>DISTINCT</tt>. Change the current <tt>SELECT</tt> into <tt>SELECT
--   DISTINCT</tt>. For example:
--   
--   <pre>
--   select $ distinct $
--     <a>from</a> \foo -&gt; do
--     ...
--   </pre>
--   
--   Note that this also has the same effect:
--   
--   <pre>
--   select $
--     <a>from</a> \foo -&gt; do
--     distinct (return ())
--     ...
--   </pre>
distinct :: SqlQuery a -> SqlQuery a

-- | <tt>DISTINCT ON</tt>. Change the current <tt>SELECT</tt> into
--   <tt>SELECT DISTINCT ON (SqlExpressions)</tt>. For example:
--   
--   <pre>
--   select $
--     <a>from</a> \foo -&gt;
--     <a>distinctOn</a> [<a>don</a> (foo ^. FooName), <a>don</a> (foo ^. FooState)] $ do
--     ...
--   </pre>
--   
--   You can also chain different calls to <a>distinctOn</a>. The above is
--   equivalent to:
--   
--   <pre>
--   select $
--     <a>from</a> \foo -&gt;
--     <a>distinctOn</a> [<a>don</a> (foo ^. FooName)] $
--     <a>distinctOn</a> [<a>don</a> (foo ^. FooState)] $ do
--     ...
--   </pre>
--   
--   Each call to <a>distinctOn</a> adds more SqlExpressions. Calls to
--   <a>distinctOn</a> override any calls to <a>distinct</a>.
--   
--   Note that PostgreSQL requires the SqlExpressions on <tt>DISTINCT
--   ON</tt> to be the first ones to appear on a <tt>ORDER BY</tt>. This is
--   not managed automatically by esqueleto, keeping its spirit of trying
--   to be close to raw SQL.
--   
--   Supported by PostgreSQL only.

-- | <i>Deprecated: This function is deprecated, as it is only supported in
--   Postgresql. Please use the variant in <a>PostgreSQL</a> instead.</i>
distinctOn :: [SqlExpr DistinctOn] -> SqlQuery a -> SqlQuery a

-- | Erase an SqlExpression's type so that it's suitable to be used by
--   <a>distinctOn</a>.
don :: SqlExpr (Value a) -> SqlExpr DistinctOn

-- | A convenience function that calls both <a>distinctOn</a> and
--   <a>orderBy</a>. In other words,
--   
--   <pre>
--   <a>distinctOnOrderBy</a> [asc foo, desc bar, desc quux] $ do
--     ...
--   </pre>
--   
--   is the same as:
--   
--   <pre>
--   <a>distinctOn</a> [don foo, don  bar, don  quux] $ do
--     <a>orderBy</a>  [asc foo, desc bar, desc quux]
--     ...
--   </pre>

-- | <i>Deprecated: This function is deprecated, as it is only supported in
--   Postgresql. Please use the function defined in <a>PostgreSQL</a>
--   instead.</i>
distinctOnOrderBy :: [SqlExpr OrderBy] -> SqlQuery a -> SqlQuery a

-- | <tt>HAVING</tt>.
having :: SqlExpr (Value Bool) -> SqlQuery ()

-- | Add a locking clause to the query. Please read <a>LockingKind</a>
--   documentation and your RDBMS manual. Unsafe since not all locking
--   clauses are implemented for every RDBMS
--   
--   If multiple calls to <a>locking</a> are made on the same query, the
--   last one is used.
locking :: LockingKind -> SqlQuery ()

-- | Helper to add a any type of locking clause to a query
putLocking :: LockingClause -> SqlQuery ()

-- | Execute a subquery <tt>SELECT</tt> in a <a>SqlExpr</a>. The query
--   passed to this function will only return a single result - it has a
--   <tt>LIMIT 1</tt> passed in to the query to make it safe, and the
--   return type is <a>Maybe</a> to indicate that the subquery might result
--   in 0 rows.
--   
--   If you find yourself writing <tt><a>joinV</a> . <a>subSelect</a></tt>,
--   then consider using <a>subSelectMaybe</a>.
--   
--   If you're performing a <a>countRows</a>, then you can use
--   <a>subSelectCount</a> which is safe.
--   
--   If you know that the subquery will always return exactly one row (eg a
--   foreign key constraint guarantees that you'll get exactly one row),
--   then consider <a>subSelectUnsafe</a>, along with a comment explaining
--   why it is safe.
subSelect :: (PersistField a, NullableFieldProjection a a') => SqlQuery (SqlExpr (Value a)) -> SqlExpr (Value (Maybe a'))

-- | Execute a subquery <tt>SELECT</tt> in a <a>SqlExpr</a>. This function
--   is a shorthand for the common <tt><a>joinV</a> . <a>subSelect</a></tt>
--   idiom, where you are calling <a>subSelect</a> on an expression that
--   would be <a>Maybe</a> already.
--   
--   As an example, you would use this function when calling <a>sum_</a> or
--   <a>max_</a>, which have <a>Maybe</a> in the result type (for a 0 row
--   query).
subSelectMaybe :: PersistField a => SqlQuery (SqlExpr (Value (Maybe a))) -> SqlExpr (Value (Maybe a))

-- | Performs a <tt>COUNT</tt> of the given query in a <tt>subSelect</tt>
--   manner. This is always guaranteed to return a result value, and is
--   completely safe.
subSelectCount :: (Num a, PersistField a) => SqlQuery ignored -> SqlExpr (Value a)

-- | Execute a subquery <tt>SELECT</tt> in a <a>SqlExpr</a> that returns a
--   list. This is an alias for <a>subList_select</a> and is provided for
--   symmetry with the other safe subselect functions.
subSelectList :: PersistField a => SqlQuery (SqlExpr (Value a)) -> SqlExpr (ValueList a)

-- | Performs a sub-select using the given foreign key on the entity. This
--   is useful to extract values that are known to be present by the
--   database schema.
--   
--   As an example, consider the following persistent definition:
--   
--   <pre>
--   User
--     profile ProfileId
--   
--   Profile
--     name    Text
--   </pre>
--   
--   The following query will return the name of the user.
--   
--   <pre>
--   getUserWithName =
--       <a>select</a> $
--       <a>from</a> $ user -&gt;
--       <a>pure</a> (user, <a>subSelectForeign</a> user UserProfile (^. ProfileName)
--   </pre>
subSelectForeign :: (BackendCompatible SqlBackend (PersistEntityBackend val1), PersistEntity val1, PersistEntity val2, PersistField a) => SqlExpr (Entity val2) -> EntityField val2 (Key val1) -> (SqlExpr (Entity val1) -> SqlExpr (Value a)) -> SqlExpr (Value a)

-- | Execute a subquery <tt>SELECT</tt> in a <a>SqlExpr</a>. This function
--   is unsafe, because it can throw runtime exceptions in two cases:
--   
--   <ol>
--   <li>If the query passed has 0 result rows, then it will return a
--   <tt>NULL</tt> value. The <tt>persistent</tt> parsing operations will
--   fail on an unexpected <tt>NULL</tt>.</li>
--   <li>If the query passed returns more than one row, then the SQL engine
--   will fail with an error like "More than one row returned by a subquery
--   used as an expression".</li>
--   </ol>
--   
--   This function is safe if you guarantee that exactly one row will be
--   returned, or if the result already has a <a>Maybe</a> type for some
--   reason.
--   
--   For variants with the safety encoded already, see <a>subSelect</a> and
--   <a>subSelectMaybe</a>. For the most common safe use of this, see
--   <a>subSelectCount</a>.
subSelectUnsafe :: PersistField a => SqlQuery (SqlExpr (Value a)) -> SqlExpr (Value a)

-- | Project a field of an entity.
(^.) :: forall typ val. (PersistEntity val, PersistField typ) => SqlExpr (Entity val) -> EntityField val typ -> SqlExpr (Value typ)
infixl 9 ^.

-- | Project an SqlExpression that may be null, guarding against null
--   cases.
withNonNull :: PersistField typ => SqlExpr (Value (Maybe typ)) -> (SqlExpr (Value typ) -> SqlQuery a) -> SqlQuery a

-- | Project an <a>EntityField</a> of a nullable entity. The result type
--   will be <a>Nullable</a>, meaning that nested <a>Maybe</a> won't be
--   produced here.
--   
--   As of v3.6.0.0, this will attempt to combine nested <a>Maybe</a>. If
--   you want to keep nested <a>Maybe</a>, then see <a>??.</a>.
(?.) :: (PersistEntity val, PersistField typ) => SqlExpr (Maybe (Entity val)) -> EntityField val typ -> SqlExpr (Value (Maybe (Nullable typ)))
infixl 9 ?.

-- | Project a field of an entity that may be null.
--   
--   This variant will produce a nested <a>Maybe</a> if you select a
--   <a>Maybe</a> column. If you want to collapse <a>Maybe</a>, see
--   <a>?.</a>.
(??.) :: (PersistEntity val, PersistField typ) => SqlExpr (Maybe (Entity val)) -> EntityField val typ -> SqlExpr (Value (Maybe typ))

-- | Lift a constant value from Haskell-land to the query.
val :: PersistField typ => typ -> SqlExpr (Value typ)

-- | <tt>IS NULL</tt> comparison.
--   
--   For <tt>IS NOT NULL</tt>, you can negate this with <a>not_</a>, as in
--   <tt>not_ (isNothing (person ^. PersonAge))</tt>
--   
--   Warning: Persistent and Esqueleto have different behavior for <tt>!=
--   Nothing</tt>:
--   
--   TODO: table
--   
--   In SQL, <tt>= NULL</tt> and <tt>!= NULL</tt> return NULL instead of
--   true or false. For this reason, you very likely do not want to use
--   <tt><a>!=.</a> Nothing</tt> in Esqueleto. You may find these
--   <tt>hlint</tt> rules helpful to enforce this:
--   
--   <pre>
--   - error: {lhs: v Database.Esqueleto.==. Database.Esqueleto.nothing, rhs: Database.Esqueleto.isNothing v, name: Use Esqueleto's isNothing}
--   - error: {lhs: v Database.Esqueleto.==. Database.Esqueleto.val Nothing, rhs: Database.Esqueleto.isNothing v, name: Use Esqueleto's isNothing}
--   - error: {lhs: v Database.Esqueleto.!=. Database.Esqueleto.nothing, rhs: not_ (Database.Esqueleto.isNothing v), name: Use Esqueleto's not isNothing}
--   - error: {lhs: v Database.Esqueleto.!=. Database.Esqueleto.val Nothing, rhs: not_ (Database.Esqueleto.isNothing v), name: Use Esqueleto's not isNothing}
--   </pre>
isNothing :: PersistField typ => SqlExpr (Value (Maybe typ)) -> SqlExpr (Value Bool)

-- | An alias for <a>isNothing</a> that avoids clashing with the function
--   from <a>Data.Maybe</a> <a>isNothing</a>.
isNothing_ :: PersistField typ => SqlExpr (Value (Maybe typ)) -> SqlExpr (Value Bool)

-- | Analogous to <a>Just</a>, promotes a value of type <tt>typ</tt> into
--   one of type <tt>Maybe typ</tt>. It should hold that <tt><a>val</a> .
--   Just === just . <a>val</a></tt>.
--   
--   This function will try not to produce a nested <a>Maybe</a>. This is
--   in accord with how SQL represents <tt>NULL</tt>. That means that
--   <tt><a>just</a> . <a>just</a> = <a>just</a></tt>. This behavior was
--   changed in v3.6.0.0. If you want to produce nested <a>Maybe</a>, see
--   <a>just'</a>.
just :: NullableFieldProjection typ typ' => SqlExpr (Value typ) -> SqlExpr (Value (Maybe typ'))

-- | Like <a>just</a>, but this function does not try to collapse nested
--   <a>Maybe</a>. This may be useful if you have type inference problems
--   with <a>just</a>.
just' :: SqlExpr (Value typ) -> SqlExpr (Value (Maybe typ))

-- | <tt>NULL</tt> value.
nothing :: SqlExpr (Value (Maybe typ))

-- | Join nested <a>Maybe</a>s in a <a>Value</a> into one. This is useful
--   when calling aggregate functions on nullable fields.
--   
--   As of v3.6.0.0, this function will attempt to work on both
--   <tt><a>SqlExpr</a> (<a>Value</a> (<a>Maybe</a> a))</tt> as well as
--   <tt><a>SqlExpr</a> (<a>Value</a> (<a>Maybe</a> (<a>Maybe</a> a)))</tt>
--   inputs to make transitioning to <a>NullableFieldProjection</a> easier.
--   This may make type inference worse in some cases. If you want the
--   monomorphic variant, see <a>joinV'</a>
joinV :: NullableFieldProjection typ typ' => SqlExpr (Value (Maybe typ)) -> SqlExpr (Value (Maybe typ'))

-- | Like <a>joinV</a>, but monomorphic: the input type only works on
--   <tt><a>SqlExpr</a> (<a>Value</a> (Maybe (Maybe a)))</tt>.
--   
--   This function may be useful if you have type inference issues with
--   <a>joinV</a>.
joinV' :: SqlExpr (Value (Maybe (Maybe typ))) -> SqlExpr (Value (Maybe typ))
countHelper :: Num a => Builder -> Builder -> SqlExpr (Value typ) -> SqlExpr (Value a)

-- | <tt>COUNT(*)</tt> value.
countRows :: Num a => SqlExpr (Value a)

-- | <tt>COUNT</tt>.
count :: Num a => SqlExpr (Value typ) -> SqlExpr (Value a)

-- | <tt>COUNT(DISTINCT x)</tt>.
countDistinct :: Num a => SqlExpr (Value typ) -> SqlExpr (Value a)
not_ :: SqlExpr (Value Bool) -> SqlExpr (Value Bool)

-- | This operator produces the SQL operator <tt>=</tt>, which is used to
--   compare values for equality.
--   
--   Example:
--   
--   <pre>
--   query :: UserId -&gt; SqlPersistT IO [Entity User]
--   query userId = select $ do
--       user &lt;- from $ table @User
--       where_ (user ^. UserId ==. val userId)
--       pure user
--   </pre>
--   
--   This would generate the following SQL:
--   
--   <pre>
--   SELECT user.*
--   FROM user
--   WHERE user.id = ?
--   </pre>
(==.) :: PersistField typ => SqlExpr (Value typ) -> SqlExpr (Value typ) -> SqlExpr (Value Bool)
infix 4 ==.

-- | This operator translates to the SQL operator <tt>&gt;=</tt>.
--   
--   Example:
--   
--   <pre>
--   where_ $ user ^. UserAge &gt;=. val 21
--   </pre>
(>=.) :: PersistField typ => SqlExpr (Value typ) -> SqlExpr (Value typ) -> SqlExpr (Value Bool)
infix 4 >=.

-- | This operator translates to the SQL operator <tt>&gt;</tt>.
--   
--   Example:
--   
--   <pre>
--   where_ $ user ^. UserAge &gt;. val 20
--   </pre>
(>.) :: PersistField typ => SqlExpr (Value typ) -> SqlExpr (Value typ) -> SqlExpr (Value Bool)
infix 4 >.

-- | This operator translates to the SQL operator <tt>&lt;=</tt>.
--   
--   Example:
--   
--   <pre>
--   where_ $ val 21 &lt;=. user ^. UserAge
--   </pre>
(<=.) :: PersistField typ => SqlExpr (Value typ) -> SqlExpr (Value typ) -> SqlExpr (Value Bool)
infix 4 <=.

-- | This operator translates to the SQL operator <tt>&lt;</tt>.
--   
--   Example:
--   
--   <pre>
--   where_ $ val 20 &lt;. user ^. UserAge
--   </pre>
(<.) :: PersistField typ => SqlExpr (Value typ) -> SqlExpr (Value typ) -> SqlExpr (Value Bool)
infix 4 <.

-- | This operator translates to the SQL operator <tt>!=</tt>.
--   
--   Example:
--   
--   <pre>
--   where_ $ user ^. UserName !=. val <a>Bob</a>
--   </pre>
(!=.) :: PersistField typ => SqlExpr (Value typ) -> SqlExpr (Value typ) -> SqlExpr (Value Bool)
infix 4 !=.

-- | This operator translates to the SQL operator <tt>AND</tt>.
--   
--   Example:
--   
--   <pre>
--   where_ $
--           user ^. UserName ==. val <a>Matt</a>
--       &amp;&amp;. user ^. UserAge &gt;=. val 21
--   </pre>
(&&.) :: SqlExpr (Value Bool) -> SqlExpr (Value Bool) -> SqlExpr (Value Bool)
infixr 3 &&.

-- | This operator translates to the SQL operator <tt>AND</tt>.
--   
--   Example:
--   
--   <pre>
--   where_ $
--           user ^. UserName ==. val <a>Matt</a>
--       ||. user ^. UserName ==. val <a>John</a>
--   </pre>
(||.) :: SqlExpr (Value Bool) -> SqlExpr (Value Bool) -> SqlExpr (Value Bool)
infixr 2 ||.

-- | This operator translates to the SQL operator <tt>+</tt>.
--   
--   This does not require or assume anything about the SQL values.
--   Interpreting what <tt>+.</tt> means for a given type is left to the
--   database engine.
--   
--   Example:
--   
--   <pre>
--   user ^. UserAge +. val 10
--   </pre>
(+.) :: PersistField a => SqlExpr (Value a) -> SqlExpr (Value a) -> SqlExpr (Value a)
infixl 6 +.

-- | This operator translates to the SQL operator <tt>-</tt>.
--   
--   This does not require or assume anything about the SQL values.
--   Interpreting what <tt>-.</tt> means for a given type is left to the
--   database engine.
--   
--   Example:
--   
--   <pre>
--   user ^. UserAge -. val 10
--   </pre>
(-.) :: PersistField a => SqlExpr (Value a) -> SqlExpr (Value a) -> SqlExpr (Value a)
infixl 6 -.

-- | This operator translates to the SQL operator <tt>/</tt>.
--   
--   This does not require or assume anything about the SQL values.
--   Interpreting what <tt>/.</tt> means for a given type is left to the
--   database engine.
--   
--   Example:
--   
--   <pre>
--   user ^. UserAge /. val 10
--   </pre>
(/.) :: PersistField a => SqlExpr (Value a) -> SqlExpr (Value a) -> SqlExpr (Value a)
infixl 7 /.

-- | This operator translates to the SQL operator <tt>*</tt>.
--   
--   This does not require or assume anything about the SQL values.
--   Interpreting what <tt>*.</tt> means for a given type is left to the
--   database engine.
--   
--   Example:
--   
--   <pre>
--   user ^. UserAge *. val 10
--   </pre>
(*.) :: PersistField a => SqlExpr (Value a) -> SqlExpr (Value a) -> SqlExpr (Value a)
infixl 7 *.

-- | <tt>a <a>between</a> (b, c)</tt> translates to the SQL expression
--   <tt>a &gt;= b AND a &lt;= c</tt>. It does not use a SQL
--   <tt>BETWEEN</tt> operator.
--   
--   @since: 3.1.0
between :: PersistField a => SqlExpr (Value a) -> (SqlExpr (Value a), SqlExpr (Value a)) -> SqlExpr (Value Bool)
round_ :: (PersistField a, Num a, PersistField b, Num b) => SqlExpr (Value a) -> SqlExpr (Value b)
ceiling_ :: (PersistField a, Num a, PersistField b, Num b) => SqlExpr (Value a) -> SqlExpr (Value b)
floor_ :: (PersistField a, Num a, PersistField b, Num b) => SqlExpr (Value a) -> SqlExpr (Value b)
sum_ :: (PersistField a, PersistField b) => SqlExpr (Value a) -> SqlExpr (Value (Maybe b))
min_ :: PersistField a => SqlExpr (Value a) -> SqlExpr (Value (Maybe (Nullable a)))
max_ :: PersistField a => SqlExpr (Value a) -> SqlExpr (Value (Maybe (Nullable a)))
avg_ :: (PersistField a, PersistField b) => SqlExpr (Value a) -> SqlExpr (Value (Maybe b))

-- | Allow a number of one type to be used as one of another type via an
--   implicit cast. An explicit cast is not made, this function changes
--   only the types on the Haskell side.
--   
--   <i>Caveat</i>: Trying to use <tt>castNum</tt> from <tt>Double</tt> to
--   <tt>Int</tt> will not result in an integer, the original fractional
--   number will still be used! Use <a>round_</a>, <a>ceiling_</a> or
--   <a>floor_</a> instead.
--   
--   <i>Safety</i>: This operation is mostly safe due to the <a>Num</a>
--   constraint between the types and the fact that RDBMSs usually allow
--   numbers of different types to be used interchangeably. However, there
--   may still be issues with the query not being accepted by the RDBMS or
--   <tt>persistent</tt> not being able to parse it.
castNum :: (Num a, Num b) => SqlExpr (Value a) -> SqlExpr (Value b)

-- | Same as <a>castNum</a>, but for nullable values.
castNumM :: (Num a, Num b) => SqlExpr (Value (Maybe a)) -> SqlExpr (Value (Maybe b))

-- | <tt>COALESCE</tt> function. Evaluates the arguments in order and
--   returns the value of the first non-NULL SqlExpression, or NULL
--   (Nothing) otherwise. Some RDBMSs (such as SQLite) require at least two
--   arguments; please refer to the appropriate documentation.
coalesce :: (PersistField a, NullableFieldProjection a a') => [SqlExpr (Value (Maybe a))] -> SqlExpr (Value (Maybe a'))

-- | Like <tt>coalesce</tt>, but takes a non-nullable SqlExpression placed
--   at the end of the SqlExpression list, which guarantees a non-NULL
--   result.
coalesceDefault :: PersistField a => [SqlExpr (Value (Maybe a))] -> SqlExpr (Value a) -> SqlExpr (Value a)

-- | <tt>LOWER</tt> function.
lower_ :: SqlString s => SqlExpr (Value s) -> SqlExpr (Value s)

-- | <tt>UPPER</tt> function. @since 3.3.0
upper_ :: SqlString s => SqlExpr (Value s) -> SqlExpr (Value s)

-- | <tt>TRIM</tt> function. @since 3.3.0
trim_ :: SqlString s => SqlExpr (Value s) -> SqlExpr (Value s)

-- | <tt>RTRIM</tt> function. @since 3.3.0
rtrim_ :: SqlString s => SqlExpr (Value s) -> SqlExpr (Value s)

-- | <tt>LTRIM</tt> function. @since 3.3.0
ltrim_ :: SqlString s => SqlExpr (Value s) -> SqlExpr (Value s)

-- | <tt>LENGTH</tt> function. @since 3.3.0
length_ :: (SqlString s, Num a) => SqlExpr (Value s) -> SqlExpr (Value a)

-- | <tt>LEFT</tt> function. @since 3.3.0
left_ :: (SqlString s, Num a) => (SqlExpr (Value s), SqlExpr (Value a)) -> SqlExpr (Value s)

-- | <tt>RIGHT</tt> function. @since 3.3.0
right_ :: (SqlString s, Num a) => (SqlExpr (Value s), SqlExpr (Value a)) -> SqlExpr (Value s)

-- | <tt>LIKE</tt> operator.
like :: SqlString s => SqlExpr (Value s) -> SqlExpr (Value s) -> SqlExpr (Value Bool)
infixr 2 `like`

-- | <tt>ILIKE</tt> operator (case-insensitive <tt>LIKE</tt>).
--   
--   Supported by PostgreSQL only. Deprecated in version 3.6.0 in favor of
--   the version available from <a>Database.Esqueleto.PostgreSQL</a>.

-- | <i>Deprecated: Since 3.6.0: <a>ilike</a> is only supported on
--   Postgres. Please import it from 'Database.Esqueleto.PostgreSQL.</i>
ilike :: SqlString s => SqlExpr (Value s) -> SqlExpr (Value s) -> SqlExpr (Value Bool)
infixr 2 `ilike`

-- | The string <tt><a>%</a></tt>. May be useful while using <a>like</a>
--   and concatenation (<a>concat_</a> or <a>++.</a>, depending on your
--   database). Note that you always have to type the parenthesis, for
--   example:
--   
--   <pre>
--   name `<a>like</a>` (%) ++. <a>val</a> "John" ++. (%)
--   </pre>
(%) :: SqlString s => SqlExpr (Value s)

-- | The <tt>CONCAT</tt> function with a variable number of parameters.
--   Supported by MySQL and PostgreSQL. SQLite supports this in versions
--   after 3.44.0, and <tt>persistent-sqlite</tt> supports this in versions
--   <tt>2.13.3.0</tt> and after.
concat_ :: SqlString s => [SqlExpr (Value s)] -> SqlExpr (Value s)

-- | The <tt>||</tt> string concatenation operator (named after Haskell's
--   <a>++</a> in order to avoid naming clash with <a>||.</a>).
--   
--   Supported by SQLite and PostgreSQL.
--   
--   MySQL support requires setting the SQL mode to
--   <tt>PIPES_AS_CONCAT</tt> or <tt>ANSI</tt> - see <a>this StackOverflow
--   answer</a>.
(++.) :: SqlString s => SqlExpr (Value s) -> SqlExpr (Value s) -> SqlExpr (Value s)
infixr 5 ++.

-- | Cast a string type into <a>Text</a>. This function is very useful if
--   you want to use <tt>newtype</tt>s, or if you want to apply functions
--   such as <a>like</a> to strings of different types.
--   
--   <i>Safety:</i> This is a slightly unsafe function, especially if you
--   have defined your own instances of <a>SqlString</a>. Also, since
--   <a>Maybe</a> is an instance of <a>SqlString</a>, it's possible to turn
--   a nullable value into a non-nullable one. Avoid using this function if
--   possible.
castString :: (SqlString s, SqlString r) => SqlExpr (Value s) -> SqlExpr (Value r)

-- | Execute a subquery <tt>SELECT</tt> in an SqlExpression. Returns a list
--   of values.
subList_select :: PersistField a => SqlQuery (SqlExpr (Value a)) -> SqlExpr (ValueList a)

-- | Lift a list of constant value from Haskell-land to the query.
valList :: PersistField typ => [typ] -> SqlExpr (ValueList typ)

-- | Same as <a>just</a> but for <a>ValueList</a>. Most of the time you
--   won't need it, though, because you can use <a>just</a> from inside
--   <a>subList_select</a> or <a>Just</a> from inside <a>valList</a>.
justList :: SqlExpr (ValueList typ) -> SqlExpr (ValueList (Maybe typ))

-- | <tt>IN</tt> operator. For example if you want to select all
--   <tt>Person</tt>s by a list of IDs:
--   
--   <pre>
--   SELECT *
--   FROM Person
--   WHERE Person.id IN (?)
--   </pre>
--   
--   In <tt>esqueleto</tt>, we may write the same query above as:
--   
--   <pre>
--   select $
--   <a>from</a> $ \person -&gt; do
--   <a>where_</a> $ person <a>^.</a> PersonId `<tt>in_</tt>` <a>valList</a> personIds
--   return person
--   </pre>
--   
--   Where <tt>personIds</tt> is of type <tt>[Key Person]</tt>.
in_ :: PersistField typ => SqlExpr (Value typ) -> SqlExpr (ValueList typ) -> SqlExpr (Value Bool)

-- | <tt>NOT IN</tt> operator.
notIn :: PersistField typ => SqlExpr (Value typ) -> SqlExpr (ValueList typ) -> SqlExpr (Value Bool)

-- | <tt>EXISTS</tt> operator. For example:
--   
--   <pre>
--   select $
--   <a>from</a> $ \person -&gt; do
--   <a>where_</a> $ <a>exists</a> $
--            <a>from</a> $ \post -&gt; do
--            <a>where_</a> (post <a>^.</a> BlogPostAuthorId <a>==.</a> person <a>^.</a> PersonId)
--   return person
--   </pre>
exists :: SqlQuery () -> SqlExpr (Value Bool)

-- | <tt>NOT EXISTS</tt> operator.
notExists :: SqlQuery () -> SqlExpr (Value Bool)

-- | <tt>SET</tt> clause used on <tt>UPDATE</tt>s. Note that while it's not
--   a type error to use this function on a <tt>SELECT</tt>, it will most
--   certainly result in a runtime error.
set :: PersistEntity val => SqlExpr (Entity val) -> [SqlExpr (Entity val) -> SqlExpr Update] -> SqlQuery ()
(=.) :: (PersistEntity val, PersistField typ) => EntityField val typ -> SqlExpr (Value typ) -> SqlExpr (Entity val) -> SqlExpr Update
infixr 3 =.
(+=.) :: (PersistEntity val, PersistField a) => EntityField val a -> SqlExpr (Value a) -> SqlExpr (Entity val) -> SqlExpr Update
infixr 3 +=.
(-=.) :: (PersistEntity val, PersistField a) => EntityField val a -> SqlExpr (Value a) -> SqlExpr (Entity val) -> SqlExpr Update
infixr 3 -=.
(*=.) :: (PersistEntity val, PersistField a) => EntityField val a -> SqlExpr (Value a) -> SqlExpr (Entity val) -> SqlExpr Update
infixr 3 *=.
(/=.) :: (PersistEntity val, PersistField a) => EntityField val a -> SqlExpr (Value a) -> SqlExpr (Entity val) -> SqlExpr Update
infixr 3 /=.

-- | Apply a <a>PersistField</a> constructor to <tt>SqlExpr Value</tt>
--   arguments.
(<#) :: (a -> b) -> SqlExpr (Value a) -> SqlExpr (Insertion b)

-- | Apply extra <tt>SqlExpr Value</tt> arguments to a <a>PersistField</a>
--   constructor
(<&>) :: SqlExpr (Insertion (a -> b)) -> SqlExpr (Value a) -> SqlExpr (Insertion b)

-- | <tt>CASE</tt> statement. For example:
--   
--   <pre>
--   select $
--   return $
--   <a>case_</a>
--      [ <a>when_</a>
--          (<a>exists</a> $
--          <a>from</a> $ \p -&gt; do
--          <a>where_</a> (p <a>^.</a> PersonName <a>==.</a> <a>val</a> "Mike"))
--        <a>then_</a>
--          (<a>subSelect</a> $
--          <a>from</a> $ \v -&gt; do
--          let sub =
--                  <a>from</a> $ \c -&gt; do
--                  <a>where_</a> (c <a>^.</a> PersonName <a>==.</a> <a>val</a> "Mike")
--                  return (c <a>^.</a> PersonFavNum)
--          <a>where_</a> (<a>just</a> (v <a>^.</a> PersonFavNum) &gt;. <a>subSelect</a> sub)
--          return $ <a>count</a> (v <a>^.</a> PersonName) +. <a>val</a> (1 :: Int)) ]
--      (<a>else_</a> $ <a>val</a> (-1))
--   </pre>
--   
--   This query is a bit complicated, but basically it checks if a person
--   named <tt>"Mike"</tt> exists, and if that person does, run the
--   subquery to find out how many people have a ranking (by Fav Num)
--   higher than <tt>"Mike"</tt>.
--   
--   <b>NOTE:</b> There are a few things to be aware about this statement.
--   
--   <ul>
--   <li>This only implements the full CASE statement, it does not
--   implement the "simple" CASE statement.</li>
--   <li>At least one <a>when_</a> and <a>then_</a> is mandatory otherwise
--   it will emit an error.</li>
--   <li>The <a>else_</a> is also mandatory, unlike the SQL statement in
--   which if the <tt>ELSE</tt> is omitted it will return a <tt>NULL</tt>.
--   You can reproduce this via <a>nothing</a>.</li>
--   </ul>
case_ :: PersistField a => [(SqlExpr (Value Bool), SqlExpr (Value a))] -> SqlExpr (Value a) -> SqlExpr (Value a)

-- | Convert an entity's key into another entity's.
--   
--   This function is to be used when you change an entity's <tt>Id</tt> to
--   be that of another entity. For example:
--   
--   <pre>
--   Bar
--     barNum Int
--   Foo
--     bar BarId
--     fooNum Int
--     Primary bar
--   </pre>
--   
--   In this example, Bar is said to be the BaseEnt(ity), and Foo the
--   child. To model this in Esqueleto, declare:
--   
--   <pre>
--   instance ToBaseId Foo where
--     type BaseEnt Foo = Bar
--     toBaseIdWitness barId = FooKey barId
--   </pre>
--   
--   Now you're able to write queries such as:
--   
--   <pre>
--   <a>select</a> $
--   <a>from</a> $ (bar `<tt>InnerJoin</tt>` foo) -&gt; do
--   <a>on</a> (<a>toBaseId</a> (foo <a>^.</a> FooId) <a>==.</a> bar <a>^.</a> BarId)
--   return (bar, foo)
--   </pre>
--   
--   Note: this function may be unsafe to use in conditions not like the
--   one of the example above.
toBaseId :: ToBaseId ent => SqlExpr (Value (Key ent)) -> SqlExpr (Value (Key (BaseEnt ent)))

-- | Like <a>toBaseId</a>, but works on <a>Maybe</a> keys.
toBaseIdMaybe :: ToBaseId ent => SqlExpr (Value (Maybe (Key ent))) -> SqlExpr (Value (Maybe (Key (BaseEnt ent))))

-- | The inverse of <a>toBaseId</a>. Note that this is somewhat less "safe"
--   than <a>toBaseId</a>. Calling <a>toBaseId</a> will usually mean that a
--   foreign key constraint is present that guarantees the presence of the
--   base ID. <a>fromBaseId</a> has no such guarantee. Consider the code
--   example given in <a>toBaseId</a>:
--   
--   <pre>
--   Bar
--     barNum Int
--   Foo
--     bar BarId
--     fooNum Int
--     Primary bar
--   </pre>
--   
--   <pre>
--   instance ToBaseId Foo where
--     type BaseEnt Foo = Bar
--     toBaseIdWitness barId = FooKey barId
--   </pre>
--   
--   The type of <a>toBaseId</a> for <tt>Foo</tt> would be:
--   
--   <pre>
--   toBaseId :: SqlExpr (Value FooId) -&gt; SqlExpr (Value BarId)
--   </pre>
--   
--   The foreign key constraint on <tt>Foo</tt> means that every
--   <tt>FooId</tt> points to a <tt>BarId</tt> in the database. However,
--   <a>fromBaseId</a> will not have this:
--   
--   <pre>
--   fromBaseId :: SqlExpr (Value BarId) -&gt; SqlExpr (Value FooId)
--   </pre>
fromBaseId :: ToBaseId ent => SqlExpr (Value (Key (BaseEnt ent))) -> SqlExpr (Value (Key ent))

-- | As <a>fromBaseId</a>, but works on <a>Maybe</a> keys.
fromBaseIdMaybe :: ToBaseId ent => SqlExpr (Value (Maybe (Key (BaseEnt ent)))) -> SqlExpr (Value (Maybe (Key ent)))

-- | Syntax sugar for <a>case_</a>.
when_ :: expr (Value Bool) -> () -> expr a -> (expr (Value Bool), expr a)

-- | Syntax sugar for <a>case_</a>.
then_ :: ()

-- | Syntax sugar for <a>case_</a>.
else_ :: expr a -> expr a

-- | A single value (as opposed to a whole entity). You may use
--   <tt>(<a>^.</a>)</tt> or <tt>(<a>?.</a>)</tt> to get a <a>Value</a>
--   from an <a>Entity</a>.
newtype Value a
Value :: a -> Value a
[unValue] :: Value a -> a

-- | A list of single values. There's a limited set of functions able to
--   work with this data type (such as <a>subList_select</a>,
--   <a>valList</a>, <a>in_</a> and <a>exists</a>).
newtype ValueList a
ValueList :: a -> ValueList a

-- | A wrapper type for for any <tt>expr (Value a)</tt> for all a.
data SomeValue
[SomeValue] :: forall a. SqlExpr (Value a) -> SomeValue

-- | A class of things that can be converted into a list of SomeValue. It
--   has instances for tuples and is the reason why <a>groupBy</a> can take
--   tuples, like <tt><a>groupBy</a> (foo <a>^.</a> FooId, foo <a>^.</a>
--   FooName, foo <a>^.</a> FooType)</tt>.
class ToSomeValues a
toSomeValues :: ToSomeValues a => a -> [SomeValue]
type family KnowResult a

-- | A class for constructors or function which result type is known.
class FinalResult a
finalR :: FinalResult a => a -> KnowResult a

-- | Convert a constructor for a <a>Unique</a> key on a record to the
--   <a>UniqueDef</a> that defines it. You can supply just the constructor
--   itself, or a value of the type - the library is capable of figuring it
--   out from there.
toUniqueDef :: (KnowResult a ~ Unique val, PersistEntity val, FinalResult a) => a -> UniqueDef

-- | Render updates to be use in a SET clause for a given sql backend.
renderUpdates :: BackendCompatible SqlBackend backend => backend -> [SqlExpr (Entity val) -> SqlExpr Update] -> (Builder, [PersistValue])

-- | Data type that represents an <tt>INNER JOIN</tt> (see
--   <a>LeftOuterJoin</a> for an example).
data InnerJoin a b
InnerJoin :: a -> b -> InnerJoin a b
infixl 2 `InnerJoin`
infixl 2 `InnerJoin`

-- | Data type that represents a <tt>CROSS JOIN</tt> (see
--   <a>LeftOuterJoin</a> for an example).
data CrossJoin a b
CrossJoin :: a -> b -> CrossJoin a b
infixl 2 `CrossJoin`
infixl 2 `CrossJoin`

-- | Data type that represents a <tt>LEFT OUTER JOIN</tt>. For example,
--   
--   <pre>
--   select $
--   <a>from</a> $ \(person `<tt>LeftOuterJoin</tt>` pet) -&gt;
--     ...
--   </pre>
--   
--   is translated into
--   
--   <pre>
--   SELECT ...
--   FROM Person LEFT OUTER JOIN Pet
--   ...
--   </pre>
--   
--   See also: <a>from</a>.
data LeftOuterJoin a b
LeftOuterJoin :: a -> b -> LeftOuterJoin a b
infixl 2 `LeftOuterJoin`
infixl 2 `LeftOuterJoin`

-- | Data type that represents a <tt>RIGHT OUTER JOIN</tt> (see
--   <a>LeftOuterJoin</a> for an example).
data RightOuterJoin a b
RightOuterJoin :: a -> b -> RightOuterJoin a b
infixl 2 `RightOuterJoin`
infixl 2 `RightOuterJoin`

-- | Data type that represents a <tt>FULL OUTER JOIN</tt> (see
--   <a>LeftOuterJoin</a> for an example).
data FullOuterJoin a b
FullOuterJoin :: a -> b -> FullOuterJoin a b
infixl 2 `FullOuterJoin`
infixl 2 `FullOuterJoin`

-- | (Internal) A kind of <tt>JOIN</tt>.
data JoinKind

-- | <pre>
--   INNER JOIN
--   </pre>
InnerJoinKind :: JoinKind

-- | <pre>
--   CROSS JOIN
--   </pre>
CrossJoinKind :: JoinKind

-- | <pre>
--   LEFT OUTER JOIN
--   </pre>
LeftOuterJoinKind :: JoinKind

-- | <pre>
--   RIGHT OUTER JOIN
--   </pre>
RightOuterJoinKind :: JoinKind

-- | <pre>
--   FULL OUTER JOIN
--   </pre>
FullOuterJoinKind :: JoinKind

-- | (Internal) Functions that operate on types (that should be) of kind
--   <a>JoinKind</a>.
class IsJoinKind (join :: Type -> Type -> Type)

-- | (Internal) <tt>smartJoin a b</tt> is a <tt>JOIN</tt> of the correct
--   kind.
smartJoin :: IsJoinKind join => a -> b -> join a b

-- | (Internal) Reify a <tt>JoinKind</tt> from a <tt>JOIN</tt>. This
--   function is non-strict.
reifyJoinKind :: IsJoinKind join => join a b -> JoinKind

-- | Exception thrown whenever <a>on</a> is used to create an <tt>ON</tt>
--   clause but no matching <tt>JOIN</tt> is found.
data OnClauseWithoutMatchingJoinException
OnClauseWithoutMatchingJoinException :: String -> OnClauseWithoutMatchingJoinException

-- | Phantom type used by <a>orderBy</a>, <a>asc</a> and <a>desc</a>.
data OrderBy

-- | Phantom type used by <a>distinctOn</a> and <a>don</a>.
data DistinctOn

-- | Phantom type for a <tt>SET</tt> operation on an entity of the given
--   type (see <a>set</a> and <a>(=.)</a>).
data Update

-- | Phantom type used by <a>insertSelect</a>.
data Insertion a

-- | A left-precedence pair. Pronounced "and". Used to represent
--   expressions that have been joined together.
--   
--   The precedence behavior can be demonstrated by:
--   
--   <pre>
--   a :&amp; b :&amp; c == ((a :&amp; b) :&amp; c)
--   </pre>
--   
--   See the examples at the beginning of this module to see how this
--   operator is used in <tt>JOIN</tt> operations.
data a :& b
(:&) :: a -> b -> (:&) a b
infixl 2 :&
infixl 2 :&

-- | Different kinds of locking clauses supported by <a>locking</a>.
--   
--   Note that each RDBMS has different locking support. The constructors
--   of this datatype specify only the <i>syntax</i> of the locking
--   mechanism, not its <i>semantics</i>. For example, even though both
--   MySQL and PostgreSQL support <a>ForUpdate</a>, there are no guarantees
--   that they will behave the same.
data LockingKind

-- | <tt>FOR UPDATE</tt> syntax. Supported by MySQL, Oracle and PostgreSQL.

-- | <i>Deprecated: The constructors for <a>LockingKind</a> are deprecated
--   in v3.6.0.0. Instead, please refer to the smart constructors
--   <a>forUpdate</a> and <a>forUpdateSkipLocked</a>.</i>
ForUpdate :: LockingKind

-- | <tt>FOR UPDATE SKIP LOCKED</tt> syntax. Supported by MySQL, Oracle and
--   PostgreSQL.

-- | <i>Deprecated: The constructors for <a>LockingKind</a> are deprecated
--   in v3.6.0.0. Instead, please refer to the smart constructors
--   <a>forUpdate</a> and <a>forUpdateSkipLocked</a>.</i>
ForUpdateSkipLocked :: LockingKind

-- | <tt>FOR SHARE</tt> syntax. Supported by PostgreSQL.

-- | <i>Deprecated: The constructors for <a>LockingKind</a> are deprecated
--   in v3.6.0.0. Instead, please refer to the smart constructor
--   <tt>forShare</tt> exported from Database.Esqueleto.PostgreSQL.</i>
ForShare :: LockingKind

-- | <tt>LOCK IN SHARE MODE</tt> syntax. Supported by MySQL.

-- | <i>Deprecated: The constructors for <a>LockingKind</a> are deprecated
--   in v3.6.0.0. Instead, please refer to the smart constructors
--   <tt>lockInShareMode</tt> exported from Database.Esqueleto.MySQL.</i>
LockInShareMode :: LockingKind

-- | <tt>FOR UPDATE</tt> syntax.
--   
--   Usage:
--   
--   <pre>
--   <a>locking</a> <a>forUpdate</a>
--   </pre>
forUpdate :: LockingKind

-- | <tt>FOR UPDATE SKIP LOCKED</tt> syntax.
--   
--   <pre>
--   <a>locking</a> <a>forUpdateSkipLocked</a>
--   </pre>
forUpdateSkipLocked :: LockingKind

-- | Postgres specific locking, used only internally
data PostgresLockingKind
PostgresLockingKind :: PostgresRowLevelLockStrength -> Maybe LockingOfClause -> OnLockedBehavior -> PostgresLockingKind
[postgresRowLevelLockStrength] :: PostgresLockingKind -> PostgresRowLevelLockStrength
[postgresLockingOfClause] :: PostgresLockingKind -> Maybe LockingOfClause
[postgresOnLockedBehavior] :: PostgresLockingKind -> OnLockedBehavior
data PostgresRowLevelLockStrength
PostgresForUpdate :: PostgresRowLevelLockStrength
PostgresForNoKeyUpdate :: PostgresRowLevelLockStrength
PostgresForShare :: PostgresRowLevelLockStrength
PostgresForKeyShare :: PostgresRowLevelLockStrength
data LockingOfClause
[LockingOfClause] :: forall a. LockableEntity a => a -> LockingOfClause
data OnLockedBehavior

-- | <tt>NOWAIT</tt> syntax locking behaviour. query excutes immediately
--   failing on locked rows
NoWait :: OnLockedBehavior

-- | <tt>SKIP LOCKED</tt> syntax locking behaviour. query skips locked rows
SkipLocked :: OnLockedBehavior

-- | default locking behaviour. query will wait on locked rows
Wait :: OnLockedBehavior

-- | Lockable entity
--   
--   Example use:
--   
--   <pre>
--   select $ do
--       (p :&amp; bp) &lt;- from $
--           table <tt>Person
--           <tt>innerJoin</tt> table </tt>BlogPost
--               <a>on</a> do
--                   (p :&amp; bp) -&gt; p ^. PersonId ==. b ^. BlogPostAuthorId
--       forUpdateOf (p :&amp; b) skipLocked
--       return p
--   </pre>
class LockableEntity a
flattenLockableEntity :: LockableEntity a => a -> NonEmpty LockableSqlExpr
makeLockableEntity :: LockableEntity a => IdentInfo -> a -> (Builder, [PersistValue])
data LockableSqlExpr
[LockableSqlExpr] :: forall val. PersistEntity val => SqlExpr (Entity val) -> LockableSqlExpr

-- | Phantom class of data types that are treated as strings by the RDBMS.
--   It has no methods because it's only used to avoid type errors such as
--   trying to concatenate integers.
--   
--   If you have a custom data type or <tt>newtype</tt>, feel free to make
--   it an instance of this class.
class PersistField a => SqlString a

-- | Class that enables one to use <a>toBaseId</a> to convert an entity's
--   key on a query into another (cf. <a>toBaseId</a>).
class ToBaseId ent where {
    
    -- | e.g. <tt>type BaseEnt MyBase = MyChild</tt>
    type BaseEnt ent;
}

-- | Convert from the key of the BaseEnt(ity) to the key of the child
--   entity. This function is not actually called, but that it typechecks
--   proves this operation is safe.
toBaseIdWitness :: ToBaseId ent => Key (BaseEnt ent) -> Key ent

-- | <tt>FROM</tt> clause: bring entities into scope.
--   
--   Note that this function will be replaced by the one in
--   <a>Database.Esqueleto.Experimental</a> in version 4.0.0.0 of the
--   library. The <tt>Experimental</tt> module has a dramatically improved
--   means for introducing tables and entities that provides more power and
--   less potential for runtime errors.
--   
--   This function internally uses two type classes in order to provide
--   some flexibility of how you may call it. Internally we refer to these
--   type classes as the two different magics.
--   
--   The innermost magic allows you to use <tt>from</tt> with the following
--   types:
--   
--   <ul>
--   <li><tt>expr (Entity val)</tt>, which brings a single entity into
--   scope.</li>
--   <li><tt>expr (Maybe (Entity val))</tt>, which brings a single entity
--   that may be <tt>NULL</tt> into scope. Used for <tt>OUTER
--   JOIN</tt>s.</li>
--   <li>A <tt>JOIN</tt> of any other two types allowed by the innermost
--   magic, where a <tt>JOIN</tt> may be an <a>InnerJoin</a>, a
--   <a>CrossJoin</a>, a <a>LeftOuterJoin</a>, a <a>RightOuterJoin</a>, or
--   a <a>FullOuterJoin</a>. The <tt>JOINs</tt> have left fixity.</li>
--   </ul>
--   
--   The outermost magic allows you to use <tt>from</tt> on any tuples of
--   types supported by innermost magic (and also tuples of tuples, and so
--   on), up to 8-tuples.
--   
--   Note that using <tt>from</tt> for the same entity twice does work and
--   corresponds to a self-join. You don't even need to use two different
--   calls to <tt>from</tt>, you may use a <tt>JOIN</tt> or a tuple.
--   
--   The following are valid examples of uses of <tt>from</tt> (the types
--   of the arguments of the lambda are inside square brackets):
--   
--   <pre>
--   <a>from</a> $ \person -&gt; ...
--   <a>from</a> $ \(person, blogPost) -&gt; ...
--   <a>from</a> $ \(p `<a>LeftOuterJoin</a>` mb) -&gt; ...
--   <a>from</a> $ \(p1 `<a>InnerJoin</a>` f `<a>InnerJoin</a>` p2) -&gt; ...
--   <a>from</a> $ \((p1 `<a>InnerJoin</a>` f) `<a>InnerJoin</a>` p2) -&gt; ...
--   </pre>
--   
--   The types of the arguments to the lambdas above are, respectively:
--   
--   <pre>
--   person
--     :: ( Esqueleto query expr backend
--        , PersistEntity Person
--        , PersistEntityBackend Person ~ backend
--        ) =&gt; expr (Entity Person)
--   (person, blogPost)
--     :: (...) =&gt; (expr (Entity Person), expr (Entity BlogPost))
--   (p `<a>LeftOuterJoin</a>` mb)
--     :: (...) =&gt; InnerJoin (expr (Entity Person)) (expr (Maybe (Entity BlogPost)))
--   (p1 `<a>InnerJoin</a>` f `<a>InnerJoin</a>` p2)
--     :: (...) =&gt; InnerJoin
--                   (InnerJoin (expr (Entity Person))
--                              (expr (Entity Follow)))
--                   (expr (Entity Person))
--   (p1 `<a>InnerJoin</a>` (f `<a>InnerJoin</a>` p2)) ::
--     :: (...) =&gt; InnerJoin
--                   (expr (Entity Person))
--                   (InnerJoin (expr (Entity Follow))
--                              (expr (Entity Person)))
--   </pre>
--   
--   Note that some backends may not support all kinds of <tt>JOIN</tt>s.
from :: From a => (a -> SqlQuery b) -> SqlQuery b

-- | (Internal) Class that implements the tuple <a>from</a> magic (see
--   <a>fromStart</a>).
class From a
from_ :: From a => SqlQuery a

-- | (Internal) Class that implements the <tt>JOIN</tt> <a>from</a> magic
--   (see <a>fromStart</a>).
class FromPreprocess a
fromPreprocess :: FromPreprocess a => SqlQuery (PreprocessedFrom a)

-- | Exception data type for <tt>esqueleto</tt> internal errors
data EsqueletoError
CompositeKeyErr :: CompositeKeyError -> EsqueletoError
AliasedValueErr :: UnexpectedValueError -> EsqueletoError
UnexpectedCaseErr :: UnexpectedCaseError -> EsqueletoError
SqlBinOpCompositeErr :: SqlBinOpCompositeError -> EsqueletoError
data UnexpectedValueError
NotError :: UnexpectedValueError
ToInsertionError :: UnexpectedValueError
CombineInsertionError :: UnexpectedValueError
FoldHelpError :: UnexpectedValueError
SqlCaseError :: UnexpectedValueError
SqlCastAsError :: UnexpectedValueError
SqlFunctionError :: UnexpectedValueError
MakeOnClauseError :: UnexpectedValueError
MakeExcError :: UnexpectedValueError
MakeSetError :: UnexpectedValueError
MakeWhereError :: UnexpectedValueError
MakeHavingError :: UnexpectedValueError
FilterWhereAggError :: UnexpectedValueError
FilterWhereClauseError :: UnexpectedValueError
type CompositeKeyError = UnexpectedValueError
data UnexpectedCaseError
EmptySqlExprValueList :: UnexpectedCaseError
MakeFromError :: UnexpectedCaseError
UnsupportedSqlInsertIntoType :: UnexpectedCaseError
InsertionFinalError :: UnexpectedCaseError
NewIdentForError :: UnexpectedCaseError
UnsafeSqlCaseError :: UnexpectedCaseError
OperationNotSupported :: UnexpectedCaseError
NotImplemented :: UnexpectedCaseError
data SqlBinOpCompositeError
MismatchingLengthsError :: SqlBinOpCompositeError
NullPlaceholdersError :: SqlBinOpCompositeError
DeconstructionError :: SqlBinOpCompositeError

-- | SQL backend for <tt>esqueleto</tt> using <a>SqlPersistT</a>.
newtype SqlQuery a
Q :: WriterT SideData (State IdentState) a -> SqlQuery a
[unQ] :: SqlQuery a -> WriterT SideData (State IdentState) a

-- | Constraint synonym for <tt>persistent</tt> entities whose backend is
--   <a>SqlBackend</a>.
type SqlEntity ent = (PersistEntity ent, PersistEntityBackend ent ~ SqlBackend)

-- | Side data written by <a>SqlQuery</a>.
data SideData
SideData :: !DistinctClause -> ![FromClause] -> ![SetClause] -> !WhereClause -> !GroupByClause -> !HavingClause -> ![OrderByClause] -> !LimitClause -> !LockingClause -> ![CommonTableExpressionClause] -> SideData
[sdDistinctClause] :: SideData -> !DistinctClause
[sdFromClause] :: SideData -> ![FromClause]
[sdSetClause] :: SideData -> ![SetClause]
[sdWhereClause] :: SideData -> !WhereClause
[sdGroupByClause] :: SideData -> !GroupByClause
[sdHavingClause] :: SideData -> !HavingClause
[sdOrderByClause] :: SideData -> ![OrderByClause]
[sdLimitClause] :: SideData -> !LimitClause
[sdLockingClause] :: SideData -> !LockingClause
[sdCteClause] :: SideData -> ![CommonTableExpressionClause]

-- | The <tt>DISTINCT</tt> "clause".
data DistinctClause

-- | The default, everything.
DistinctAll :: DistinctClause

-- | Only <tt>DISTINCT</tt>, SQL standard.
DistinctStandard :: DistinctClause

-- | <tt>DISTINCT ON</tt>, PostgreSQL extension.
DistinctOn :: [SqlExpr DistinctOn] -> DistinctClause

-- | A part of a <tt>FROM</tt> clause.
data FromClause
FromStart :: Ident -> EntityDef -> FromClause
FromJoin :: FromClause -> JoinKind -> FromClause -> Maybe (SqlExpr (Value Bool)) -> FromClause
OnClause :: SqlExpr (Value Bool) -> FromClause
FromRaw :: (NeedParens -> IdentInfo -> (Builder, [PersistValue])) -> FromClause
data CommonTableExpressionKind
RecursiveCommonTableExpression :: CommonTableExpressionKind
NormalCommonTableExpression :: CommonTableExpressionKind
type CommonTableExpressionModifierAfterAs = CommonTableExpressionClause -> IdentInfo -> Builder
data CommonTableExpressionClause
CommonTableExpressionClause :: CommonTableExpressionKind -> CommonTableExpressionModifierAfterAs -> Ident -> (IdentInfo -> (Builder, [PersistValue])) -> CommonTableExpressionClause
data SubQueryType
NormalSubQuery :: SubQueryType
LateralSubQuery :: SubQueryType
collectIdents :: FromClause -> Set Ident

-- | A part of a <tt>SET</tt> clause.
newtype SetClause
SetClause :: SqlExpr Update -> SetClause

-- | Collect <a>OnClause</a>s on <a>FromJoin</a>s. Returns the first
--   unmatched <a>OnClause</a>s data on error. Returns a list without
--   <tt>OnClauses</tt> on success.
collectOnClauses :: SqlBackend -> [FromClause] -> Either (SqlExpr (Value Bool)) [FromClause]

-- | A complete <tt>WHERE</tt> clause.
data WhereClause
Where :: SqlExpr (Value Bool) -> WhereClause
NoWhere :: WhereClause

-- | A <tt>GROUP BY</tt> clause.
newtype GroupByClause
GroupBy :: [SomeValue] -> GroupByClause

-- | A <tt>HAVING</tt> cause.
type HavingClause = WhereClause

-- | A <tt>ORDER BY</tt> clause.
type OrderByClause = SqlExpr OrderBy

-- | A <tt>LIMIT</tt> clause.
data LimitClause
Limit :: Maybe Int64 -> Maybe Int64 -> LimitClause

-- | A locking clause.
data LockingClause

-- | Locking clause not specific to any database implementation
LegacyLockingClause :: LockingKind -> LockingClause

-- | Locking clause specific to postgres
PostgresLockingClauses :: [PostgresLockingKind] -> LockingClause
NoLockingClause :: LockingClause

-- | Identifier used for table names.
newtype Ident
I :: Text -> Ident

-- | List of identifiers already in use and supply of temporary
--   identifiers.
newtype IdentState
IdentState :: HashSet Text -> IdentState
[inUse] :: IdentState -> HashSet Text
initialIdentState :: IdentState

-- | Create a fresh <a>Ident</a>. If possible, use the given <a>DBName</a>.
newIdentFor :: DBName -> SqlQuery Ident

-- | Information needed to escape and use identifiers.
type IdentInfo = (SqlBackend, IdentState)

-- | Use an identifier.
useIdent :: IdentInfo -> Ident -> Builder
data SqlExprMeta
SqlExprMeta :: Maybe (IdentInfo -> [Builder]) -> Maybe Ident -> Bool -> SqlExprMeta
[sqlExprMetaCompositeFields] :: SqlExprMeta -> Maybe (IdentInfo -> [Builder])
[sqlExprMetaAlias] :: SqlExprMeta -> Maybe Ident
[sqlExprMetaIsReference] :: SqlExprMeta -> Bool

-- | Empty <a>SqlExprMeta</a> if you are constructing an <a>ERaw</a>
--   probably use this for your meta
noMeta :: SqlExprMeta

-- | Does this meta contain values for composite fields. This field is
--   field out for composite key values
hasCompositeKeyMeta :: SqlExprMeta -> Bool
entityAsValue :: SqlExpr (Entity val) -> SqlExpr (Value (Entity val))
entityAsValueMaybe :: SqlExpr (Maybe (Entity val)) -> SqlExpr (Value (Maybe (Entity val)))

-- | An expression on the SQL backend.
--   
--   Raw expression: Contains a <a>SqlExprMeta</a> and a function for
--   building the expr. It recieves a parameter telling it whether it is in
--   a parenthesized context, and takes information about the SQL
--   connection (mainly for escaping names) and returns both an string
--   (<a>Builder</a>) and a list of values to be interpolated by the SQL
--   backend.
data SqlExpr a
ERaw :: SqlExprMeta -> (NeedParens -> IdentInfo -> (Builder, [PersistValue])) -> SqlExpr a

-- | The type <tt><a>SqlExpr</a> a</tt> represents a SQL expression that
--   evaluates to a value that can be parsed in Haskell to an <tt>a</tt>.
--   There are often many underlying SQL values that can parse exactly. The
--   function <a>veryUnsafeCoerceSqlExpr</a> allows you to change this
--   type.
--   
--   There is no guarantee that the result works! To be safe, you want to
--   provide a local helper function that calls this at a tested type.
--   
--   As an example, you may know that two types share an identical SQL
--   representation, and can be parsed exactly the same way. Perhaps you
--   have a <tt>data SomeEnum</tt> which you represent as a <tt>TEXT</tt>
--   in Postgres, and you want to treat it as a <tt>TEXT</tt>. You could
--   define a top-level type-restricted alias to this which allows this to
--   be done safely:
--   
--   <pre>
--   enumToText :: SqlExpr (Value SomeEnum) -&gt; SqlExpr (Value Text)
--   enumToText = veryUnsafeCoerceSqlExpr
--   </pre>
--   
--   Note that this is fragile: if you change the encoding of
--   <tt>SomeEnum</tt> to be anything other than <a>Text</a>, then your
--   code will fail at runtime.
veryUnsafeCoerceSqlExpr :: SqlExpr a -> SqlExpr b

-- | While <a>veryUnsafeCoerceSqlExpr</a> allows you to coerce anything at
--   all, this requires that the two types are <a>Coercible</a> in Haskell.
--   This is not truly safe: after all, the point of <tt>newtype</tt> is to
--   allow you to provide different instances of classes like
--   <a>PersistFieldSql</a> and <a>SqlSelect</a>. Using this may break your
--   code if you change the underlying SQL representation.
unsafeCoerceSqlExpr :: Coercible a b => SqlExpr a -> SqlExpr b

-- | Like <a>unsafeCoerceSqlExpr</a> but for the common case where you are
--   coercing a <a>Value</a>.
unsafeCoerceSqlExprValue :: Coercible a b => SqlExpr (Value a) -> SqlExpr (Value b)

-- | The type error message given when you try to do <a>fmap</a> on a
--   <a>SqlExpr</a>. This is intended to guide folks towards the docs,
--   which should guide them towards alternative implementations.
type SqlExprFunctorMessage = 'Text "You're trying to treat `SqlExpr` like a `Functor`, but it cannot be one." ':$$: 'Text "We would need to send arbitrary functions to the database for interpretation to support that instance." ':$$: 'Text "See the docs for the fake instance of `Functor SqlExpr` for more information." ':$$: 'Text "Consider using a SQL function with `unsafeSqlFunction` and a good type signature."

-- | The <a>NullableFieldProjection</a> type is used to determine whether a
--   <a>Maybe</a> should be stripped off or not. This is used in the
--   <a>HasField</a> for <tt><a>SqlExpr</a> (<a>Maybe</a> (<a>Entity</a>
--   a))</tt> to allow you to only have a single level of <a>Maybe</a>.
--   
--   <pre>
--   MyTable
--     column         Int Maybe
--     someTableId    SomeTableId
--   
--    select $ do
--        (_ :&amp; maybeMyTable) &lt;-
--            from $ table <tt>SomeTable
--                <tt>leftJoin</tt> table </tt>MyTable
--                    <a>on</a> do
--                        (someTable :&amp; maybeMyTable) -&gt;
--                            just someTable.id ==. maybeMyTable.someTableId
--          where_ $ maybeMyTable.column ==. just (val 10)
--          pure maybeMyTable
--   </pre>
--   
--   Without this class, projecting a field with type <tt><a>Maybe</a>
--   typ</tt> would have resulted in a <tt><a>SqlExpr</a> (<a>Value</a>
--   (<a>Maybe</a> (<a>Maybe</a> typ)))</tt>.
class NullableFieldProjection typ typ'

-- | Data type to support from hack
data PreprocessedFrom a
PreprocessedFrom :: a -> FromClause -> PreprocessedFrom a

-- | Phantom type used to mark a <tt>INSERT INTO</tt> query.
data InsertFinal
data NeedParens
Parens :: NeedParens
Never :: NeedParens
parensM :: NeedParens -> Builder -> Builder
data OrderByType
ASC :: OrderByType
DESC :: OrderByType
fieldName :: (PersistEntity val, PersistField typ) => IdentInfo -> EntityField val typ -> Builder
setAux :: (PersistEntity val, PersistField typ) => EntityField val typ -> (SqlExpr (Entity val) -> SqlExpr (Value typ)) -> SqlExpr (Entity val) -> SqlExpr Update
sub :: PersistField a => Mode -> SqlQuery (SqlExpr (Value a)) -> SqlExpr (Value a)
fromDBName :: IdentInfo -> DBName -> Builder
existsHelper :: SqlQuery () -> SqlExpr (Value Bool)

-- | (Internal) Create a case statement.
--   
--   Since: 2.1.1
unsafeSqlCase :: PersistField a => [(SqlExpr (Value Bool), SqlExpr (Value a))] -> SqlExpr (Value a) -> SqlExpr (Value a)

-- | (Internal) Create a custom binary operator. You <i>should</i>
--   <i>not</i> use this function directly since its type is very general,
--   you should always use it with an explicit type signature. For example:
--   
--   <pre>
--   (==.) :: SqlExpr (Value a) -&gt; SqlExpr (Value a) -&gt; SqlExpr (Value Bool)
--   (==.) = unsafeSqlBinOp " = "
--   </pre>
--   
--   In the example above, we constraint the arguments to be of the same
--   type and constraint the result to be a boolean value.
unsafeSqlBinOp :: Builder -> SqlExpr (Value a) -> SqlExpr (Value b) -> SqlExpr (Value c)

-- | Similar to <a>unsafeSqlBinOp</a>, but may also be applied to composite
--   keys. Uses the operator given as the second argument whenever applied
--   to composite keys.
--   
--   Usage example:
--   
--   <pre>
--   (==.) :: SqlExpr (Value a) -&gt; SqlExpr (Value a) -&gt; SqlExpr (Value Bool)
--   (==.) = unsafeSqlBinOpComposite " = " " AND "
--   </pre>
--   
--   Persistent has a hack for implementing composite keys (see
--   <tt>ECompositeKey</tt> doc for more details), so we're forced to use a
--   hack here as well. We deconstruct <a>ERaw</a> values based on two
--   rules:
--   
--   <ul>
--   <li>If it is a single placeholder, then it's assumed to be coming from
--   a <a>PersistList</a> and thus its components are separated so that
--   they may be applied to a composite key.</li>
--   <li>If it is not a single placeholder, then it's assumed to be a
--   foreign (composite or not) key, so we enforce that it has no
--   placeholders and split it on the commas.</li>
--   </ul>
unsafeSqlBinOpComposite :: Builder -> Builder -> SqlExpr (Value a) -> SqlExpr (Value b) -> SqlExpr (Value c)

-- | (Internal) A raw SQL value. The same warning from
--   <a>unsafeSqlBinOp</a> applies to this function as well.
unsafeSqlValue :: Builder -> SqlExpr (Value a)
unsafeSqlEntity :: PersistEntity ent => Ident -> SqlExpr (Entity ent)
valueToFunctionArg :: IdentInfo -> SqlExpr (Value a) -> (Builder, [PersistValue])

-- | (Internal) A raw SQL function. Once again, the same warning from
--   <a>unsafeSqlBinOp</a> applies to this function as well.
unsafeSqlFunction :: UnsafeSqlFunctionArgument a => Builder -> a -> SqlExpr (Value b)

-- | (Internal) An unsafe SQL function to extract a subfield from a
--   compound field, e.g. datetime. See <a>unsafeSqlBinOp</a> for warnings.
--   
--   Since: 1.3.6.
unsafeSqlExtractSubField :: UnsafeSqlFunctionArgument a => Builder -> a -> SqlExpr (Value b)

-- | (Internal) A raw SQL function. Preserves parentheses around arguments.
--   See <a>unsafeSqlBinOp</a> for warnings.
unsafeSqlFunctionParens :: UnsafeSqlFunctionArgument a => Builder -> a -> SqlExpr (Value b)

-- | (Internal) An explicit SQL type cast using CAST(value as type). See
--   <a>unsafeSqlBinOp</a> for warnings.
unsafeSqlCastAs :: Text -> SqlExpr (Value a) -> SqlExpr (Value b)

-- | (Internal) This class allows <a>unsafeSqlFunction</a> to work with
--   different numbers of arguments; specifically it allows providing
--   arguments to a sql function via an n-tuple of <tt>SqlExpr (Value
--   _)</tt> values, which are not all necessarily required to be the same
--   type. There are instances for up to 10-tuples, but for sql functions
--   which take more than 10 arguments, you can also nest tuples, as e.g.
--   <tt>toArgList ((a,b),(c,d))</tt> is the same as <tt>toArgList
--   (a,b,c,d)</tt>.
class UnsafeSqlFunctionArgument a
toArgList :: UnsafeSqlFunctionArgument a => a -> [SqlExpr (Value ())]

-- | (Internal) Coerce a value's type from 'SqlExpr (Value a)' to 'SqlExpr
--   (Value b)'. You should <i>not</i> use this function unless you know
--   what you're doing!
--   
--   This is an alias for <a>veryUnsafeCoerceSqlExpr</a> with the type
--   fixed to <a>Value</a>.
veryUnsafeCoerceSqlExprValue :: SqlExpr (Value a) -> SqlExpr (Value b)

-- | (Internal) Coerce a value's type from 'SqlExpr (ValueList a)' to
--   'SqlExpr (Value a)'. Does not work with empty lists.
--   
--   This is an alias for <a>veryUnsafeCoerceSqlExpr</a>, with the type
--   fixed to <a>ValueList</a> and <a>Value</a>.
veryUnsafeCoerceSqlExprValueList :: SqlExpr (ValueList a) -> SqlExpr (Value a)

-- | (Internal) Execute an <tt>esqueleto</tt> <tt>SELECT</tt>
--   <a>SqlQuery</a> inside <tt>persistent</tt>'s <a>SqlPersistT</a> monad.
rawSelectSource :: forall a r (m1 :: Type -> Type) (m2 :: Type -> Type) backend. (SqlSelect a r, MonadIO m1, MonadIO m2, SqlBackendCanRead backend) => Mode -> SqlQuery a -> ReaderT backend m1 (Acquire (ConduitT () r m2 ()))

-- | Execute an <tt>esqueleto</tt> <tt>SELECT</tt> query inside
--   <tt>persistent</tt>'s <a>SqlPersistT</a> monad and return a
--   <a>Source</a> of rows.
selectSource :: forall a r backend (m :: Type -> Type). (SqlSelect a r, BackendCompatible SqlBackend backend, IsPersistBackend backend, PersistQueryRead backend, PersistStoreRead backend, PersistUniqueRead backend, MonadResource m) => SqlQuery a -> ConduitT () r (ReaderT backend m) ()

-- | Execute an <tt>esqueleto</tt> <tt>SELECT</tt> query inside
--   <tt>persistent</tt>'s <a>SqlPersistT</a> monad and return a list of
--   rows.
--   
--   We've seen that <a>from</a> has some magic about which kinds of things
--   you may bring into scope. This <a>select</a> function also has some
--   magic for which kinds of things you may bring back to Haskell-land by
--   using <tt>SqlQuery</tt>'s <tt>return</tt>:
--   
--   <ul>
--   <li>You may return a <tt>SqlExpr (<a>Entity</a> v)</tt> for an entity
--   <tt>v</tt> (i.e., like the <tt>*</tt> in SQL), which is then returned
--   to Haskell-land as just <tt>Entity v</tt>.</li>
--   <li>You may return a <tt>SqlExpr (Maybe (Entity v))</tt> for an entity
--   <tt>v</tt> that may be <tt>NULL</tt>, which is then returned to
--   Haskell-land as <tt>Maybe (Entity v)</tt>. Used for <tt>OUTER
--   JOIN</tt>s.</li>
--   <li>You may return a <tt>SqlExpr (<a>Value</a> t)</tt> for a value
--   <tt>t</tt> (i.e., a single column), where <tt>t</tt> is any instance
--   of <a>PersistField</a>, which is then returned to Haskell-land as
--   <tt>Value t</tt>. You may use <tt>Value</tt> to return projections of
--   an <tt>Entity</tt> (see <tt>(<a>^.</a>)</tt> and <tt>(<a>?.</a>)</tt>)
--   or to return any other value calculated on the query (e.g.,
--   <a>countRows</a> or <a>subSelect</a>).</li>
--   </ul>
--   
--   The <tt>SqlSelect a r</tt> class has functional dependencies that
--   allow type information to flow both from <tt>a</tt> to <tt>r</tt> and
--   vice-versa. This means that you'll almost never have to give any type
--   signatures for <tt>esqueleto</tt> queries. For example, the query
--   <tt><a>select</a> $ from $ \p -&gt; return p</tt> alone is ambiguous,
--   but in the context of
--   
--   <pre>
--   do ps &lt;- <a>select</a> $
--            <a>from</a> $ \p -&gt;
--            return p
--      liftIO $ mapM_ (putStrLn . personName . entityVal) ps
--   </pre>
--   
--   we are able to infer from that single <tt>personName . entityVal</tt>
--   function composition that the <tt>p</tt> inside the query is of type
--   <tt>SqlExpr (Entity Person)</tt>.
select :: forall a r (m :: Type -> Type) backend. (SqlSelect a r, MonadIO m, SqlBackendCanRead backend) => SqlQuery a -> ReaderT backend m [r]

-- | Execute an <tt>esqueleto</tt> <tt>SELECT</tt> query inside
--   <tt>persistent</tt>'s <a>SqlPersistT</a> monad and return the first
--   entry wrapped in a <tt>Maybe</tt>. @since 3.5.1.0
--   
--   <h3><b>Example usage</b></h3>
--   
--   <pre>
--   firstPerson :: MonadIO m =&gt; SqlPersistT m (Maybe (Entity Person))
--   firstPerson =
--    <a>selectOne</a> $ do
--        person &lt;- <a>from</a> $ <tt>table</tt> @Person
--        return person
--   </pre>
--   
--   The above query is equivalent to a <a>select</a> combined with
--   <a>limit</a> but you would still have to transform the results from a
--   list:
--   
--   <pre>
--   firstPerson :: MonadIO m =&gt; SqlPersistT m [Entity Person]
--   firstPerson =
--    <a>select</a> $ do
--        person &lt;- <a>from</a> $ <tt>table</tt> @Person
--        <a>limit</a> 1
--        return person
--   </pre>
selectOne :: forall a r (m :: Type -> Type) backend. (SqlSelect a r, MonadIO m, SqlBackendCanRead backend) => SqlQuery a -> ReaderT backend m (Maybe r)

-- | (Internal) Run a <a>Source</a> of rows.
runSource :: forall (m :: Type -> Type) r backend. Monad m => ConduitT () r (ReaderT backend m) () -> ReaderT backend m [r]

-- | (Internal) Execute an <tt>esqueleto</tt> statement inside
--   <tt>persistent</tt>'s <a>SqlPersistT</a> monad.
rawEsqueleto :: forall (m :: Type -> Type) a r backend. (MonadIO m, SqlSelect a r, BackendCompatible SqlBackend backend) => Mode -> SqlQuery a -> ReaderT backend m Int64

-- | Execute an <tt>esqueleto</tt> <tt>DELETE</tt> query inside
--   <tt>persistent</tt>'s <a>SqlPersistT</a> monad. Note that currently
--   there are no type checks for statements that should not appear on a
--   <tt>DELETE</tt> query.
--   
--   Example of usage:
--   
--   <pre>
--   <a>delete</a> $
--   <a>from</a> $ \appointment -&gt;
--   <a>where_</a> (appointment <a>^.</a> AppointmentDate <a>&lt;.</a> <a>val</a> now)
--   </pre>
--   
--   Unlike <a>select</a>, there is a useful way of using <a>delete</a>
--   that will lead to type ambiguities. If you want to delete all rows
--   (i.e., no <a>where_</a> clause), you'll have to use a type signature:
--   
--   <pre>
--   <a>delete</a> $
--   <a>from</a> $ \(appointment :: <a>SqlExpr</a> (<a>Entity</a> Appointment)) -&gt;
--   return ()
--   </pre>
--   
--   <h4><a>Database.Esqueleto.Experimental</a>:</h4>
--   
--   <pre>
--   delete $ do
--     userFeature &lt;- from $ table @UserFeature
--     where_ ((userFeature ^. UserFeatureFeature) <a>notIn</a> valList allKnownFeatureFlags)
--   </pre>
delete :: forall (m :: Type -> Type) backend. (MonadIO m, SqlBackendCanWrite backend) => SqlQuery () -> ReaderT backend m ()

-- | Same as <a>delete</a>, but returns the number of rows affected.
deleteCount :: forall (m :: Type -> Type) backend. (MonadIO m, SqlBackendCanWrite backend) => SqlQuery () -> ReaderT backend m Int64

-- | Execute an <tt>esqueleto</tt> <tt>UPDATE</tt> query inside
--   <tt>persistent</tt>'s <a>SqlPersistT</a> monad. Note that currently
--   there are no type checks for statements that should not appear on a
--   <tt>UPDATE</tt> query.
--   
--   Example of usage:
--   
--   <pre>
--   <a>update</a> $ \p -&gt; do
--   <a>set</a> p [ PersonAge <a>=.</a> <a>just</a> (<a>val</a> thisYear) -. p <a>^.</a> PersonBorn ]
--   <a>where_</a> $ isNothing (p <a>^.</a> PersonAge)
--   </pre>
update :: forall (m :: Type -> Type) val backend. (MonadIO m, PersistEntity val, BackendCompatible SqlBackend (PersistEntityBackend val), SqlBackendCanWrite backend) => (SqlExpr (Entity val) -> SqlQuery ()) -> ReaderT backend m ()

-- | Same as <a>update</a>, but returns the number of rows affected.
updateCount :: forall (m :: Type -> Type) val backend. (MonadIO m, PersistEntity val, BackendCompatible SqlBackend (PersistEntityBackend val), SqlBackendCanWrite backend) => (SqlExpr (Entity val) -> SqlQuery ()) -> ReaderT backend m Int64
builderToText :: Builder -> Text

-- | (Internal) Pretty prints a <a>SqlQuery</a> into a SQL query.
--   
--   Note: if you're curious about the SQL query being generated by
--   <tt>esqueleto</tt>, instead of manually using this function (which is
--   possible but tedious), see the <a>renderQueryToText</a> function
--   (along with <a>renderQuerySelect</a>, <a>renderQueryUpdate</a>, etc).
toRawSql :: (SqlSelect a r, BackendCompatible SqlBackend backend) => Mode -> (backend, IdentState) -> SqlQuery a -> (Builder, [PersistValue])

-- | Renders a <a>SqlQuery</a> into a <a>Text</a> value along with the list
--   of <a>PersistValue</a>s that would be supplied to the database for
--   <tt>?</tt> placeholders.
--   
--   You must ensure that the <a>Mode</a> you pass to this function
--   corresponds with the actual <a>SqlQuery</a>. If you pass a query that
--   uses incompatible features (like an <tt>INSERT</tt> statement with a
--   <tt>SELECT</tt> mode) then you'll get a weird result.
renderQueryToText :: forall a r backend (m :: Type -> Type). (SqlSelect a r, BackendCompatible SqlBackend backend, Monad m) => Mode -> SqlQuery a -> ReaderT backend m (Text, [PersistValue])

-- | Renders a <a>SqlQuery</a> into a <a>Text</a> value along with the list
--   of <a>PersistValue</a>s that would be supplied to the database for
--   <tt>?</tt> placeholders.
renderQuerySelect :: forall a r backend (m :: Type -> Type). (SqlSelect a r, BackendCompatible SqlBackend backend, Monad m) => SqlQuery a -> ReaderT backend m (Text, [PersistValue])

-- | Renders a <a>SqlQuery</a> into a <a>Text</a> value along with the list
--   of <a>PersistValue</a>s that would be supplied to the database for
--   <tt>?</tt> placeholders.
renderQueryDelete :: forall a r backend (m :: Type -> Type). (SqlSelect a r, BackendCompatible SqlBackend backend, Monad m) => SqlQuery a -> ReaderT backend m (Text, [PersistValue])

-- | Renders a <a>SqlQuery</a> into a <a>Text</a> value along with the list
--   of <a>PersistValue</a>s that would be supplied to the database for
--   <tt>?</tt> placeholders.
renderQueryUpdate :: forall a r backend (m :: Type -> Type). (SqlSelect a r, BackendCompatible SqlBackend backend, Monad m) => SqlQuery a -> ReaderT backend m (Text, [PersistValue])

-- | Renders a <a>SqlQuery</a> into a <a>Text</a> value along with the list
--   of <a>PersistValue</a>s that would be supplied to the database for
--   <tt>?</tt> placeholders.
renderQueryInsertInto :: forall a r backend (m :: Type -> Type). (SqlSelect a r, BackendCompatible SqlBackend backend, Monad m) => SqlQuery a -> ReaderT backend m (Text, [PersistValue])

-- | (Internal) Mode of query being converted by <a>toRawSql</a>.
data Mode
SELECT :: Mode
DELETE :: Mode
UPDATE :: Mode
INSERT_INTO :: Mode
uncommas :: [Builder] -> Builder
intersperseB :: Builder -> [Builder] -> Builder
uncommas' :: Monoid a => [(Builder, a)] -> (Builder, a)
makeCte :: IdentInfo -> [CommonTableExpressionClause] -> (Builder, [PersistValue])
makeInsertInto :: SqlSelect a r => IdentInfo -> Mode -> a -> (Builder, [PersistValue])
makeSelect :: SqlSelect a r => IdentInfo -> Mode -> DistinctClause -> a -> (Builder, [PersistValue])
makeFrom :: IdentInfo -> Mode -> [FromClause] -> (Builder, [PersistValue])
makeSet :: IdentInfo -> [SetClause] -> (Builder, [PersistValue])
makeWhere :: IdentInfo -> WhereClause -> (Builder, [PersistValue])
makeGroupBy :: IdentInfo -> GroupByClause -> (Builder, [PersistValue])
makeHaving :: IdentInfo -> WhereClause -> (Builder, [PersistValue])
makeOrderByNoNewline :: IdentInfo -> [OrderByClause] -> (Builder, [PersistValue])
makeOrderBy :: IdentInfo -> [OrderByClause] -> (Builder, [PersistValue])
makeLimit :: IdentInfo -> LimitClause -> (Builder, [PersistValue])
makeLocking :: IdentInfo -> LockingClause -> (Builder, [PersistValue])
parens :: Builder -> Builder
aliasedEntityColumnIdent :: Ident -> FieldDef -> Ident
aliasedColumnName :: Ident -> IdentInfo -> Text -> Builder

-- | (Internal) Class for mapping results coming from <a>SqlQuery</a> into
--   actual results.
--   
--   This looks very similar to <tt>RawSql</tt>, and it is! However, there
--   are some crucial differences and ultimately they're different classes.
class SqlSelect a r | a -> r, r -> a

-- | Creates the variable part of the <tt>SELECT</tt> query and returns the
--   list of <a>PersistValue</a>s that will be given to <a>rawQuery</a>.
sqlSelectCols :: SqlSelect a r => IdentInfo -> a -> (Builder, [PersistValue])

-- | Number of columns that will be consumed.
sqlSelectColCount :: SqlSelect a r => Proxy a -> Int

-- | Transform a row of the result into the data type.
sqlSelectProcessRow :: SqlSelect a r => [PersistValue] -> Either Text r

-- | Create <tt>INSERT INTO</tt> clause instead.
sqlInsertInto :: SqlSelect a r => IdentInfo -> a -> (Builder, [PersistValue])
unescapedColumnNames :: EntityDef -> [DBName]
getEntityVal :: Proxy (SqlExpr (Entity a)) -> Proxy a

-- | Materialize a <tt>SqlExpr (Value a)</tt>.
materializeExpr :: IdentInfo -> SqlExpr (Value a) -> (Builder, [PersistValue])
from3P :: Proxy (a, b, c) -> Proxy ((a, b), c)
from3 :: (a, b, c) -> ((a, b), c)
to3 :: ((a, b), c) -> (a, b, c)
from4P :: Proxy (a, b, c, d) -> Proxy ((a, b), (c, d))
from4 :: (a, b, c, d) -> ((a, b), (c, d))
to4 :: ((a, b), (c, d)) -> (a, b, c, d)
from5P :: Proxy (a, b, c, d, e) -> Proxy ((a, b), (c, d), e)
from5 :: (a, b, c, d, e) -> ((a, b), (c, d), e)
to5 :: ((a, b), (c, d), e) -> (a, b, c, d, e)
from6P :: Proxy (a, b, c, d, e, f) -> Proxy ((a, b), (c, d), (e, f))
from6 :: (a, b, c, d, e, f) -> ((a, b), (c, d), (e, f))
to6 :: ((a, b), (c, d), (e, f)) -> (a, b, c, d, e, f)
from7P :: Proxy (a, b, c, d, e, f, g) -> Proxy ((a, b), (c, d), (e, f), g)
from7 :: (a, b, c, d, e, f, g) -> ((a, b), (c, d), (e, f), g)
to7 :: ((a, b), (c, d), (e, f), g) -> (a, b, c, d, e, f, g)
from8P :: Proxy (a, b, c, d, e, f, g, h) -> Proxy ((a, b), (c, d), (e, f), (g, h))
from8 :: (a, b, c, d, e, f, g, h) -> ((a, b), (c, d), (e, f), (g, h))
to8 :: ((a, b), (c, d), (e, f), (g, h)) -> (a, b, c, d, e, f, g, h)
from9P :: Proxy (a, b, c, d, e, f, g, h, i) -> Proxy ((a, b), (c, d), (e, f), (g, h), i)
from9 :: (a, b, c, d, e, f, g, h, i) -> ((a, b), (c, d), (e, f), (g, h), i)
to9 :: ((a, b), (c, d), (e, f), (g, h), i) -> (a, b, c, d, e, f, g, h, i)
from10P :: Proxy (a, b, c, d, e, f, g, h, i, j) -> Proxy ((a, b), (c, d), (e, f), (g, h), (i, j))
from10 :: (a, b, c, d, e, f, g, h, i, j) -> ((a, b), (c, d), (e, f), (g, h), (i, j))
to10 :: ((a, b), (c, d), (e, f), (g, h), (i, j)) -> (a, b, c, d, e, f, g, h, i, j)
from11P :: Proxy (a, b, c, d, e, f, g, h, i, j, k) -> Proxy ((a, b), (c, d), (e, f), (g, h), (i, j), k)
from11 :: (a, b, c, d, e, f, g, h, i, j, k) -> ((a, b), (c, d), (e, f), (g, h), (i, j), k)
to11 :: ((a, b), (c, d), (e, f), (g, h), (i, j), k) -> (a, b, c, d, e, f, g, h, i, j, k)
from12P :: Proxy (a, b, c, d, e, f, g, h, i, j, k, l) -> Proxy ((a, b), (c, d), (e, f), (g, h), (i, j), (k, l))
from12 :: (a, b, c, d, e, f, g, h, i, j, k, l) -> ((a, b), (c, d), (e, f), (g, h), (i, j), (k, l))
to12 :: ((a, b), (c, d), (e, f), (g, h), (i, j), (k, l)) -> (a, b, c, d, e, f, g, h, i, j, k, l)
from13P :: Proxy (a, b, c, d, e, f, g, h, i, j, k, l, m) -> Proxy ((a, b), (c, d), (e, f), (g, h), (i, j), (k, l), m)
from13 :: (a, b, c, d, e, f, g, h, i, j, k, l, m) -> ((a, b), (c, d), (e, f), (g, h), (i, j), (k, l), m)
to13 :: ((a, b), (c, d), (e, f), (g, h), (i, j), (k, l), m) -> (a, b, c, d, e, f, g, h, i, j, k, l, m)
from14P :: Proxy (a, b, c, d, e, f, g, h, i, j, k, l, m, n) -> Proxy ((a, b), (c, d), (e, f), (g, h), (i, j), (k, l), (m, n))
from14 :: (a, b, c, d, e, f, g, h, i, j, k, l, m, n) -> ((a, b), (c, d), (e, f), (g, h), (i, j), (k, l), (m, n))
to14 :: ((a, b), (c, d), (e, f), (g, h), (i, j), (k, l), (m, n)) -> (a, b, c, d, e, f, g, h, i, j, k, l, m, n)
from15P :: Proxy (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) -> Proxy ((a, b), (c, d), (e, f), (g, h), (i, j), (k, l), (m, n), o)
from15 :: (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) -> ((a, b), (c, d), (e, f), (g, h), (i, j), (k, l), (m, n), o)
to15 :: ((a, b), (c, d), (e, f), (g, h), (i, j), (k, l), (m, n), o) -> (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o)
from16P :: Proxy (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) -> Proxy ((a, b), (c, d), (e, f), (g, h), (i, j), (k, l), (m, n), (o, p))
from16 :: (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) -> ((a, b), (c, d), (e, f), (g, h), (i, j), (k, l), (m, n), (o, p))
to16 :: ((a, b), (c, d), (e, f), (g, h), (i, j), (k, l), (m, n), (o, p)) -> (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p)

-- | Insert a <a>PersistField</a> for every selected value.
insertSelect :: forall (m :: Type -> Type) a backend. (MonadIO m, PersistEntity a, SqlBackendCanWrite backend) => SqlQuery (SqlExpr (Insertion a)) -> ReaderT backend m ()

-- | Insert a <a>PersistField</a> for every selected value, return the
--   count afterward
insertSelectCount :: forall (m :: Type -> Type) a backend. (MonadIO m, PersistEntity a, SqlBackendCanWrite backend) => SqlQuery (SqlExpr (Insertion a)) -> ReaderT backend m Int64

-- | Renders an expression into <a>Text</a>. Only useful for creating a
--   textual representation of the clauses passed to an <a>On</a> clause.
renderExpr :: SqlBackend -> SqlExpr (Value Bool) -> Text

-- | An exception thrown by <tt>RenderExpr</tt> - it's not designed to
--   handle composite keys, and will blow up if you give it one.
data RenderExprException
RenderExprUnexpectedECompositeKey :: Text -> RenderExprException

-- | <tt>valkey i = <a>val</a> . <a>toSqlKey</a></tt>
--   (<a>https://github.com/prowdsponsor/esqueleto/issues/9</a>).
valkey :: (ToBackendKey SqlBackend entity, PersistField (Key entity)) => Int64 -> SqlExpr (Value (Key entity))

-- | <tt>valJ</tt> is like <tt>val</tt> but for something that is already a
--   <tt>Value</tt>. The use case it was written for was, given a
--   <tt>Value</tt> lift the <tt>Key</tt> for that <tt>Value</tt> into the
--   query expression in a type safe way. However, the implementation is
--   more generic than that so we call it <tt>valJ</tt>.
--   
--   Its important to note that the input entity and the output entity are
--   constrained to be the same by the type signature on the function
--   (<a>https://github.com/prowdsponsor/esqueleto/pull/69</a>).
valJ :: PersistField (Key entity) => Value (Key entity) -> SqlExpr (Value (Key entity))

-- | Synonym for <a>delete</a> that does not clash with
--   <tt>esqueleto</tt>'s <a>delete</a>.
deleteKey :: forall backend val (m :: Type -> Type). (PersistStore backend, BaseBackend backend ~ PersistEntityBackend val, MonadIO m, PersistEntity val) => Key val -> ReaderT backend m ()

-- | Avoid N+1 queries and join entities into a map structure.
--   
--   This function is useful to call on the result of a single
--   <tt>JOIN</tt>. For example, suppose you have this query:
--   
--   <pre>
--   getFoosAndNestedBarsFromParent
--       :: ParentId
--       -&gt; SqlPersistT IO [(Entity Foo, Maybe (Entity Bar))]
--   getFoosAndNestedBarsFromParent parentId =
--       <a>select</a> $ do
--           (foo :&amp; bar) &lt;- from $
--               table <tt>Foo
--               <a>`LeftOuterJoin`</a>
--               table </tt>Bar
--                   <a>`on`</a> do
--                       \(foo :&amp; bar) -&gt;
--                           foo ^. FooId ==. bar ?. BarFooId
--           where_ $
--               foo ^. FooParentId ==. val parentId
--           pure (foo, bar)
--   </pre>
--   
--   This is a natural result type for SQL - a list of tuples. However,
--   it's not what we usually want in Haskell - each <tt>Foo</tt> in the
--   list will be represented multiple times, once for each <tt>Bar</tt>.
--   
--   We can write <tt><a>fmap</a> <a>associateJoin</a></tt> and it will
--   translate it into a <tt>Map</tt> that is keyed on the <a>Key</a> of
--   the left <a>Entity</a>, and the value is a tuple of the entity's value
--   as well as the list of each coresponding entity.
--   
--   <pre>
--   getFoosAndNestedBarsFromParentHaskellese
--       :: ParentId
--       -&gt; SqlPersistT (Map (Key Foo) (Foo, [Maybe (Entity Bar)]))
--   getFoosAndNestedBarsFromParentHaskellese parentId =
--       <a>fmap</a> <a>associateJoin</a> $ getFoosdAndNestedBarsFromParent parentId
--   </pre>
--   
--   What if you have multiple joins?
--   
--   Let's use <a>associateJoin</a> with a *two* join query.
--   
--   <pre>
--   userPostComments
--       :: SqlQuery (SqlExpr (Entity User, Entity Post, Entity Comment))
--   userPostsComment = do
--       (u :&amp; p :&amp; c) &lt;- from $
--           table <tt>User
--           <a>`InnerJoin`</a>
--           table </tt>Post
--               <a>on</a> do
--                   \(u :&amp; p) -&gt;
--                       u ^. UserId ==. p ^. PostUserId
--           <a>`InnerJoin`</a>
--           table @Comment
--               <a>`on`</a> do
--                   \(_ :&amp; p :&amp; c) -&gt;
--                       p ^. PostId ==. c ^. CommentPostId
--       pure (u, p, c)
--   </pre>
--   
--   This query returns a User, with all of the users Posts, and then all
--   of the Comments on that post.
--   
--   First, we *nest* the tuple.
--   
--   <pre>
--   nest :: (a, b, c) -&gt; (a, (b, c))
--   nest (a, b, c) = (a, (b, c))
--   </pre>
--   
--   This makes the return of the query conform to the input expected from
--   <a>associateJoin</a>.
--   
--   <pre>
--   nestedUserPostComments
--       :: SqlPersistT IO [(Entity User, (Entity Post, Entity Comment))]
--   nestedUserPostComments =
--       fmap nest $ select userPostsComments
--   </pre>
--   
--   Now, we can call <a>associateJoin</a> on it.
--   
--   <pre>
--   associateUsers
--       :: [(Entity User, (Entity Post, Entity Comment))]
--       -&gt; Map UserId (User, [(Entity Post, Entity Comment)])
--   associateUsers =
--       associateJoin
--   </pre>
--   
--   Next, we'll use the <a>Functor</a> instances for <tt>Map</tt> and
--   tuple to call <a>associateJoin</a> on the <tt>[(Entity Post, Entity
--   Comment)]</tt>.
--   
--   <pre>
--   associatePostsAndComments
--       :: Map UserId (User, [(Entity Post, Entity Comment)])
--       -&gt; Map UserId (User, Map PostId (Post, [Entity Comment]))
--   associatePostsAndComments =
--       fmap (fmap associateJoin)
--   </pre>
--   
--   For more reading on this topic, see <a>this Foxhound Systems blog
--   post</a>.
associateJoin :: forall e1 e0. Ord (Key e0) => [(Entity e0, e1)] -> Map (Key e0) (e0, [e1])
type family Nullable a
instance GHC.Internal.Base.Applicative Database.Esqueleto.Internal.Internal.SqlQuery
instance GHC.Internal.Base.Applicative Database.Esqueleto.Internal.Internal.Value
instance Data.Bifunctor.Bifunctor (Database.Esqueleto.Internal.Internal.:&)
instance (GHC.Classes.Eq a, GHC.Classes.Eq b) => GHC.Classes.Eq (a Database.Esqueleto.Internal.Internal.:& b)
instance GHC.Classes.Eq Database.Esqueleto.Internal.Internal.CommonTableExpressionKind
instance GHC.Classes.Eq Database.Esqueleto.Internal.Internal.Ident
instance GHC.Classes.Eq Database.Esqueleto.Internal.Internal.JoinKind
instance GHC.Classes.Eq Database.Esqueleto.Internal.Internal.LimitClause
instance GHC.Classes.Eq Database.Esqueleto.Internal.Internal.NeedParens
instance GHC.Classes.Eq Database.Esqueleto.Internal.Internal.OnClauseWithoutMatchingJoinException
instance GHC.Classes.Eq Database.Esqueleto.Internal.Internal.OnLockedBehavior
instance GHC.Classes.Eq Database.Esqueleto.Internal.Internal.PostgresRowLevelLockStrength
instance GHC.Classes.Eq a => GHC.Classes.Eq (Database.Esqueleto.Internal.Internal.Value a)
instance GHC.Classes.Eq a => GHC.Classes.Eq (Database.Esqueleto.Internal.Internal.ValueList a)
instance GHC.Internal.Exception.Type.Exception Database.Esqueleto.Internal.Internal.EsqueletoError
instance GHC.Internal.Exception.Type.Exception Database.Esqueleto.Internal.Internal.OnClauseWithoutMatchingJoinException
instance GHC.Internal.Exception.Type.Exception Database.Esqueleto.Internal.Internal.RenderExprException
instance Database.Esqueleto.Internal.Internal.FinalResult b => Database.Esqueleto.Internal.Internal.FinalResult (a -> b)
instance Database.Esqueleto.Internal.Internal.FinalResult (Database.Persist.Class.PersistEntity.Unique val)
instance GHC.Internal.Data.Foldable.Foldable Database.Esqueleto.Internal.Internal.Value
instance (Database.Persist.Class.PersistEntity.PersistEntity val, Database.Persist.Class.PersistStore.BackendCompatible Database.Persist.SqlBackend.Internal.SqlBackend (Database.Persist.Class.PersistEntity.PersistEntityBackend val)) => Database.Esqueleto.Internal.Internal.FromPreprocess (Database.Esqueleto.Internal.Internal.SqlExpr (Database.Persist.Class.PersistEntity.Entity val))
instance (Database.Persist.Class.PersistEntity.PersistEntity val, Database.Persist.Class.PersistStore.BackendCompatible Database.Persist.SqlBackend.Internal.SqlBackend (Database.Persist.Class.PersistEntity.PersistEntityBackend val)) => Database.Esqueleto.Internal.Internal.FromPreprocess (Database.Esqueleto.Internal.Internal.SqlExpr (GHC.Internal.Maybe.Maybe (Database.Persist.Class.PersistEntity.Entity val)))
instance (Database.Esqueleto.Internal.Internal.FromPreprocess a, Database.Esqueleto.Internal.Internal.FromPreprocess b, Database.Esqueleto.Internal.Internal.IsJoinKind join) => Database.Esqueleto.Internal.Internal.FromPreprocess (join a b)
instance Database.Esqueleto.Internal.Internal.FromPreprocess (Database.Esqueleto.Internal.Internal.CrossJoin a b) => Database.Esqueleto.Internal.Internal.From (Database.Esqueleto.Internal.Internal.CrossJoin a b)
instance Database.Esqueleto.Internal.Internal.FromPreprocess (Database.Esqueleto.Internal.Internal.FullOuterJoin a b) => Database.Esqueleto.Internal.Internal.From (Database.Esqueleto.Internal.Internal.FullOuterJoin a b)
instance Database.Esqueleto.Internal.Internal.FromPreprocess (Database.Esqueleto.Internal.Internal.InnerJoin a b) => Database.Esqueleto.Internal.Internal.From (Database.Esqueleto.Internal.Internal.InnerJoin a b)
instance Database.Esqueleto.Internal.Internal.FromPreprocess (Database.Esqueleto.Internal.Internal.LeftOuterJoin a b) => Database.Esqueleto.Internal.Internal.From (Database.Esqueleto.Internal.Internal.LeftOuterJoin a b)
instance Database.Esqueleto.Internal.Internal.FromPreprocess (Database.Esqueleto.Internal.Internal.RightOuterJoin a b) => Database.Esqueleto.Internal.Internal.From (Database.Esqueleto.Internal.Internal.RightOuterJoin a b)
instance Database.Esqueleto.Internal.Internal.FromPreprocess (Database.Esqueleto.Internal.Internal.SqlExpr (Database.Persist.Class.PersistEntity.Entity val)) => Database.Esqueleto.Internal.Internal.From (Database.Esqueleto.Internal.Internal.SqlExpr (Database.Persist.Class.PersistEntity.Entity val))
instance Database.Esqueleto.Internal.Internal.FromPreprocess (Database.Esqueleto.Internal.Internal.SqlExpr (GHC.Internal.Maybe.Maybe (Database.Persist.Class.PersistEntity.Entity val))) => Database.Esqueleto.Internal.Internal.From (Database.Esqueleto.Internal.Internal.SqlExpr (GHC.Internal.Maybe.Maybe (Database.Persist.Class.PersistEntity.Entity val)))
instance (Database.Esqueleto.Internal.Internal.From a, Database.Esqueleto.Internal.Internal.From b) => Database.Esqueleto.Internal.Internal.From (a, b)
instance (Database.Esqueleto.Internal.Internal.From a, Database.Esqueleto.Internal.Internal.From b, Database.Esqueleto.Internal.Internal.From c) => Database.Esqueleto.Internal.Internal.From (a, b, c)
instance (Database.Esqueleto.Internal.Internal.From a, Database.Esqueleto.Internal.Internal.From b, Database.Esqueleto.Internal.Internal.From c, Database.Esqueleto.Internal.Internal.From d) => Database.Esqueleto.Internal.Internal.From (a, b, c, d)
instance (Database.Esqueleto.Internal.Internal.From a, Database.Esqueleto.Internal.Internal.From b, Database.Esqueleto.Internal.Internal.From c, Database.Esqueleto.Internal.Internal.From d, Database.Esqueleto.Internal.Internal.From e) => Database.Esqueleto.Internal.Internal.From (a, b, c, d, e)
instance (Database.Esqueleto.Internal.Internal.From a, Database.Esqueleto.Internal.Internal.From b, Database.Esqueleto.Internal.Internal.From c, Database.Esqueleto.Internal.Internal.From d, Database.Esqueleto.Internal.Internal.From e, Database.Esqueleto.Internal.Internal.From f) => Database.Esqueleto.Internal.Internal.From (a, b, c, d, e, f)
instance (Database.Esqueleto.Internal.Internal.From a, Database.Esqueleto.Internal.Internal.From b, Database.Esqueleto.Internal.Internal.From c, Database.Esqueleto.Internal.Internal.From d, Database.Esqueleto.Internal.Internal.From e, Database.Esqueleto.Internal.Internal.From f, Database.Esqueleto.Internal.Internal.From g) => Database.Esqueleto.Internal.Internal.From (a, b, c, d, e, f, g)
instance (Database.Esqueleto.Internal.Internal.From a, Database.Esqueleto.Internal.Internal.From b, Database.Esqueleto.Internal.Internal.From c, Database.Esqueleto.Internal.Internal.From d, Database.Esqueleto.Internal.Internal.From e, Database.Esqueleto.Internal.Internal.From f, Database.Esqueleto.Internal.Internal.From g, Database.Esqueleto.Internal.Internal.From h) => Database.Esqueleto.Internal.Internal.From (a, b, c, d, e, f, g, h)
instance GHC.Internal.Base.Functor ((Database.Esqueleto.Internal.Internal.:&) a)
instance (TypeError ...) => GHC.Internal.Base.Functor Database.Esqueleto.Internal.Internal.SqlExpr
instance GHC.Internal.Base.Functor Database.Esqueleto.Internal.Internal.SqlQuery
instance GHC.Internal.Base.Functor Database.Esqueleto.Internal.Internal.Value
instance (Database.Persist.Class.PersistEntity.PersistEntity rec, Database.Persist.Class.PersistField.PersistField typ, Database.Persist.Class.PersistEntity.SymbolToField sym rec typ) => GHC.Internal.Records.HasField sym (Database.Esqueleto.Internal.Internal.SqlExpr (Database.Persist.Class.PersistEntity.Entity rec)) (Database.Esqueleto.Internal.Internal.SqlExpr (Database.Esqueleto.Internal.Internal.Value typ))
instance (Database.Persist.Class.PersistEntity.PersistEntity rec, Database.Persist.Class.PersistField.PersistField typ, Database.Persist.Class.PersistField.PersistField typ', Database.Persist.Class.PersistEntity.SymbolToField sym rec typ, Database.Esqueleto.Internal.Internal.NullableFieldProjection typ typ', GHC.Internal.Records.HasField sym (Database.Esqueleto.Internal.Internal.SqlExpr (GHC.Internal.Maybe.Maybe (Database.Persist.Class.PersistEntity.Entity rec))) (Database.Esqueleto.Internal.Internal.SqlExpr (Database.Esqueleto.Internal.Internal.Value (GHC.Internal.Maybe.Maybe typ')))) => GHC.Internal.Records.HasField sym (Database.Esqueleto.Internal.Internal.SqlExpr (GHC.Internal.Maybe.Maybe (Database.Persist.Class.PersistEntity.Entity rec))) (Database.Esqueleto.Internal.Internal.SqlExpr (Database.Esqueleto.Internal.Internal.Value (GHC.Internal.Maybe.Maybe typ')))
instance Database.Esqueleto.Internal.Internal.IsJoinKind Database.Esqueleto.Internal.Internal.CrossJoin
instance Database.Esqueleto.Internal.Internal.IsJoinKind Database.Esqueleto.Internal.Internal.FullOuterJoin
instance Database.Esqueleto.Internal.Internal.IsJoinKind Database.Esqueleto.Internal.Internal.InnerJoin
instance Database.Esqueleto.Internal.Internal.IsJoinKind Database.Esqueleto.Internal.Internal.LeftOuterJoin
instance Database.Esqueleto.Internal.Internal.IsJoinKind Database.Esqueleto.Internal.Internal.RightOuterJoin
instance (Database.Esqueleto.Internal.Internal.LockableEntity a, Database.Esqueleto.Internal.Internal.LockableEntity b) => Database.Esqueleto.Internal.Internal.LockableEntity (a Database.Esqueleto.Internal.Internal.:& b)
instance Database.Persist.Class.PersistEntity.PersistEntity val => Database.Esqueleto.Internal.Internal.LockableEntity (Database.Esqueleto.Internal.Internal.SqlExpr (Database.Persist.Class.PersistEntity.Entity val))
instance GHC.Internal.Base.Monad Database.Esqueleto.Internal.Internal.SqlQuery
instance GHC.Internal.Base.Monad Database.Esqueleto.Internal.Internal.Value
instance GHC.Internal.Base.Monoid Database.Esqueleto.Internal.Internal.DistinctClause
instance GHC.Internal.Base.Monoid Database.Esqueleto.Internal.Internal.GroupByClause
instance GHC.Internal.Base.Monoid Database.Esqueleto.Internal.Internal.LimitClause
instance GHC.Internal.Base.Monoid Database.Esqueleto.Internal.Internal.LockingClause
instance GHC.Internal.Base.Monoid Database.Esqueleto.Internal.Internal.SideData
instance GHC.Internal.Base.Monoid Database.Esqueleto.Internal.Internal.WhereClause
instance (typ GHC.Types.~ typ') => Database.Esqueleto.Internal.Internal.NullableFieldProjection (GHC.Internal.Maybe.Maybe typ) typ'
instance (typ GHC.Types.~ typ') => Database.Esqueleto.Internal.Internal.NullableFieldProjection typ typ'
instance GHC.Classes.Ord Database.Esqueleto.Internal.Internal.Ident
instance GHC.Classes.Ord Database.Esqueleto.Internal.Internal.OnClauseWithoutMatchingJoinException
instance GHC.Classes.Ord Database.Esqueleto.Internal.Internal.OnLockedBehavior
instance GHC.Classes.Ord Database.Esqueleto.Internal.Internal.PostgresRowLevelLockStrength
instance GHC.Classes.Ord a => GHC.Classes.Ord (Database.Esqueleto.Internal.Internal.Value a)
instance GHC.Classes.Ord a => GHC.Classes.Ord (Database.Esqueleto.Internal.Internal.ValueList a)
instance GHC.Internal.Base.Semigroup Database.Esqueleto.Internal.Internal.DistinctClause
instance GHC.Internal.Base.Semigroup Database.Esqueleto.Internal.Internal.GroupByClause
instance GHC.Internal.Base.Semigroup Database.Esqueleto.Internal.Internal.LimitClause
instance GHC.Internal.Base.Semigroup Database.Esqueleto.Internal.Internal.LockingClause
instance GHC.Internal.Base.Semigroup Database.Esqueleto.Internal.Internal.SideData
instance GHC.Internal.Base.Semigroup Database.Esqueleto.Internal.Internal.WhereClause
instance (GHC.Internal.Show.Show a, GHC.Internal.Show.Show b) => GHC.Internal.Show.Show (a Database.Esqueleto.Internal.Internal.:& b)
instance GHC.Internal.Show.Show Database.Esqueleto.Internal.Internal.EsqueletoError
instance GHC.Internal.Show.Show Database.Esqueleto.Internal.Internal.FromClause
instance GHC.Internal.Show.Show Database.Esqueleto.Internal.Internal.Ident
instance GHC.Internal.Show.Show Database.Esqueleto.Internal.Internal.JoinKind
instance GHC.Internal.Show.Show Database.Esqueleto.Internal.Internal.OnClauseWithoutMatchingJoinException
instance GHC.Internal.Show.Show Database.Esqueleto.Internal.Internal.OnLockedBehavior
instance GHC.Internal.Show.Show Database.Esqueleto.Internal.Internal.RenderExprException
instance GHC.Internal.Show.Show Database.Esqueleto.Internal.Internal.SqlBinOpCompositeError
instance GHC.Internal.Show.Show Database.Esqueleto.Internal.Internal.SubQueryType
instance GHC.Internal.Show.Show Database.Esqueleto.Internal.Internal.UnexpectedCaseError
instance GHC.Internal.Show.Show Database.Esqueleto.Internal.Internal.UnexpectedValueError
instance GHC.Internal.Show.Show a => GHC.Internal.Show.Show (Database.Esqueleto.Internal.Internal.Value a)
instance GHC.Internal.Show.Show a => GHC.Internal.Show.Show (Database.Esqueleto.Internal.Internal.ValueList a)
instance Database.Persist.Class.PersistEntity.PersistEntity a => Database.Esqueleto.Internal.Internal.SqlSelect (Database.Esqueleto.Internal.Internal.SqlExpr (Database.Persist.Class.PersistEntity.Entity a)) (Database.Persist.Class.PersistEntity.Entity a)
instance Database.Persist.Class.PersistEntity.PersistEntity e => Database.Esqueleto.Internal.Internal.SqlSelect (Database.Esqueleto.Internal.Internal.SqlExpr (Database.Esqueleto.Internal.Internal.Insertion e)) (Database.Esqueleto.Internal.Internal.Insertion e)
instance Database.Persist.Class.PersistEntity.PersistEntity a => Database.Esqueleto.Internal.Internal.SqlSelect (Database.Esqueleto.Internal.Internal.SqlExpr (GHC.Internal.Maybe.Maybe (Database.Persist.Class.PersistEntity.Entity a))) (GHC.Internal.Maybe.Maybe (Database.Persist.Class.PersistEntity.Entity a))
instance Database.Persist.Class.PersistField.PersistField a => Database.Esqueleto.Internal.Internal.SqlSelect (Database.Esqueleto.Internal.Internal.SqlExpr (Database.Esqueleto.Internal.Internal.Value a)) (Database.Esqueleto.Internal.Internal.Value a)
instance (Database.Esqueleto.Internal.Internal.SqlSelect a ra, Database.Esqueleto.Internal.Internal.SqlSelect b rb, Database.Esqueleto.Internal.Internal.SqlSelect c rc, Database.Esqueleto.Internal.Internal.SqlSelect d rd, Database.Esqueleto.Internal.Internal.SqlSelect e re, Database.Esqueleto.Internal.Internal.SqlSelect f rf, Database.Esqueleto.Internal.Internal.SqlSelect g rg, Database.Esqueleto.Internal.Internal.SqlSelect h rh, Database.Esqueleto.Internal.Internal.SqlSelect i ri, Database.Esqueleto.Internal.Internal.SqlSelect j rj) => Database.Esqueleto.Internal.Internal.SqlSelect (a, b, c, d, e, f, g, h, i, j) (ra, rb, rc, rd, re, rf, rg, rh, ri, rj)
instance (Database.Esqueleto.Internal.Internal.SqlSelect a ra, Database.Esqueleto.Internal.Internal.SqlSelect b rb, Database.Esqueleto.Internal.Internal.SqlSelect c rc, Database.Esqueleto.Internal.Internal.SqlSelect d rd, Database.Esqueleto.Internal.Internal.SqlSelect e re, Database.Esqueleto.Internal.Internal.SqlSelect f rf, Database.Esqueleto.Internal.Internal.SqlSelect g rg, Database.Esqueleto.Internal.Internal.SqlSelect h rh, Database.Esqueleto.Internal.Internal.SqlSelect i ri, Database.Esqueleto.Internal.Internal.SqlSelect j rj, Database.Esqueleto.Internal.Internal.SqlSelect k rk) => Database.Esqueleto.Internal.Internal.SqlSelect (a, b, c, d, e, f, g, h, i, j, k) (ra, rb, rc, rd, re, rf, rg, rh, ri, rj, rk)
instance (Database.Esqueleto.Internal.Internal.SqlSelect a ra, Database.Esqueleto.Internal.Internal.SqlSelect b rb, Database.Esqueleto.Internal.Internal.SqlSelect c rc, Database.Esqueleto.Internal.Internal.SqlSelect d rd, Database.Esqueleto.Internal.Internal.SqlSelect e re, Database.Esqueleto.Internal.Internal.SqlSelect f rf, Database.Esqueleto.Internal.Internal.SqlSelect g rg, Database.Esqueleto.Internal.Internal.SqlSelect h rh, Database.Esqueleto.Internal.Internal.SqlSelect i ri, Database.Esqueleto.Internal.Internal.SqlSelect j rj, Database.Esqueleto.Internal.Internal.SqlSelect k rk, Database.Esqueleto.Internal.Internal.SqlSelect l rl) => Database.Esqueleto.Internal.Internal.SqlSelect (a, b, c, d, e, f, g, h, i, j, k, l) (ra, rb, rc, rd, re, rf, rg, rh, ri, rj, rk, rl)
instance (Database.Esqueleto.Internal.Internal.SqlSelect a ra, Database.Esqueleto.Internal.Internal.SqlSelect b rb, Database.Esqueleto.Internal.Internal.SqlSelect c rc, Database.Esqueleto.Internal.Internal.SqlSelect d rd, Database.Esqueleto.Internal.Internal.SqlSelect e re, Database.Esqueleto.Internal.Internal.SqlSelect f rf, Database.Esqueleto.Internal.Internal.SqlSelect g rg, Database.Esqueleto.Internal.Internal.SqlSelect h rh, Database.Esqueleto.Internal.Internal.SqlSelect i ri, Database.Esqueleto.Internal.Internal.SqlSelect j rj, Database.Esqueleto.Internal.Internal.SqlSelect k rk, Database.Esqueleto.Internal.Internal.SqlSelect l rl, Database.Esqueleto.Internal.Internal.SqlSelect m rm) => Database.Esqueleto.Internal.Internal.SqlSelect (a, b, c, d, e, f, g, h, i, j, k, l, m) (ra, rb, rc, rd, re, rf, rg, rh, ri, rj, rk, rl, rm)
instance (Database.Esqueleto.Internal.Internal.SqlSelect a ra, Database.Esqueleto.Internal.Internal.SqlSelect b rb, Database.Esqueleto.Internal.Internal.SqlSelect c rc, Database.Esqueleto.Internal.Internal.SqlSelect d rd, Database.Esqueleto.Internal.Internal.SqlSelect e re, Database.Esqueleto.Internal.Internal.SqlSelect f rf, Database.Esqueleto.Internal.Internal.SqlSelect g rg, Database.Esqueleto.Internal.Internal.SqlSelect h rh, Database.Esqueleto.Internal.Internal.SqlSelect i ri, Database.Esqueleto.Internal.Internal.SqlSelect j rj, Database.Esqueleto.Internal.Internal.SqlSelect k rk, Database.Esqueleto.Internal.Internal.SqlSelect l rl, Database.Esqueleto.Internal.Internal.SqlSelect m rm, Database.Esqueleto.Internal.Internal.SqlSelect n rn) => Database.Esqueleto.Internal.Internal.SqlSelect (a, b, c, d, e, f, g, h, i, j, k, l, m, n) (ra, rb, rc, rd, re, rf, rg, rh, ri, rj, rk, rl, rm, rn)
instance (Database.Esqueleto.Internal.Internal.SqlSelect a ra, Database.Esqueleto.Internal.Internal.SqlSelect b rb, Database.Esqueleto.Internal.Internal.SqlSelect c rc, Database.Esqueleto.Internal.Internal.SqlSelect d rd, Database.Esqueleto.Internal.Internal.SqlSelect e re, Database.Esqueleto.Internal.Internal.SqlSelect f rf, Database.Esqueleto.Internal.Internal.SqlSelect g rg, Database.Esqueleto.Internal.Internal.SqlSelect h rh, Database.Esqueleto.Internal.Internal.SqlSelect i ri, Database.Esqueleto.Internal.Internal.SqlSelect j rj, Database.Esqueleto.Internal.Internal.SqlSelect k rk, Database.Esqueleto.Internal.Internal.SqlSelect l rl, Database.Esqueleto.Internal.Internal.SqlSelect m rm, Database.Esqueleto.Internal.Internal.SqlSelect n rn, Database.Esqueleto.Internal.Internal.SqlSelect o ro) => Database.Esqueleto.Internal.Internal.SqlSelect (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) (ra, rb, rc, rd, re, rf, rg, rh, ri, rj, rk, rl, rm, rn, ro)
instance (Database.Esqueleto.Internal.Internal.SqlSelect a ra, Database.Esqueleto.Internal.Internal.SqlSelect b rb, Database.Esqueleto.Internal.Internal.SqlSelect c rc, Database.Esqueleto.Internal.Internal.SqlSelect d rd, Database.Esqueleto.Internal.Internal.SqlSelect e re, Database.Esqueleto.Internal.Internal.SqlSelect f rf, Database.Esqueleto.Internal.Internal.SqlSelect g rg, Database.Esqueleto.Internal.Internal.SqlSelect h rh, Database.Esqueleto.Internal.Internal.SqlSelect i ri, Database.Esqueleto.Internal.Internal.SqlSelect j rj, Database.Esqueleto.Internal.Internal.SqlSelect k rk, Database.Esqueleto.Internal.Internal.SqlSelect l rl, Database.Esqueleto.Internal.Internal.SqlSelect m rm, Database.Esqueleto.Internal.Internal.SqlSelect n rn, Database.Esqueleto.Internal.Internal.SqlSelect o ro, Database.Esqueleto.Internal.Internal.SqlSelect p rp) => Database.Esqueleto.Internal.Internal.SqlSelect (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) (ra, rb, rc, rd, re, rf, rg, rh, ri, rj, rk, rl, rm, rn, ro, rp)
instance (Database.Esqueleto.Internal.Internal.SqlSelect a ra, Database.Esqueleto.Internal.Internal.SqlSelect b rb) => Database.Esqueleto.Internal.Internal.SqlSelect (a, b) (ra, rb)
instance (Database.Esqueleto.Internal.Internal.SqlSelect a ra, Database.Esqueleto.Internal.Internal.SqlSelect b rb, Database.Esqueleto.Internal.Internal.SqlSelect c rc) => Database.Esqueleto.Internal.Internal.SqlSelect (a, b, c) (ra, rb, rc)
instance (Database.Esqueleto.Internal.Internal.SqlSelect a ra, Database.Esqueleto.Internal.Internal.SqlSelect b rb, Database.Esqueleto.Internal.Internal.SqlSelect c rc, Database.Esqueleto.Internal.Internal.SqlSelect d rd) => Database.Esqueleto.Internal.Internal.SqlSelect (a, b, c, d) (ra, rb, rc, rd)
instance (Database.Esqueleto.Internal.Internal.SqlSelect a ra, Database.Esqueleto.Internal.Internal.SqlSelect b rb, Database.Esqueleto.Internal.Internal.SqlSelect c rc, Database.Esqueleto.Internal.Internal.SqlSelect d rd, Database.Esqueleto.Internal.Internal.SqlSelect e re) => Database.Esqueleto.Internal.Internal.SqlSelect (a, b, c, d, e) (ra, rb, rc, rd, re)
instance (Database.Esqueleto.Internal.Internal.SqlSelect a ra, Database.Esqueleto.Internal.Internal.SqlSelect b rb, Database.Esqueleto.Internal.Internal.SqlSelect c rc, Database.Esqueleto.Internal.Internal.SqlSelect d rd, Database.Esqueleto.Internal.Internal.SqlSelect e re, Database.Esqueleto.Internal.Internal.SqlSelect f rf) => Database.Esqueleto.Internal.Internal.SqlSelect (a, b, c, d, e, f) (ra, rb, rc, rd, re, rf)
instance (Database.Esqueleto.Internal.Internal.SqlSelect a ra, Database.Esqueleto.Internal.Internal.SqlSelect b rb, Database.Esqueleto.Internal.Internal.SqlSelect c rc, Database.Esqueleto.Internal.Internal.SqlSelect d rd, Database.Esqueleto.Internal.Internal.SqlSelect e re, Database.Esqueleto.Internal.Internal.SqlSelect f rf, Database.Esqueleto.Internal.Internal.SqlSelect g rg) => Database.Esqueleto.Internal.Internal.SqlSelect (a, b, c, d, e, f, g) (ra, rb, rc, rd, re, rf, rg)
instance (Database.Esqueleto.Internal.Internal.SqlSelect a ra, Database.Esqueleto.Internal.Internal.SqlSelect b rb, Database.Esqueleto.Internal.Internal.SqlSelect c rc, Database.Esqueleto.Internal.Internal.SqlSelect d rd, Database.Esqueleto.Internal.Internal.SqlSelect e re, Database.Esqueleto.Internal.Internal.SqlSelect f rf, Database.Esqueleto.Internal.Internal.SqlSelect g rg, Database.Esqueleto.Internal.Internal.SqlSelect h rh) => Database.Esqueleto.Internal.Internal.SqlSelect (a, b, c, d, e, f, g, h) (ra, rb, rc, rd, re, rf, rg, rh)
instance (Database.Esqueleto.Internal.Internal.SqlSelect a ra, Database.Esqueleto.Internal.Internal.SqlSelect b rb, Database.Esqueleto.Internal.Internal.SqlSelect c rc, Database.Esqueleto.Internal.Internal.SqlSelect d rd, Database.Esqueleto.Internal.Internal.SqlSelect e re, Database.Esqueleto.Internal.Internal.SqlSelect f rf, Database.Esqueleto.Internal.Internal.SqlSelect g rg, Database.Esqueleto.Internal.Internal.SqlSelect h rh, Database.Esqueleto.Internal.Internal.SqlSelect i ri) => Database.Esqueleto.Internal.Internal.SqlSelect (a, b, c, d, e, f, g, h, i) (ra, rb, rc, rd, re, rf, rg, rh, ri)
instance Database.Esqueleto.Internal.Internal.SqlSelect () ()
instance Database.Esqueleto.Internal.Internal.SqlString Data.ByteString.Internal.Type.ByteString
instance (a GHC.Types.~ GHC.Types.Char) => Database.Esqueleto.Internal.Internal.SqlString [a]
instance Database.Esqueleto.Internal.Internal.SqlString Text.Blaze.Html.Html
instance Database.Esqueleto.Internal.Internal.SqlString a => Database.Esqueleto.Internal.Internal.SqlString (GHC.Internal.Maybe.Maybe a)
instance Database.Esqueleto.Internal.Internal.SqlString Data.Text.Internal.Lazy.Text
instance Database.Esqueleto.Internal.Internal.SqlString Data.Text.Internal.Text
instance Database.Esqueleto.Internal.Internal.ToSomeValues (Database.Esqueleto.Internal.Internal.SqlExpr (Database.Esqueleto.Internal.Internal.Value a))
instance (Database.Esqueleto.Internal.Internal.ToSomeValues a, Database.Esqueleto.Internal.Internal.ToSomeValues b) => Database.Esqueleto.Internal.Internal.ToSomeValues (a, b)
instance (Database.Esqueleto.Internal.Internal.ToSomeValues a, Database.Esqueleto.Internal.Internal.ToSomeValues b, Database.Esqueleto.Internal.Internal.ToSomeValues c) => Database.Esqueleto.Internal.Internal.ToSomeValues (a, b, c)
instance (Database.Esqueleto.Internal.Internal.ToSomeValues a, Database.Esqueleto.Internal.Internal.ToSomeValues b, Database.Esqueleto.Internal.Internal.ToSomeValues c, Database.Esqueleto.Internal.Internal.ToSomeValues d) => Database.Esqueleto.Internal.Internal.ToSomeValues (a, b, c, d)
instance (Database.Esqueleto.Internal.Internal.ToSomeValues a, Database.Esqueleto.Internal.Internal.ToSomeValues b, Database.Esqueleto.Internal.Internal.ToSomeValues c, Database.Esqueleto.Internal.Internal.ToSomeValues d, Database.Esqueleto.Internal.Internal.ToSomeValues e) => Database.Esqueleto.Internal.Internal.ToSomeValues (a, b, c, d, e)
instance (Database.Esqueleto.Internal.Internal.ToSomeValues a, Database.Esqueleto.Internal.Internal.ToSomeValues b, Database.Esqueleto.Internal.Internal.ToSomeValues c, Database.Esqueleto.Internal.Internal.ToSomeValues d, Database.Esqueleto.Internal.Internal.ToSomeValues e, Database.Esqueleto.Internal.Internal.ToSomeValues f) => Database.Esqueleto.Internal.Internal.ToSomeValues (a, b, c, d, e, f)
instance (Database.Esqueleto.Internal.Internal.ToSomeValues a, Database.Esqueleto.Internal.Internal.ToSomeValues b, Database.Esqueleto.Internal.Internal.ToSomeValues c, Database.Esqueleto.Internal.Internal.ToSomeValues d, Database.Esqueleto.Internal.Internal.ToSomeValues e, Database.Esqueleto.Internal.Internal.ToSomeValues f, Database.Esqueleto.Internal.Internal.ToSomeValues g) => Database.Esqueleto.Internal.Internal.ToSomeValues (a, b, c, d, e, f, g)
instance (Database.Esqueleto.Internal.Internal.ToSomeValues a, Database.Esqueleto.Internal.Internal.ToSomeValues b, Database.Esqueleto.Internal.Internal.ToSomeValues c, Database.Esqueleto.Internal.Internal.ToSomeValues d, Database.Esqueleto.Internal.Internal.ToSomeValues e, Database.Esqueleto.Internal.Internal.ToSomeValues f, Database.Esqueleto.Internal.Internal.ToSomeValues g, Database.Esqueleto.Internal.Internal.ToSomeValues h) => Database.Esqueleto.Internal.Internal.ToSomeValues (a, b, c, d, e, f, g, h)
instance GHC.Internal.Data.Traversable.Traversable Database.Esqueleto.Internal.Internal.Value
instance Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument a => Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument [a]
instance (a GHC.Types.~ Database.Esqueleto.Internal.Internal.Value b) => Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument (Database.Esqueleto.Internal.Internal.SqlExpr a)
instance (Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument a, Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument b, Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument c, Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument d, Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument e, Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument f, Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument g, Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument h, Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument i, Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument j) => Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument (a, b, c, d, e, f, g, h, i, j)
instance (Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument a, Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument b) => Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument (a, b)
instance (Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument a, Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument b, Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument c) => Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument (a, b, c)
instance (Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument a, Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument b, Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument c, Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument d) => Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument (a, b, c, d)
instance (Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument a, Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument b, Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument c, Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument d, Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument e) => Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument (a, b, c, d, e)
instance (Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument a, Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument b, Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument c, Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument d, Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument e, Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument f) => Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument (a, b, c, d, e, f)
instance (Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument a, Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument b, Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument c, Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument d, Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument e, Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument f, Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument g) => Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument (a, b, c, d, e, f, g)
instance (Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument a, Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument b, Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument c, Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument d, Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument e, Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument f, Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument g, Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument h) => Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument (a, b, c, d, e, f, g, h)
instance (Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument a, Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument b, Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument c, Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument d, Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument e, Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument f, Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument g, Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument h, Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument i) => Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument (a, b, c, d, e, f, g, h, i)
instance Database.Esqueleto.Internal.Internal.UnsafeSqlFunctionArgument ()

module Database.Esqueleto.Experimental.ToMaybe
class ToMaybe a where {
    type ToMaybeT a;
}
toMaybe :: ToMaybe a => a -> ToMaybeT a
type family ToMaybeT a
type family Nullable a
instance Database.Esqueleto.Experimental.ToMaybe.ToMaybe (Database.Esqueleto.Internal.Internal.SqlExpr (GHC.Internal.Maybe.Maybe a))
instance Database.Esqueleto.Experimental.ToMaybe.ToMaybe (Database.Esqueleto.Internal.Internal.SqlExpr (Database.Persist.Class.PersistEntity.Entity a))
instance Database.Esqueleto.Experimental.ToMaybe.ToMaybe (Database.Esqueleto.Internal.Internal.SqlExpr (Database.Esqueleto.Internal.Internal.Value a))
instance (Database.Esqueleto.Experimental.ToMaybe.ToMaybe a, Database.Esqueleto.Experimental.ToMaybe.ToMaybe b) => Database.Esqueleto.Experimental.ToMaybe.ToMaybe (a, b)
instance (Database.Esqueleto.Experimental.ToMaybe.ToMaybe a, Database.Esqueleto.Experimental.ToMaybe.ToMaybe b, Database.Esqueleto.Experimental.ToMaybe.ToMaybe c) => Database.Esqueleto.Experimental.ToMaybe.ToMaybe (a, b, c)
instance (Database.Esqueleto.Experimental.ToMaybe.ToMaybe a, Database.Esqueleto.Experimental.ToMaybe.ToMaybe b, Database.Esqueleto.Experimental.ToMaybe.ToMaybe c, Database.Esqueleto.Experimental.ToMaybe.ToMaybe d) => Database.Esqueleto.Experimental.ToMaybe.ToMaybe (a, b, c, d)
instance (Database.Esqueleto.Experimental.ToMaybe.ToMaybe a, Database.Esqueleto.Experimental.ToMaybe.ToMaybe b, Database.Esqueleto.Experimental.ToMaybe.ToMaybe c, Database.Esqueleto.Experimental.ToMaybe.ToMaybe d, Database.Esqueleto.Experimental.ToMaybe.ToMaybe e) => Database.Esqueleto.Experimental.ToMaybe.ToMaybe (a, b, c, d, e)
instance (Database.Esqueleto.Experimental.ToMaybe.ToMaybe a, Database.Esqueleto.Experimental.ToMaybe.ToMaybe b, Database.Esqueleto.Experimental.ToMaybe.ToMaybe c, Database.Esqueleto.Experimental.ToMaybe.ToMaybe d, Database.Esqueleto.Experimental.ToMaybe.ToMaybe e, Database.Esqueleto.Experimental.ToMaybe.ToMaybe f) => Database.Esqueleto.Experimental.ToMaybe.ToMaybe (a, b, c, d, e, f)
instance (Database.Esqueleto.Experimental.ToMaybe.ToMaybe a, Database.Esqueleto.Experimental.ToMaybe.ToMaybe b, Database.Esqueleto.Experimental.ToMaybe.ToMaybe c, Database.Esqueleto.Experimental.ToMaybe.ToMaybe d, Database.Esqueleto.Experimental.ToMaybe.ToMaybe e, Database.Esqueleto.Experimental.ToMaybe.ToMaybe f, Database.Esqueleto.Experimental.ToMaybe.ToMaybe g) => Database.Esqueleto.Experimental.ToMaybe.ToMaybe (a, b, c, d, e, f, g)
instance (Database.Esqueleto.Experimental.ToMaybe.ToMaybe a, Database.Esqueleto.Experimental.ToMaybe.ToMaybe b, Database.Esqueleto.Experimental.ToMaybe.ToMaybe c, Database.Esqueleto.Experimental.ToMaybe.ToMaybe d, Database.Esqueleto.Experimental.ToMaybe.ToMaybe e, Database.Esqueleto.Experimental.ToMaybe.ToMaybe f, Database.Esqueleto.Experimental.ToMaybe.ToMaybe g, Database.Esqueleto.Experimental.ToMaybe.ToMaybe h) => Database.Esqueleto.Experimental.ToMaybe.ToMaybe (a, b, c, d, e, f, g, h)

module Database.Esqueleto.Experimental.ToAliasReference
class ToAliasReference a
toAliasReference :: ToAliasReference a => Ident -> a -> SqlQuery a
instance Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference (Database.Esqueleto.Internal.Internal.SqlExpr (Database.Esqueleto.Internal.Internal.Value a))
instance Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference (Database.Esqueleto.Internal.Internal.SqlExpr (Database.Persist.Class.PersistEntity.Entity a))
instance Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference (Database.Esqueleto.Internal.Internal.SqlExpr (GHC.Internal.Maybe.Maybe (Database.Persist.Class.PersistEntity.Entity a)))
instance (Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference a, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference b, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference c, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference d, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference e, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference f, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference g, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference h, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference i, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference j) => Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference (a, b, c, d, e, f, g, h, i, j)
instance (Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference a, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference b, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference c, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference d, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference e, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference f, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference g, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference h, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference i, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference j, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference k) => Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference (a, b, c, d, e, f, g, h, i, j, k)
instance (Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference a, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference b, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference c, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference d, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference e, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference f, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference g, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference h, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference i, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference j, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference k, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference l) => Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference (a, b, c, d, e, f, g, h, i, j, k, l)
instance (Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference a, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference b, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference c, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference d, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference e, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference f, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference g, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference h, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference i, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference j, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference k, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference l, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference m) => Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference (a, b, c, d, e, f, g, h, i, j, k, l, m)
instance (Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference a, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference b, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference c, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference d, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference e, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference f, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference g, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference h, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference i, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference j, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference k, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference l, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference m, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference n) => Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference (a, b, c, d, e, f, g, h, i, j, k, l, m, n)
instance (Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference a, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference b, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference c, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference d, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference e, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference f, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference g, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference h, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference i, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference j, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference k, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference l, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference m, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference n, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference o) => Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o)
instance (Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference a, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference b, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference c, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference d, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference e, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference f, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference g, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference h, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference i, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference j, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference k, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference l, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference m, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference n, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference o, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference p) => Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p)
instance (Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference a, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference b) => Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference (a, b)
instance (Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference a, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference b, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference c) => Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference (a, b, c)
instance (Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference a, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference b, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference c, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference d) => Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference (a, b, c, d)
instance (Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference a, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference b, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference c, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference d, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference e) => Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference (a, b, c, d, e)
instance (Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference a, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference b, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference c, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference d, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference e, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference f) => Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference (a, b, c, d, e, f)
instance (Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference a, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference b, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference c, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference d, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference e, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference f, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference g) => Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference (a, b, c, d, e, f, g)
instance (Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference a, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference b, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference c, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference d, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference e, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference f, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference g, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference h) => Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference (a, b, c, d, e, f, g, h)
instance (Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference a, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference b, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference c, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference d, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference e, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference f, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference g, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference h, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference i) => Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference (a, b, c, d, e, f, g, h, i)

module Database.Esqueleto.Experimental.ToAlias
class ToAlias a
toAlias :: ToAlias a => a -> SqlQuery a
instance Database.Esqueleto.Experimental.ToAlias.ToAlias (Database.Esqueleto.Internal.Internal.SqlExpr (Database.Esqueleto.Internal.Internal.Value a))
instance Database.Esqueleto.Experimental.ToAlias.ToAlias (Database.Esqueleto.Internal.Internal.SqlExpr (Database.Persist.Class.PersistEntity.Entity a))
instance Database.Esqueleto.Experimental.ToAlias.ToAlias (Database.Esqueleto.Internal.Internal.SqlExpr (GHC.Internal.Maybe.Maybe (Database.Persist.Class.PersistEntity.Entity a)))
instance (Database.Esqueleto.Experimental.ToAlias.ToAlias a, Database.Esqueleto.Experimental.ToAlias.ToAlias b, Database.Esqueleto.Experimental.ToAlias.ToAlias c, Database.Esqueleto.Experimental.ToAlias.ToAlias d, Database.Esqueleto.Experimental.ToAlias.ToAlias e, Database.Esqueleto.Experimental.ToAlias.ToAlias f, Database.Esqueleto.Experimental.ToAlias.ToAlias g, Database.Esqueleto.Experimental.ToAlias.ToAlias h, Database.Esqueleto.Experimental.ToAlias.ToAlias i, Database.Esqueleto.Experimental.ToAlias.ToAlias j) => Database.Esqueleto.Experimental.ToAlias.ToAlias (a, b, c, d, e, f, g, h, i, j)
instance (Database.Esqueleto.Experimental.ToAlias.ToAlias a, Database.Esqueleto.Experimental.ToAlias.ToAlias b, Database.Esqueleto.Experimental.ToAlias.ToAlias c, Database.Esqueleto.Experimental.ToAlias.ToAlias d, Database.Esqueleto.Experimental.ToAlias.ToAlias e, Database.Esqueleto.Experimental.ToAlias.ToAlias f, Database.Esqueleto.Experimental.ToAlias.ToAlias g, Database.Esqueleto.Experimental.ToAlias.ToAlias h, Database.Esqueleto.Experimental.ToAlias.ToAlias i, Database.Esqueleto.Experimental.ToAlias.ToAlias j, Database.Esqueleto.Experimental.ToAlias.ToAlias k) => Database.Esqueleto.Experimental.ToAlias.ToAlias (a, b, c, d, e, f, g, h, i, j, k)
instance (Database.Esqueleto.Experimental.ToAlias.ToAlias a, Database.Esqueleto.Experimental.ToAlias.ToAlias b, Database.Esqueleto.Experimental.ToAlias.ToAlias c, Database.Esqueleto.Experimental.ToAlias.ToAlias d, Database.Esqueleto.Experimental.ToAlias.ToAlias e, Database.Esqueleto.Experimental.ToAlias.ToAlias f, Database.Esqueleto.Experimental.ToAlias.ToAlias g, Database.Esqueleto.Experimental.ToAlias.ToAlias h, Database.Esqueleto.Experimental.ToAlias.ToAlias i, Database.Esqueleto.Experimental.ToAlias.ToAlias j, Database.Esqueleto.Experimental.ToAlias.ToAlias k, Database.Esqueleto.Experimental.ToAlias.ToAlias l) => Database.Esqueleto.Experimental.ToAlias.ToAlias (a, b, c, d, e, f, g, h, i, j, k, l)
instance (Database.Esqueleto.Experimental.ToAlias.ToAlias a, Database.Esqueleto.Experimental.ToAlias.ToAlias b, Database.Esqueleto.Experimental.ToAlias.ToAlias c, Database.Esqueleto.Experimental.ToAlias.ToAlias d, Database.Esqueleto.Experimental.ToAlias.ToAlias e, Database.Esqueleto.Experimental.ToAlias.ToAlias f, Database.Esqueleto.Experimental.ToAlias.ToAlias g, Database.Esqueleto.Experimental.ToAlias.ToAlias h, Database.Esqueleto.Experimental.ToAlias.ToAlias i, Database.Esqueleto.Experimental.ToAlias.ToAlias j, Database.Esqueleto.Experimental.ToAlias.ToAlias k, Database.Esqueleto.Experimental.ToAlias.ToAlias l, Database.Esqueleto.Experimental.ToAlias.ToAlias m) => Database.Esqueleto.Experimental.ToAlias.ToAlias (a, b, c, d, e, f, g, h, i, j, k, l, m)
instance (Database.Esqueleto.Experimental.ToAlias.ToAlias a, Database.Esqueleto.Experimental.ToAlias.ToAlias b, Database.Esqueleto.Experimental.ToAlias.ToAlias c, Database.Esqueleto.Experimental.ToAlias.ToAlias d, Database.Esqueleto.Experimental.ToAlias.ToAlias e, Database.Esqueleto.Experimental.ToAlias.ToAlias f, Database.Esqueleto.Experimental.ToAlias.ToAlias g, Database.Esqueleto.Experimental.ToAlias.ToAlias h, Database.Esqueleto.Experimental.ToAlias.ToAlias i, Database.Esqueleto.Experimental.ToAlias.ToAlias j, Database.Esqueleto.Experimental.ToAlias.ToAlias k, Database.Esqueleto.Experimental.ToAlias.ToAlias l, Database.Esqueleto.Experimental.ToAlias.ToAlias m, Database.Esqueleto.Experimental.ToAlias.ToAlias n) => Database.Esqueleto.Experimental.ToAlias.ToAlias (a, b, c, d, e, f, g, h, i, j, k, l, m, n)
instance (Database.Esqueleto.Experimental.ToAlias.ToAlias a, Database.Esqueleto.Experimental.ToAlias.ToAlias b, Database.Esqueleto.Experimental.ToAlias.ToAlias c, Database.Esqueleto.Experimental.ToAlias.ToAlias d, Database.Esqueleto.Experimental.ToAlias.ToAlias e, Database.Esqueleto.Experimental.ToAlias.ToAlias f, Database.Esqueleto.Experimental.ToAlias.ToAlias g, Database.Esqueleto.Experimental.ToAlias.ToAlias h, Database.Esqueleto.Experimental.ToAlias.ToAlias i, Database.Esqueleto.Experimental.ToAlias.ToAlias j, Database.Esqueleto.Experimental.ToAlias.ToAlias k, Database.Esqueleto.Experimental.ToAlias.ToAlias l, Database.Esqueleto.Experimental.ToAlias.ToAlias m, Database.Esqueleto.Experimental.ToAlias.ToAlias n, Database.Esqueleto.Experimental.ToAlias.ToAlias o) => Database.Esqueleto.Experimental.ToAlias.ToAlias (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o)
instance (Database.Esqueleto.Experimental.ToAlias.ToAlias a, Database.Esqueleto.Experimental.ToAlias.ToAlias b, Database.Esqueleto.Experimental.ToAlias.ToAlias c, Database.Esqueleto.Experimental.ToAlias.ToAlias d, Database.Esqueleto.Experimental.ToAlias.ToAlias e, Database.Esqueleto.Experimental.ToAlias.ToAlias f, Database.Esqueleto.Experimental.ToAlias.ToAlias g, Database.Esqueleto.Experimental.ToAlias.ToAlias h, Database.Esqueleto.Experimental.ToAlias.ToAlias i, Database.Esqueleto.Experimental.ToAlias.ToAlias j, Database.Esqueleto.Experimental.ToAlias.ToAlias k, Database.Esqueleto.Experimental.ToAlias.ToAlias l, Database.Esqueleto.Experimental.ToAlias.ToAlias m, Database.Esqueleto.Experimental.ToAlias.ToAlias n, Database.Esqueleto.Experimental.ToAlias.ToAlias o, Database.Esqueleto.Experimental.ToAlias.ToAlias p) => Database.Esqueleto.Experimental.ToAlias.ToAlias (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p)
instance (Database.Esqueleto.Experimental.ToAlias.ToAlias a, Database.Esqueleto.Experimental.ToAlias.ToAlias b) => Database.Esqueleto.Experimental.ToAlias.ToAlias (a, b)
instance (Database.Esqueleto.Experimental.ToAlias.ToAlias a, Database.Esqueleto.Experimental.ToAlias.ToAlias b, Database.Esqueleto.Experimental.ToAlias.ToAlias c) => Database.Esqueleto.Experimental.ToAlias.ToAlias (a, b, c)
instance (Database.Esqueleto.Experimental.ToAlias.ToAlias a, Database.Esqueleto.Experimental.ToAlias.ToAlias b, Database.Esqueleto.Experimental.ToAlias.ToAlias c, Database.Esqueleto.Experimental.ToAlias.ToAlias d) => Database.Esqueleto.Experimental.ToAlias.ToAlias (a, b, c, d)
instance (Database.Esqueleto.Experimental.ToAlias.ToAlias a, Database.Esqueleto.Experimental.ToAlias.ToAlias b, Database.Esqueleto.Experimental.ToAlias.ToAlias c, Database.Esqueleto.Experimental.ToAlias.ToAlias d, Database.Esqueleto.Experimental.ToAlias.ToAlias e) => Database.Esqueleto.Experimental.ToAlias.ToAlias (a, b, c, d, e)
instance (Database.Esqueleto.Experimental.ToAlias.ToAlias a, Database.Esqueleto.Experimental.ToAlias.ToAlias b, Database.Esqueleto.Experimental.ToAlias.ToAlias c, Database.Esqueleto.Experimental.ToAlias.ToAlias d, Database.Esqueleto.Experimental.ToAlias.ToAlias e, Database.Esqueleto.Experimental.ToAlias.ToAlias f) => Database.Esqueleto.Experimental.ToAlias.ToAlias (a, b, c, d, e, f)
instance (Database.Esqueleto.Experimental.ToAlias.ToAlias a, Database.Esqueleto.Experimental.ToAlias.ToAlias b, Database.Esqueleto.Experimental.ToAlias.ToAlias c, Database.Esqueleto.Experimental.ToAlias.ToAlias d, Database.Esqueleto.Experimental.ToAlias.ToAlias e, Database.Esqueleto.Experimental.ToAlias.ToAlias f, Database.Esqueleto.Experimental.ToAlias.ToAlias g) => Database.Esqueleto.Experimental.ToAlias.ToAlias (a, b, c, d, e, f, g)
instance (Database.Esqueleto.Experimental.ToAlias.ToAlias a, Database.Esqueleto.Experimental.ToAlias.ToAlias b, Database.Esqueleto.Experimental.ToAlias.ToAlias c, Database.Esqueleto.Experimental.ToAlias.ToAlias d, Database.Esqueleto.Experimental.ToAlias.ToAlias e, Database.Esqueleto.Experimental.ToAlias.ToAlias f, Database.Esqueleto.Experimental.ToAlias.ToAlias g, Database.Esqueleto.Experimental.ToAlias.ToAlias h) => Database.Esqueleto.Experimental.ToAlias.ToAlias (a, b, c, d, e, f, g, h)
instance (Database.Esqueleto.Experimental.ToAlias.ToAlias a, Database.Esqueleto.Experimental.ToAlias.ToAlias b, Database.Esqueleto.Experimental.ToAlias.ToAlias c, Database.Esqueleto.Experimental.ToAlias.ToAlias d, Database.Esqueleto.Experimental.ToAlias.ToAlias e, Database.Esqueleto.Experimental.ToAlias.ToAlias f, Database.Esqueleto.Experimental.ToAlias.ToAlias g, Database.Esqueleto.Experimental.ToAlias.ToAlias h, Database.Esqueleto.Experimental.ToAlias.ToAlias i) => Database.Esqueleto.Experimental.ToAlias.ToAlias (a, b, c, d, e, f, g, h, i)

module Database.Esqueleto.Experimental.From

-- | <tt>FROM</tt> clause, used to bring entities into scope.
--   
--   Internally, this function uses the <a>From</a> datatype. Unlike the
--   old <a>from</a>, this does not take a function as a parameter, but
--   rather a value that represents a <tt>JOIN</tt> tree constructed out of
--   instances of <a>From</a>. This implementation eliminates certain types
--   of runtime errors by preventing the construction of invalid SQL (e.g.
--   illegal nested-<tt>from</tt>).
from :: ToFrom a a' => a -> SqlQuery a'
type RawFn = NeedParens -> IdentInfo -> (Builder, [PersistValue])

-- | Data type defining the <a>From</a> language. This should not
--   constructed directly in application code.
--   
--   A <tt>From</tt> is a SqlQuery which returns a reference to the result
--   of calling from and a function that produces a portion of a FROM
--   clause. This gets passed to the FromRaw FromClause constructor
--   directly when converting from a <tt>From</tt> to a <tt>SqlQuery</tt>
--   using <tt>from</tt>
newtype From a
From :: SqlQuery (a, RawFn) -> From a
[unFrom] :: From a -> SqlQuery (a, RawFn)

-- | A helper class primarily designed to allow using <tt>SqlQuery</tt>
--   directly in a From expression. This is also useful for embedding a
--   <tt>SqlSetOperation</tt>, as well as supporting backwards
--   compatibility for the data constructor join tree used prior to
--   <i>3.5.0.0</i>
class ToFrom a r | a -> r
toFrom :: ToFrom a r => a -> From r

-- | <i>Deprecated: @since 3.5.0.0 - use <a>table</a> instead</i>
data Table a

-- | <i>Deprecated: @since 3.5.0.0 - use <a>table</a> instead</i>
Table :: Table a

-- | Bring a PersistEntity into scope from a table
--   
--   <pre>
--   select $ from $ table @People
--   </pre>
table :: PersistEntity ent => From (SqlExpr (Entity ent))

-- | Select from a subquery, often used in conjuction with joins but can be
--   used without any joins. Because <tt>SqlQuery</tt> has a
--   <tt>ToFrom</tt> instance you probably dont need to use this function
--   directly.
--   
--   <pre>
--   select $
--        p &lt;- from $
--                selectQuery do
--                p &lt;- from $ table @Person
--                limit 5
--                orderBy [ asc p ^. PersonAge ]
--        ...
--   </pre>
selectQuery :: (SqlSelect a r, ToAlias a, ToAliasReference a) => SqlQuery a -> From a
instance Database.Esqueleto.Experimental.From.ToFrom (Database.Esqueleto.Experimental.From.From a) a
instance (Database.Esqueleto.Internal.Internal.SqlSelect a r, Database.Esqueleto.Experimental.ToAlias.ToAlias a, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference a) => Database.Esqueleto.Experimental.From.ToFrom (Database.Esqueleto.Internal.Internal.SqlQuery a) a
instance Database.Persist.Class.PersistEntity.PersistEntity ent => Database.Esqueleto.Experimental.From.ToFrom (Database.Esqueleto.Experimental.From.Table ent) (Database.Esqueleto.Internal.Internal.SqlExpr (Database.Persist.Class.PersistEntity.Entity ent))

module Database.Esqueleto.Experimental.From.SqlSetOperation

-- | Data type used to implement the SqlSetOperation language this type is
--   implemented in the same way as a <tt>From</tt>
--   
--   Semantically a <tt>SqlSetOperation</tt> is always a <tt>From</tt> but
--   not vice versa
newtype SqlSetOperation a
SqlSetOperation :: (NeedParens -> SqlQuery (a, IdentInfo -> (Builder, [PersistValue]))) -> SqlSetOperation a
[unSqlSetOperation] :: SqlSetOperation a -> NeedParens -> SqlQuery (a, IdentInfo -> (Builder, [PersistValue]))

-- | Type class to support direct use of <tt>SqlQuery</tt> in a set
--   operation tree
class ToSqlSetOperation a r | a -> r
toSqlSetOperation :: ToSqlSetOperation a r => a -> SqlSetOperation r

-- | Helper function for defining set operations @since 3.5.0.0
mkSetOperation :: (ToSqlSetOperation a a', ToSqlSetOperation b a') => Builder -> a -> b -> SqlSetOperation a'

-- | Overloaded <tt>union_</tt> function to support use in both
--   <a>SqlSetOperation</a> and <tt>withRecursive</tt>
class Union_ a

-- | <tt>UNION</tt> SQL set operation. Can be used as an infix function
--   between <a>SqlQuery</a> values.
union_ :: Union_ a => a

-- | Overloaded <tt>unionAll_</tt> function to support use in both
--   <a>SqlSetOperation</a> and <tt>withRecursive</tt>
class UnionAll_ a

-- | <tt>UNION</tt> <tt>ALL</tt> SQL set operation. Can be used as an infix
--   function between <a>SqlQuery</a> values.
unionAll_ :: UnionAll_ a => a

-- | <tt>EXCEPT</tt> SQL set operation. Can be used as an infix function
--   between <a>SqlQuery</a> values.
except_ :: (ToSqlSetOperation a a', ToSqlSetOperation b a') => a -> b -> SqlSetOperation a'

-- | <tt>INTERSECT</tt> SQL set operation. Can be used as an infix function
--   between <a>SqlQuery</a> values.
intersect_ :: (ToSqlSetOperation a a', ToSqlSetOperation b a') => a -> b -> SqlSetOperation a'
instance Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference a => Database.Esqueleto.Experimental.From.ToFrom (Database.Esqueleto.Experimental.From.SqlSetOperation.SqlSetOperation a) a
instance (Database.Esqueleto.Internal.Internal.SqlSelect a r, Database.Esqueleto.Experimental.ToAlias.ToAlias a, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference a) => Database.Esqueleto.Experimental.From.SqlSetOperation.ToSqlSetOperation (Database.Esqueleto.Internal.Internal.SqlQuery a) a
instance Database.Esqueleto.Experimental.From.SqlSetOperation.ToSqlSetOperation (Database.Esqueleto.Experimental.From.SqlSetOperation.SqlSetOperation a) a
instance (Database.Esqueleto.Experimental.From.SqlSetOperation.ToSqlSetOperation a c, Database.Esqueleto.Experimental.From.SqlSetOperation.ToSqlSetOperation b c, res GHC.Types.~ Database.Esqueleto.Experimental.From.SqlSetOperation.SqlSetOperation c) => Database.Esqueleto.Experimental.From.SqlSetOperation.UnionAll_ (a -> b -> res)
instance (Database.Esqueleto.Experimental.From.SqlSetOperation.ToSqlSetOperation a c, Database.Esqueleto.Experimental.From.SqlSetOperation.ToSqlSetOperation b c, res GHC.Types.~ Database.Esqueleto.Experimental.From.SqlSetOperation.SqlSetOperation c) => Database.Esqueleto.Experimental.From.SqlSetOperation.Union_ (a -> b -> res)

module Database.Esqueleto.Experimental.From.Join

-- | A left-precedence pair. Pronounced "and". Used to represent
--   expressions that have been joined together.
--   
--   The precedence behavior can be demonstrated by:
--   
--   <pre>
--   a :&amp; b :&amp; c == ((a :&amp; b) :&amp; c)
--   </pre>
--   
--   See the examples at the beginning of this module to see how this
--   operator is used in <tt>JOIN</tt> operations.
data a :& b
(:&) :: a -> b -> (:&) a b
infixl 2 :&
infixl 2 :&
class ValidOnClause a

-- | An <tt>ON</tt> clause that describes how two tables are related. This
--   should be used as an infix operator after a <tt>JOIN</tt>. For
--   example,
--   
--   <pre>
--   select $
--   from $ table @Person
--   `innerJoin` table @BlogPost
--   `on` (\(p :&amp; bP) -&gt;
--           p ^. PersonId ==. bP ^. BlogPostAuthorId)
--   </pre>
on :: ValidOnClause a => a -> (b -> SqlExpr (Value Bool)) -> (a, b -> SqlExpr (Value Bool))
infix 9 `on`
type family ErrorOnLateral a
fromJoin :: Builder -> RawFn -> RawFn -> Maybe (SqlExpr (Value Bool)) -> RawFn
type family HasOnClause actual expected

-- | INNER JOIN
--   
--   Used as an infix operator `innerJoin`
--   
--   <pre>
--   select $
--   from $ table @Person
--   `innerJoin` table @BlogPost
--   `on` (\(p :&amp; bp) -&gt;
--           p ^. PersonId ==. bp ^. BlogPostAuthorId)
--   </pre>
innerJoin :: (ToFrom a a', ToFrom b b', HasOnClause rhs (a' :& b'), rhs ~ (b, (a' :& b') -> SqlExpr (Value Bool))) => a -> rhs -> From (a' :& b')
infixl 2 `innerJoin`

-- | INNER JOIN LATERAL
--   
--   A Lateral subquery join allows the joined query to reference entities
--   from the left hand side of the join. Discards rows that don't match
--   the on clause
--   
--   Used as an infix operator `innerJoinLateral`
--   
--   See example 6
innerJoinLateral :: (ToFrom a a', HasOnClause rhs (a' :& b), SqlSelect b r, ToAlias b, ToAliasReference b, rhs ~ (a' -> SqlQuery b, (a' :& b) -> SqlExpr (Value Bool))) => a -> rhs -> From (a' :& b)
infixl 2 `innerJoinLateral`

-- | CROSS JOIN
--   
--   Used as an infix `crossJoin`
--   
--   <pre>
--   select $ do
--   from $ table @Person
--   `crossJoin` table @BlogPost
--   </pre>
crossJoin :: (ToFrom a a', ToFrom b b') => a -> b -> From (a' :& b')
infixl 2 `crossJoin`

-- | CROSS JOIN LATERAL
--   
--   A Lateral subquery join allows the joined query to reference entities
--   from the left hand side of the join.
--   
--   Used as an infix operator `crossJoinLateral`
--   
--   See example 6
crossJoinLateral :: (ToFrom a a', SqlSelect b r, ToAlias b, ToAliasReference b) => a -> (a' -> SqlQuery b) -> From (a' :& b)
infixl 2 `crossJoinLateral`

-- | LEFT OUTER JOIN
--   
--   Join where the right side may not exist. If the on clause fails then
--   the right side will be NULL'ed Because of this the right side needs to
--   be handled as a Maybe
--   
--   Used as an infix operator `leftJoin`
--   
--   <pre>
--   select $
--   from $ table @Person
--   `leftJoin` table @BlogPost
--   `on` (\(p :&amp; bp) -&gt;
--           just (p ^. PersonId) ==. bp ?. BlogPostAuthorId)
--   </pre>
leftJoin :: (ToFrom a a', ToFrom b b', ToMaybe b', HasOnClause rhs (a' :& ToMaybeT b'), rhs ~ (b, (a' :& ToMaybeT b') -> SqlExpr (Value Bool))) => a -> rhs -> From (a' :& ToMaybeT b')
infixl 2 `leftJoin`

-- | LEFT OUTER JOIN LATERAL
--   
--   Lateral join where the right side may not exist. In the case that the
--   query returns nothing or the on clause fails the right side of the
--   join will be NULL'ed Because of this the right side needs to be
--   handled as a Maybe
--   
--   Used as an infix operator `leftJoinLateral`
--   
--   See example 6 for how to use LATERAL
leftJoinLateral :: (ToFrom a a', SqlSelect b r, HasOnClause rhs (a' :& ToMaybeT b), ToAlias b, ToAliasReference b, ToMaybe b, rhs ~ (a' -> SqlQuery b, (a' :& ToMaybeT b) -> SqlExpr (Value Bool))) => a -> rhs -> From (a' :& ToMaybeT b)
infixl 2 `leftJoinLateral`

-- | RIGHT OUTER JOIN
--   
--   Join where the left side may not exist. If the on clause fails then
--   the left side will be NULL'ed Because of this the left side needs to
--   be handled as a Maybe
--   
--   Used as an infix operator `rightJoin`
--   
--   <pre>
--   select $
--   from $ table @Person
--   `rightJoin` table @BlogPost
--   `on` (\(p :&amp; bp) -&gt;
--           p ?. PersonId ==. bp ^. BlogPostAuthorId)
--   </pre>
rightJoin :: (ToFrom a a', ToFrom b b', ToMaybe a', HasOnClause rhs (ToMaybeT a' :& b'), rhs ~ (b, (ToMaybeT a' :& b') -> SqlExpr (Value Bool))) => a -> rhs -> From (ToMaybeT a' :& b')
infixl 2 `rightJoin`

-- | FULL OUTER JOIN
--   
--   Join where both sides of the join may not exist. Because of this the
--   result needs to be handled as a Maybe
--   
--   Used as an infix operator `fullOuterJoin`
--   
--   <pre>
--   select $
--   from $ table @Person
--   `fullOuterJoin` table @BlogPost
--   `on` (\(p :&amp; bp) -&gt;
--           p ?. PersonId ==. bp ?. BlogPostAuthorId)
--   </pre>
fullOuterJoin :: (ToFrom a a', ToFrom b b', ToMaybe a', ToMaybe b', HasOnClause rhs (ToMaybeT a' :& ToMaybeT b'), rhs ~ (b, (ToMaybeT a' :& ToMaybeT b') -> SqlExpr (Value Bool))) => a -> rhs -> From (ToMaybeT a' :& ToMaybeT b')
infixl 2 `fullOuterJoin`

-- | Typeclass for selecting tables using type application syntax.
--   
--   If you have a long chain of tables joined with <a>(:&amp;)</a>, like
--   <tt>a :&amp; b :&amp; c :&amp; d</tt>, then <tt>getTable @c (a :&amp;
--   b :&amp; c :&amp; d)</tt> will give you the <tt>c</tt> table back.
--   
--   Note that this typeclass will only select the first table of the given
--   type; it may be less useful if there's multiple tables of the same
--   type.
class GetFirstTable t ts

-- | Get the first table of type <tt>t</tt> from the tables <tt>ts</tt>.
getFirstTable :: GetFirstTable t ts => ts -> t

-- | Get the first table of a given type from a chain of tables joined with
--   <a>(:&amp;)</a>.
--   
--   This can make it easier to write queries with a large number of join
--   clauses:
--   
--   <pre>
--   select $ do
--   (people :&amp; followers :&amp; blogPosts) &lt;-
--       from $ table @Person
--       `innerJoin` table @Follow
--       `on` (\(person :&amp; follow) -&gt;
--               person ^. PersonId ==. follow ^. FollowFollowed)
--       `innerJoin` table @BlogPost
--       `on` (\((getTable @Follow -&gt; follow) :&amp; blogPost) -&gt;
--               blogPost ^. BlogPostAuthorId ==. follow ^. FollowFollower)
--   where_ (people1 ^. PersonName ==. val "John")
--   pure (followers, people2)
--   </pre>
--   
--   This example is a bit trivial, but once you've joined five or six
--   tables it becomes enormously helpful. The above example uses a
--   <tt>ViewPattern</tt> to call the function and assign the variable
--   directly, but you can also imagine it being written like this:
--   
--   <pre>
--   `on` (\(prev :&amp; blogPost) -&gt;
--           let
--               follow = getTable @Follow prev
--            in
--               blogPost ^. BlogPostAuthorId ==. follow ^. FollowFollower)
--   </pre>
--   
--   This function will pluck out the first table that matches the applied
--   type, so if you join on the same table multiple times, it will always
--   select the first one provided.
--   
--   The <a>(:&amp;)</a> operator associates so that the left hand side can
--   be a wildcard for an arbitrary amount of nesting, and the "most
--   recent" or "newest" table in a join sequence is always available on
--   the rightmost - so <tt>(prev :&amp; bar)</tt> is a pattern that
--   matches <tt>bar</tt> table (the most recent table added) and
--   <tt>prev</tt> tables (all prior tables in the join match).
--   
--   By calling <a>getTable</a> on the <tt>prev</tt>, you can select
--   exactly the table you want, allowing you to omit a large number of
--   spurious pattern matches. Consider a query that does several <tt>LEFT
--   JOIN</tt> on a first table:
--   
--   <pre>
--   SELECT *
--   FROM person
--   LEFT JOIN car
--     ON person.id = car.person_id
--   LEFT JOIN bike
--     ON person.id = bike.person_id
--   LEFT JOIN food
--     ON person.id = food.person_id
--   LEFT JOIN address
--     ON person.id = address.person_id
--   </pre>
--   
--   The final <a>on</a> clause in esqueleto would look like this:
--   
--   <pre>
--   `on` do
--       \(person :&amp; _car :&amp; _bike :&amp; _food :&amp; address) -&gt;
--           person.id ==. address.personId
--   </pre>
--   
--   First, we can change it to a <tt>prev :&amp; newest</tt> match. We can
--   do this because of the operator associativity. This is kind of like
--   how a list <tt>:</tt> operator associates, but in the other direction:
--   <tt>a : (b : c) = a : b : c</tt>.
--   
--   <pre>
--   `on` do
--       \(prev :&amp; address) -&gt;
--           let (person :&amp; _car :&amp; _bike :&amp; _food) = prev
--            in person.id ==. address.personId
--   </pre>
--   
--   Then, we can use <a>getTable</a> to select the <tt>Person</tt> table
--   directly, instead of pattern matching manually.
--   
--   <pre>
--   `on` do
--       \(prev :&amp; address) -&gt;
--           let person = getTable @Person prev
--            in person.id ==. address.personId
--   </pre>
--   
--   Finally, we can use a <tt>ViewPattern</tt> language extension to
--   "inline" the access.
--   
--   <pre>
--   `on` do
--       \((getTable @Person -&gt; person) :&amp; address) -&gt;
--          person.id ==. address.personId
--   </pre>
--   
--   With this form, you do not need to be concerned about the number and
--   wildcard status of tables that do not matter to the specific
--   <tt>ON</tt> clause.
getTable :: GetFirstTable (SqlExpr (Entity t)) ts => ts -> SqlExpr (Entity t)

-- | A variant of <a>getTable</a> that operates on possibly-null entities.
getTableMaybe :: GetFirstTable (SqlExpr (Maybe (Entity t))) ts => ts -> SqlExpr (Maybe (Entity t))
data Lateral
data NotLateral
type family IsLateral a
class DoInnerJoin lateral lhs rhs res | lateral rhs lhs -> res
doInnerJoin :: DoInnerJoin lateral lhs rhs res => Proxy lateral -> lhs -> rhs -> From res
class DoLeftJoin lateral lhs rhs res | lateral rhs lhs -> res
doLeftJoin :: DoLeftJoin lateral lhs rhs res => Proxy lateral -> lhs -> rhs -> From res
class DoCrossJoin lateral lhs rhs res | lateral lhs rhs -> res
doCrossJoin :: DoCrossJoin lateral lhs rhs res => Proxy lateral -> lhs -> rhs -> From res
instance (Database.Esqueleto.Experimental.From.ToFrom a a', Database.Esqueleto.Internal.Internal.SqlSelect b r, Database.Esqueleto.Experimental.ToAlias.ToAlias b, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference b) => Database.Esqueleto.Experimental.From.Join.DoCrossJoin Database.Esqueleto.Experimental.From.Join.Lateral a (a' -> Database.Esqueleto.Internal.Internal.SqlQuery b) (a' Database.Esqueleto.Internal.Internal.:& b)
instance (Database.Esqueleto.Experimental.From.ToFrom a a', Database.Esqueleto.Experimental.From.ToFrom b b') => Database.Esqueleto.Experimental.From.Join.DoCrossJoin Database.Esqueleto.Experimental.From.Join.NotLateral a b (a' Database.Esqueleto.Internal.Internal.:& b')
instance (Database.Esqueleto.Experimental.From.ToFrom a a', Database.Esqueleto.Internal.Internal.SqlSelect b r, Database.Esqueleto.Experimental.ToAlias.ToAlias b, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference b, d GHC.Types.~ (a' Database.Esqueleto.Internal.Internal.:& b)) => Database.Esqueleto.Experimental.From.Join.DoInnerJoin Database.Esqueleto.Experimental.From.Join.Lateral a (a' -> Database.Esqueleto.Internal.Internal.SqlQuery b, d -> Database.Esqueleto.Internal.Internal.SqlExpr (Database.Esqueleto.Internal.Internal.Value GHC.Types.Bool)) d
instance (Database.Esqueleto.Experimental.From.ToFrom a a', Database.Esqueleto.Experimental.From.ToFrom b b', Database.Esqueleto.Experimental.From.Join.HasOnClause rhs (a' Database.Esqueleto.Internal.Internal.:& b'), rhs GHC.Types.~ (b, (a' Database.Esqueleto.Internal.Internal.:& b') -> Database.Esqueleto.Internal.Internal.SqlExpr (Database.Esqueleto.Internal.Internal.Value GHC.Types.Bool))) => Database.Esqueleto.Experimental.From.Join.DoInnerJoin Database.Esqueleto.Experimental.From.Join.NotLateral a rhs (a' Database.Esqueleto.Internal.Internal.:& b')
instance (Database.Esqueleto.Experimental.From.ToFrom a a', Database.Esqueleto.Experimental.ToMaybe.ToMaybe b, d GHC.Types.~ (a' Database.Esqueleto.Internal.Internal.:& Database.Esqueleto.Experimental.ToMaybe.ToMaybeT b), Database.Esqueleto.Internal.Internal.SqlSelect b r, Database.Esqueleto.Experimental.ToAlias.ToAlias b, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference b) => Database.Esqueleto.Experimental.From.Join.DoLeftJoin Database.Esqueleto.Experimental.From.Join.Lateral a (a' -> Database.Esqueleto.Internal.Internal.SqlQuery b, d -> Database.Esqueleto.Internal.Internal.SqlExpr (Database.Esqueleto.Internal.Internal.Value GHC.Types.Bool)) d
instance (Database.Esqueleto.Experimental.From.ToFrom a a', Database.Esqueleto.Experimental.From.ToFrom b b', Database.Esqueleto.Experimental.ToMaybe.ToMaybe b', Database.Esqueleto.Experimental.ToMaybe.ToMaybeT b' GHC.Types.~ mb, Database.Esqueleto.Experimental.From.Join.HasOnClause rhs (a' Database.Esqueleto.Internal.Internal.:& mb), rhs GHC.Types.~ (b, (a' Database.Esqueleto.Internal.Internal.:& mb) -> Database.Esqueleto.Internal.Internal.SqlExpr (Database.Esqueleto.Internal.Internal.Value GHC.Types.Bool))) => Database.Esqueleto.Experimental.From.Join.DoLeftJoin Database.Esqueleto.Experimental.From.Join.NotLateral a rhs (a' Database.Esqueleto.Internal.Internal.:& mb)
instance Database.Esqueleto.Experimental.From.Join.GetFirstTable t (t Database.Esqueleto.Internal.Internal.:& ts)
instance Database.Esqueleto.Experimental.From.Join.GetFirstTable t (x Database.Esqueleto.Internal.Internal.:& t)
instance Database.Esqueleto.Experimental.From.Join.GetFirstTable t ts => Database.Esqueleto.Experimental.From.Join.GetFirstTable t (ts Database.Esqueleto.Internal.Internal.:& x)
instance (Database.Esqueleto.Internal.Internal.SqlSelect a ra, Database.Esqueleto.Internal.Internal.SqlSelect b rb) => Database.Esqueleto.Internal.Internal.SqlSelect (a Database.Esqueleto.Internal.Internal.:& b) (ra Database.Esqueleto.Internal.Internal.:& rb)
instance (Database.Esqueleto.Experimental.ToAlias.ToAlias a, Database.Esqueleto.Experimental.ToAlias.ToAlias b) => Database.Esqueleto.Experimental.ToAlias.ToAlias (a Database.Esqueleto.Internal.Internal.:& b)
instance (Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference a, Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference b) => Database.Esqueleto.Experimental.ToAliasReference.ToAliasReference (a Database.Esqueleto.Internal.Internal.:& b)
instance (Database.Esqueleto.Experimental.From.Join.DoCrossJoin lateral lhs rhs r, Database.Esqueleto.Experimental.From.Join.IsLateral rhs GHC.Types.~ lateral) => Database.Esqueleto.Experimental.From.ToFrom (Database.Esqueleto.Internal.Internal.CrossJoin lhs rhs) r
instance (Database.Esqueleto.Experimental.From.ToFrom a a', Database.Esqueleto.Experimental.From.ToFrom b b', Database.Esqueleto.Experimental.ToMaybe.ToMaybe a', Database.Esqueleto.Experimental.ToMaybe.ToMaybeT a' GHC.Types.~ ma, Database.Esqueleto.Experimental.ToMaybe.ToMaybe b', Database.Esqueleto.Experimental.ToMaybe.ToMaybeT b' GHC.Types.~ mb, Database.Esqueleto.Experimental.From.Join.HasOnClause rhs (ma Database.Esqueleto.Internal.Internal.:& mb), Database.Esqueleto.Experimental.From.Join.ErrorOnLateral b, rhs GHC.Types.~ (b, (ma Database.Esqueleto.Internal.Internal.:& mb) -> Database.Esqueleto.Internal.Internal.SqlExpr (Database.Esqueleto.Internal.Internal.Value GHC.Types.Bool))) => Database.Esqueleto.Experimental.From.ToFrom (Database.Esqueleto.Internal.Internal.FullOuterJoin a rhs) (ma Database.Esqueleto.Internal.Internal.:& mb)
instance (Database.Esqueleto.Experimental.From.Join.DoInnerJoin lateral lhs rhs r, lateral GHC.Types.~ Database.Esqueleto.Experimental.From.Join.IsLateral rhs) => Database.Esqueleto.Experimental.From.ToFrom (Database.Esqueleto.Internal.Internal.InnerJoin lhs rhs) r
instance (Database.Esqueleto.Experimental.From.Join.DoLeftJoin lateral lhs rhs r, lateral GHC.Types.~ Database.Esqueleto.Experimental.From.Join.IsLateral rhs) => Database.Esqueleto.Experimental.From.ToFrom (Database.Esqueleto.Internal.Internal.LeftOuterJoin lhs rhs) r
instance (Database.Esqueleto.Experimental.From.ToFrom a a', Database.Esqueleto.Experimental.From.ToFrom b b', Database.Esqueleto.Experimental.ToMaybe.ToMaybe a', Database.Esqueleto.Experimental.ToMaybe.ToMaybeT a' GHC.Types.~ ma, Database.Esqueleto.Experimental.From.Join.HasOnClause rhs (ma Database.Esqueleto.Internal.Internal.:& b'), Database.Esqueleto.Experimental.From.Join.ErrorOnLateral b, rhs GHC.Types.~ (b, (ma Database.Esqueleto.Internal.Internal.:& b') -> Database.Esqueleto.Internal.Internal.SqlExpr (Database.Esqueleto.Internal.Internal.Value GHC.Types.Bool))) => Database.Esqueleto.Experimental.From.ToFrom (Database.Esqueleto.Internal.Internal.RightOuterJoin a rhs) (ma Database.Esqueleto.Internal.Internal.:& b')
instance (Database.Esqueleto.Experimental.ToMaybe.ToMaybe a, Database.Esqueleto.Experimental.ToMaybe.ToMaybe b) => Database.Esqueleto.Experimental.ToMaybe.ToMaybe (a Database.Esqueleto.Internal.Internal.:& b)
instance Database.Esqueleto.Experimental.From.Join.ValidOnClause (a -> Database.Esqueleto.Internal.Internal.SqlQuery b)
instance Database.Esqueleto.Experimental.From.ToFrom a a' => Database.Esqueleto.Experimental.From.Join.ValidOnClause a

module Database.Esqueleto.Experimental.From.CommonTableExpression

-- | <tt>WITH</tt> clause used to introduce a <a>Common Table Expression
--   (CTE)</a>. CTEs are supported in most modern SQL engines and can be
--   useful in performance tuning. In Esqueleto, CTEs should be used as a
--   subquery memoization tactic. When writing plain SQL, CTEs are
--   sometimes used to organize the SQL code, in Esqueleto, this is better
--   achieved through function that return <a>SqlQuery</a> values.
--   
--   <pre>
--   select $ do
--   cte &lt;- with subQuery
--   cteResult &lt;- from cte
--   where_ $ cteResult ...
--   pure cteResult
--   </pre>
--   
--   <b>WARNING</b>: In some SQL engines using a CTE can diminish
--   performance. In these engines the CTE is treated as an optimization
--   fence. You should always verify that using a CTE will in fact improve
--   your performance over a regular subquery.
--   
--   Notably, in PostgreSQL prior to version 12, CTEs are always fully
--   calculated, which can potentially significantly pessimize queries. As
--   of PostgreSQL 12, non-recursive and side-effect-free queries may be
--   inlined and optimized accordingly if not declared
--   <tt>MATERIALIZED</tt> to get the previous behaviour. See <a>the
--   PostgreSQL CTE documentation</a>, section Materialization, for more
--   information. To use a <tt>MATERIALIZED</tt> query in Esquelto, see
--   functions <tt>withMaterialized</tt> and
--   <tt>withRecursiveMaterialized</tt>.
--   
--   <i>Since: 3.4.0.0</i>
with :: (ToAlias a, ToAliasReference a, SqlSelect a r) => SqlQuery a -> SqlQuery (From a)

-- | <tt>WITH</tt> <tt>RECURSIVE</tt> allows one to make a recursive
--   subquery, which can reference itself. Like <tt>WITH</tt>, this is
--   supported in most modern SQL engines. Useful for hierarchical,
--   self-referential data, like a tree of data.
--   
--   <pre>
--   select $ do
--   cte &lt;- withRecursive
--            (do
--                person &lt;- from $ table @Person
--                where_ $ person ^. PersonId ==. val personId
--                pure person
--            )
--            unionAll_
--            (\self -&gt; do
--                (p :&amp; f :&amp; p2 :&amp; pSelf) &lt;- from self
--                         `innerJoin` $ table @Follow
--                         `on` (\(p :&amp; f) -&gt;
--                                 p ^. PersonId ==. f ^. FollowFollower)
--                         `innerJoin` $ table @Person
--                         `on` (\(p :&amp; f :&amp; p2) -&gt;
--                                 f ^. FollowFollowed ==. p2 ^. PersonId)
--                         `leftJoin` self
--                         `on` (\(_ :&amp; _ :&amp; p2 :&amp; pSelf) -&gt;
--                                 just (p2 ^. PersonId) ==. pSelf ?. PersonId)
--                where_ $ isNothing (pSelf ?. PersonId)
--                groupBy (p2 ^. PersonId)
--                pure p2
--            )
--   from cte
--   </pre>
--   
--   <i>Since: 3.4.0.0</i>
withRecursive :: (ToAlias a, ToAliasReference a, SqlSelect a r) => SqlQuery a -> UnionKind -> (From a -> SqlQuery a) -> SqlQuery (From a)
newtype UnionKind
UnionKind :: Builder -> UnionKind
[unUnionKind] :: UnionKind -> Builder
instance Database.Esqueleto.Experimental.From.SqlSetOperation.UnionAll_ Database.Esqueleto.Experimental.From.CommonTableExpression.UnionKind
instance Database.Esqueleto.Experimental.From.SqlSetOperation.Union_ Database.Esqueleto.Experimental.From.CommonTableExpression.UnionKind


-- | This module contains a new way (introduced in 3.3.3.0) of using
--   <tt>FROM</tt> in Haskell. The old method was a bit finicky and could
--   permit runtime errors, and this new way is both significantly safer
--   and much more powerful.
--   
--   This syntax will become the default syntax exported from the library
--   in version <tt>3.6.0.0</tt>. To use the old syntax, see
--   <a>Database.Esqueleto.Legacy</a>.
module Database.Esqueleto.Experimental

-- | <tt>FROM</tt> clause, used to bring entities into scope.
--   
--   Internally, this function uses the <a>From</a> datatype. Unlike the
--   old <a>from</a>, this does not take a function as a parameter, but
--   rather a value that represents a <tt>JOIN</tt> tree constructed out of
--   instances of <a>From</a>. This implementation eliminates certain types
--   of runtime errors by preventing the construction of invalid SQL (e.g.
--   illegal nested-<tt>from</tt>).
from :: ToFrom a a' => a -> SqlQuery a'

-- | Bring a PersistEntity into scope from a table
--   
--   <pre>
--   select $ from $ table @People
--   </pre>
table :: PersistEntity ent => From (SqlExpr (Entity ent))

-- | <i>Deprecated: @since 3.5.0.0 - use <a>table</a> instead</i>
data Table a

-- | <i>Deprecated: @since 3.5.0.0 - use <a>table</a> instead</i>
Table :: Table a

-- | Select from a subquery, often used in conjuction with joins but can be
--   used without any joins. Because <tt>SqlQuery</tt> has a
--   <tt>ToFrom</tt> instance you probably dont need to use this function
--   directly.
--   
--   <pre>
--   select $
--        p &lt;- from $
--                selectQuery do
--                p &lt;- from $ table @Person
--                limit 5
--                orderBy [ asc p ^. PersonAge ]
--        ...
--   </pre>
selectQuery :: (SqlSelect a r, ToAlias a, ToAliasReference a) => SqlQuery a -> From a

-- | A left-precedence pair. Pronounced "and". Used to represent
--   expressions that have been joined together.
--   
--   The precedence behavior can be demonstrated by:
--   
--   <pre>
--   a :&amp; b :&amp; c == ((a :&amp; b) :&amp; c)
--   </pre>
--   
--   See the examples at the beginning of this module to see how this
--   operator is used in <tt>JOIN</tt> operations.
data a :& b
(:&) :: a -> b -> (:&) a b
infixl 2 :&
infixl 2 :&

-- | An <tt>ON</tt> clause that describes how two tables are related. This
--   should be used as an infix operator after a <tt>JOIN</tt>. For
--   example,
--   
--   <pre>
--   select $
--   from $ table @Person
--   `innerJoin` table @BlogPost
--   `on` (\(p :&amp; bP) -&gt;
--           p ^. PersonId ==. bP ^. BlogPostAuthorId)
--   </pre>
on :: ValidOnClause a => a -> (b -> SqlExpr (Value Bool)) -> (a, b -> SqlExpr (Value Bool))
infix 9 `on`

-- | INNER JOIN
--   
--   Used as an infix operator `innerJoin`
--   
--   <pre>
--   select $
--   from $ table @Person
--   `innerJoin` table @BlogPost
--   `on` (\(p :&amp; bp) -&gt;
--           p ^. PersonId ==. bp ^. BlogPostAuthorId)
--   </pre>
innerJoin :: (ToFrom a a', ToFrom b b', HasOnClause rhs (a' :& b'), rhs ~ (b, (a' :& b') -> SqlExpr (Value Bool))) => a -> rhs -> From (a' :& b')
infixl 2 `innerJoin`

-- | INNER JOIN LATERAL
--   
--   A Lateral subquery join allows the joined query to reference entities
--   from the left hand side of the join. Discards rows that don't match
--   the on clause
--   
--   Used as an infix operator `innerJoinLateral`
--   
--   See example 6
innerJoinLateral :: (ToFrom a a', HasOnClause rhs (a' :& b), SqlSelect b r, ToAlias b, ToAliasReference b, rhs ~ (a' -> SqlQuery b, (a' :& b) -> SqlExpr (Value Bool))) => a -> rhs -> From (a' :& b)
infixl 2 `innerJoinLateral`

-- | LEFT OUTER JOIN
--   
--   Join where the right side may not exist. If the on clause fails then
--   the right side will be NULL'ed Because of this the right side needs to
--   be handled as a Maybe
--   
--   Used as an infix operator `leftJoin`
--   
--   <pre>
--   select $
--   from $ table @Person
--   `leftJoin` table @BlogPost
--   `on` (\(p :&amp; bp) -&gt;
--           just (p ^. PersonId) ==. bp ?. BlogPostAuthorId)
--   </pre>
leftJoin :: (ToFrom a a', ToFrom b b', ToMaybe b', HasOnClause rhs (a' :& ToMaybeT b'), rhs ~ (b, (a' :& ToMaybeT b') -> SqlExpr (Value Bool))) => a -> rhs -> From (a' :& ToMaybeT b')
infixl 2 `leftJoin`

-- | LEFT OUTER JOIN LATERAL
--   
--   Lateral join where the right side may not exist. In the case that the
--   query returns nothing or the on clause fails the right side of the
--   join will be NULL'ed Because of this the right side needs to be
--   handled as a Maybe
--   
--   Used as an infix operator `leftJoinLateral`
--   
--   See example 6 for how to use LATERAL
leftJoinLateral :: (ToFrom a a', SqlSelect b r, HasOnClause rhs (a' :& ToMaybeT b), ToAlias b, ToAliasReference b, ToMaybe b, rhs ~ (a' -> SqlQuery b, (a' :& ToMaybeT b) -> SqlExpr (Value Bool))) => a -> rhs -> From (a' :& ToMaybeT b)
infixl 2 `leftJoinLateral`

-- | RIGHT OUTER JOIN
--   
--   Join where the left side may not exist. If the on clause fails then
--   the left side will be NULL'ed Because of this the left side needs to
--   be handled as a Maybe
--   
--   Used as an infix operator `rightJoin`
--   
--   <pre>
--   select $
--   from $ table @Person
--   `rightJoin` table @BlogPost
--   `on` (\(p :&amp; bp) -&gt;
--           p ?. PersonId ==. bp ^. BlogPostAuthorId)
--   </pre>
rightJoin :: (ToFrom a a', ToFrom b b', ToMaybe a', HasOnClause rhs (ToMaybeT a' :& b'), rhs ~ (b, (ToMaybeT a' :& b') -> SqlExpr (Value Bool))) => a -> rhs -> From (ToMaybeT a' :& b')
infixl 2 `rightJoin`

-- | FULL OUTER JOIN
--   
--   Join where both sides of the join may not exist. Because of this the
--   result needs to be handled as a Maybe
--   
--   Used as an infix operator `fullOuterJoin`
--   
--   <pre>
--   select $
--   from $ table @Person
--   `fullOuterJoin` table @BlogPost
--   `on` (\(p :&amp; bp) -&gt;
--           p ?. PersonId ==. bp ?. BlogPostAuthorId)
--   </pre>
fullOuterJoin :: (ToFrom a a', ToFrom b b', ToMaybe a', ToMaybe b', HasOnClause rhs (ToMaybeT a' :& ToMaybeT b'), rhs ~ (b, (ToMaybeT a' :& ToMaybeT b') -> SqlExpr (Value Bool))) => a -> rhs -> From (ToMaybeT a' :& ToMaybeT b')
infixl 2 `fullOuterJoin`

-- | CROSS JOIN
--   
--   Used as an infix `crossJoin`
--   
--   <pre>
--   select $ do
--   from $ table @Person
--   `crossJoin` table @BlogPost
--   </pre>
crossJoin :: (ToFrom a a', ToFrom b b') => a -> b -> From (a' :& b')
infixl 2 `crossJoin`

-- | CROSS JOIN LATERAL
--   
--   A Lateral subquery join allows the joined query to reference entities
--   from the left hand side of the join.
--   
--   Used as an infix operator `crossJoinLateral`
--   
--   See example 6
crossJoinLateral :: (ToFrom a a', SqlSelect b r, ToAlias b, ToAliasReference b) => a -> (a' -> SqlQuery b) -> From (a' :& b)
infixl 2 `crossJoinLateral`

-- | <tt>UNION</tt> SQL set operation. Can be used as an infix function
--   between <a>SqlQuery</a> values.
union_ :: Union_ a => a

-- | <tt>UNION</tt> <tt>ALL</tt> SQL set operation. Can be used as an infix
--   function between <a>SqlQuery</a> values.
unionAll_ :: UnionAll_ a => a

-- | <tt>EXCEPT</tt> SQL set operation. Can be used as an infix function
--   between <a>SqlQuery</a> values.
except_ :: (ToSqlSetOperation a a', ToSqlSetOperation b a') => a -> b -> SqlSetOperation a'

-- | <tt>INTERSECT</tt> SQL set operation. Can be used as an infix function
--   between <a>SqlQuery</a> values.
intersect_ :: (ToSqlSetOperation a a', ToSqlSetOperation b a') => a -> b -> SqlSetOperation a'

-- | <tt>WITH</tt> clause used to introduce a <a>Common Table Expression
--   (CTE)</a>. CTEs are supported in most modern SQL engines and can be
--   useful in performance tuning. In Esqueleto, CTEs should be used as a
--   subquery memoization tactic. When writing plain SQL, CTEs are
--   sometimes used to organize the SQL code, in Esqueleto, this is better
--   achieved through function that return <a>SqlQuery</a> values.
--   
--   <pre>
--   select $ do
--   cte &lt;- with subQuery
--   cteResult &lt;- from cte
--   where_ $ cteResult ...
--   pure cteResult
--   </pre>
--   
--   <b>WARNING</b>: In some SQL engines using a CTE can diminish
--   performance. In these engines the CTE is treated as an optimization
--   fence. You should always verify that using a CTE will in fact improve
--   your performance over a regular subquery.
--   
--   Notably, in PostgreSQL prior to version 12, CTEs are always fully
--   calculated, which can potentially significantly pessimize queries. As
--   of PostgreSQL 12, non-recursive and side-effect-free queries may be
--   inlined and optimized accordingly if not declared
--   <tt>MATERIALIZED</tt> to get the previous behaviour. See <a>the
--   PostgreSQL CTE documentation</a>, section Materialization, for more
--   information. To use a <tt>MATERIALIZED</tt> query in Esquelto, see
--   functions <tt>withMaterialized</tt> and
--   <tt>withRecursiveMaterialized</tt>.
--   
--   <i>Since: 3.4.0.0</i>
with :: (ToAlias a, ToAliasReference a, SqlSelect a r) => SqlQuery a -> SqlQuery (From a)

-- | <tt>WITH</tt> <tt>RECURSIVE</tt> allows one to make a recursive
--   subquery, which can reference itself. Like <tt>WITH</tt>, this is
--   supported in most modern SQL engines. Useful for hierarchical,
--   self-referential data, like a tree of data.
--   
--   <pre>
--   select $ do
--   cte &lt;- withRecursive
--            (do
--                person &lt;- from $ table @Person
--                where_ $ person ^. PersonId ==. val personId
--                pure person
--            )
--            unionAll_
--            (\self -&gt; do
--                (p :&amp; f :&amp; p2 :&amp; pSelf) &lt;- from self
--                         `innerJoin` $ table @Follow
--                         `on` (\(p :&amp; f) -&gt;
--                                 p ^. PersonId ==. f ^. FollowFollower)
--                         `innerJoin` $ table @Person
--                         `on` (\(p :&amp; f :&amp; p2) -&gt;
--                                 f ^. FollowFollowed ==. p2 ^. PersonId)
--                         `leftJoin` self
--                         `on` (\(_ :&amp; _ :&amp; p2 :&amp; pSelf) -&gt;
--                                 just (p2 ^. PersonId) ==. pSelf ?. PersonId)
--                where_ $ isNothing (pSelf ?. PersonId)
--                groupBy (p2 ^. PersonId)
--                pure p2
--            )
--   from cte
--   </pre>
--   
--   <i>Since: 3.4.0.0</i>
withRecursive :: (ToAlias a, ToAliasReference a, SqlSelect a r) => SqlQuery a -> UnionKind -> (From a -> SqlQuery a) -> SqlQuery (From a)

-- | Data type defining the <a>From</a> language. This should not
--   constructed directly in application code.
--   
--   A <tt>From</tt> is a SqlQuery which returns a reference to the result
--   of calling from and a function that produces a portion of a FROM
--   clause. This gets passed to the FromRaw FromClause constructor
--   directly when converting from a <tt>From</tt> to a <tt>SqlQuery</tt>
--   using <tt>from</tt>
newtype From a
From :: SqlQuery (a, RawFn) -> From a
[unFrom] :: From a -> SqlQuery (a, RawFn)
class ToMaybe a where {
    type ToMaybeT a;
}
toMaybe :: ToMaybe a => a -> ToMaybeT a
class ToAlias a
toAlias :: ToAlias a => a -> SqlQuery a
class ToAliasReference a
toAliasReference :: ToAliasReference a => Ident -> a -> SqlQuery a

-- | Type class to support direct use of <tt>SqlQuery</tt> in a set
--   operation tree
class ToSqlSetOperation a r | a -> r
toSqlSetOperation :: ToSqlSetOperation a r => a -> SqlSetOperation r

-- | (Internal) Class for mapping results coming from <a>SqlQuery</a> into
--   actual results.
--   
--   This looks very similar to <tt>RawSql</tt>, and it is! However, there
--   are some crucial differences and ultimately they're different classes.
class SqlSelect a r | a -> r, r -> a
type family Nullable a

-- | <tt>WHERE</tt> clause: restrict the query's result.
where_ :: SqlExpr (Value Bool) -> SqlQuery ()

-- | <tt>GROUP BY</tt> clause. You can enclose multiple columns in a tuple.
--   
--   <pre>
--   select $ <a>from</a> \(foo `<tt>InnerJoin</tt>` bar) -&gt; do
--     <a>on</a> (foo <a>^.</a> FooBarId <a>==.</a> bar <a>^.</a> BarId)
--     <a>groupBy</a> (bar <a>^.</a> BarId, bar <a>^.</a> BarName)
--     return (bar <a>^.</a> BarId, bar <a>^.</a> BarName, countRows)
--   </pre>
--   
--   With groupBy you can sort by aggregate functions, like so (we used
--   <tt>let</tt> to restrict the more general <a>countRows</a> to
--   <tt>SqlSqlExpr (Value Int)</tt> to avoid ambiguity---the second use of
--   <a>countRows</a> has its type restricted by the <tt>:: Int</tt>
--   below):
--   
--   <pre>
--   r &lt;- select $ <a>from</a> \(foo `<tt>InnerJoin</tt>` bar) -&gt; do
--     <a>on</a> (foo <a>^.</a> FooBarId <a>==.</a> bar <a>^.</a> BarId)
--     <a>groupBy</a> $ bar <a>^.</a> BarName
--     let countRows' = <a>countRows</a>
--     <a>orderBy</a> [<a>asc</a> countRows']
--     return (bar <a>^.</a> BarName, countRows')
--   forM_ r $ \(<a>Value</a> name, <a>Value</a> count) -&gt; do
--     print name
--     print (count :: Int)
--   </pre>
--   
--   <h3>Need more columns?</h3>
--   
--   The <a>ToSomeValues</a> class is defined for <a>SqlExpr</a> and tuples
--   of <a>SqlExpr</a>s. We only have definitions for up to 8 elements in a
--   tuple right now, so it's possible that you may need to have more than
--   8 elements.
--   
--   For example, consider a query with a <a>groupBy</a> call like this:
--   
--   <pre>
--   groupBy (e0, e1, e2, e3, e4, e5, e6, e7)
--   </pre>
--   
--   This is the biggest you can get with a single tuple. However, you can
--   easily nest the tuples to add more:
--   
--   <pre>
--   groupBy ((e0, e1, e2, e3, e4, e5, e6, e7), e8, e9)
--   </pre>
groupBy :: ToSomeValues a => a -> SqlQuery ()

-- | An alias for <a>groupBy</a> that avoids conflict with the term from
--   <a>Data.List</a> <a>groupBy</a>.
groupBy_ :: ToSomeValues a => a -> SqlQuery ()

-- | <tt>ORDER BY</tt> clause. See also <a>asc</a> and <a>desc</a>.
--   
--   Multiple calls to <a>orderBy</a> get concatenated on the final query,
--   including <a>distinctOnOrderBy</a>.
orderBy :: [SqlExpr OrderBy] -> SqlQuery ()

-- | Ascending order of this field or SqlExpression.
asc :: PersistField a => SqlExpr (Value a) -> SqlExpr OrderBy

-- | Descending order of this field or SqlExpression.
desc :: PersistField a => SqlExpr (Value a) -> SqlExpr OrderBy

-- | <tt>LIMIT</tt>. Limit the number of returned rows.
limit :: Int64 -> SqlQuery ()

-- | <tt>OFFSET</tt>. Usually used with <a>limit</a>.
offset :: Int64 -> SqlQuery ()

-- | <tt>DISTINCT</tt>. Change the current <tt>SELECT</tt> into <tt>SELECT
--   DISTINCT</tt>. For example:
--   
--   <pre>
--   select $ distinct $
--     <a>from</a> \foo -&gt; do
--     ...
--   </pre>
--   
--   Note that this also has the same effect:
--   
--   <pre>
--   select $
--     <a>from</a> \foo -&gt; do
--     distinct (return ())
--     ...
--   </pre>
distinct :: SqlQuery a -> SqlQuery a

-- | <tt>DISTINCT ON</tt>. Change the current <tt>SELECT</tt> into
--   <tt>SELECT DISTINCT ON (SqlExpressions)</tt>. For example:
--   
--   <pre>
--   select $
--     <a>from</a> \foo -&gt;
--     <a>distinctOn</a> [<a>don</a> (foo ^. FooName), <a>don</a> (foo ^. FooState)] $ do
--     ...
--   </pre>
--   
--   You can also chain different calls to <a>distinctOn</a>. The above is
--   equivalent to:
--   
--   <pre>
--   select $
--     <a>from</a> \foo -&gt;
--     <a>distinctOn</a> [<a>don</a> (foo ^. FooName)] $
--     <a>distinctOn</a> [<a>don</a> (foo ^. FooState)] $ do
--     ...
--   </pre>
--   
--   Each call to <a>distinctOn</a> adds more SqlExpressions. Calls to
--   <a>distinctOn</a> override any calls to <a>distinct</a>.
--   
--   Note that PostgreSQL requires the SqlExpressions on <tt>DISTINCT
--   ON</tt> to be the first ones to appear on a <tt>ORDER BY</tt>. This is
--   not managed automatically by esqueleto, keeping its spirit of trying
--   to be close to raw SQL.
--   
--   Supported by PostgreSQL only.

-- | <i>Deprecated: This function is deprecated, as it is only supported in
--   Postgresql. Please use the variant in <a>PostgreSQL</a> instead.</i>
distinctOn :: [SqlExpr DistinctOn] -> SqlQuery a -> SqlQuery a

-- | Erase an SqlExpression's type so that it's suitable to be used by
--   <a>distinctOn</a>.
don :: SqlExpr (Value a) -> SqlExpr DistinctOn

-- | A convenience function that calls both <a>distinctOn</a> and
--   <a>orderBy</a>. In other words,
--   
--   <pre>
--   <a>distinctOnOrderBy</a> [asc foo, desc bar, desc quux] $ do
--     ...
--   </pre>
--   
--   is the same as:
--   
--   <pre>
--   <a>distinctOn</a> [don foo, don  bar, don  quux] $ do
--     <a>orderBy</a>  [asc foo, desc bar, desc quux]
--     ...
--   </pre>

-- | <i>Deprecated: This function is deprecated, as it is only supported in
--   Postgresql. Please use the function defined in <a>PostgreSQL</a>
--   instead.</i>
distinctOnOrderBy :: [SqlExpr OrderBy] -> SqlQuery a -> SqlQuery a

-- | <tt>HAVING</tt>.
having :: SqlExpr (Value Bool) -> SqlQuery ()

-- | Add a locking clause to the query. Please read <a>LockingKind</a>
--   documentation and your RDBMS manual. Unsafe since not all locking
--   clauses are implemented for every RDBMS
--   
--   If multiple calls to <a>locking</a> are made on the same query, the
--   last one is used.
locking :: LockingKind -> SqlQuery ()

-- | <tt>FOR UPDATE</tt> syntax.
--   
--   Usage:
--   
--   <pre>
--   <a>locking</a> <a>forUpdate</a>
--   </pre>
forUpdate :: LockingKind

-- | <tt>FOR UPDATE SKIP LOCKED</tt> syntax.
--   
--   <pre>
--   <a>locking</a> <a>forUpdateSkipLocked</a>
--   </pre>
forUpdateSkipLocked :: LockingKind

-- | Project a field of an entity.
(^.) :: forall typ val. (PersistEntity val, PersistField typ) => SqlExpr (Entity val) -> EntityField val typ -> SqlExpr (Value typ)
infixl 9 ^.

-- | Project an <a>EntityField</a> of a nullable entity. The result type
--   will be <a>Nullable</a>, meaning that nested <a>Maybe</a> won't be
--   produced here.
--   
--   As of v3.6.0.0, this will attempt to combine nested <a>Maybe</a>. If
--   you want to keep nested <a>Maybe</a>, then see <a>??.</a>.
(?.) :: (PersistEntity val, PersistField typ) => SqlExpr (Maybe (Entity val)) -> EntityField val typ -> SqlExpr (Value (Maybe (Nullable typ)))
infixl 9 ?.

-- | Lift a constant value from Haskell-land to the query.
val :: PersistField typ => typ -> SqlExpr (Value typ)

-- | <tt>IS NULL</tt> comparison.
--   
--   For <tt>IS NOT NULL</tt>, you can negate this with <a>not_</a>, as in
--   <tt>not_ (isNothing (person ^. PersonAge))</tt>
--   
--   Warning: Persistent and Esqueleto have different behavior for <tt>!=
--   Nothing</tt>:
--   
--   TODO: table
--   
--   In SQL, <tt>= NULL</tt> and <tt>!= NULL</tt> return NULL instead of
--   true or false. For this reason, you very likely do not want to use
--   <tt><a>!=.</a> Nothing</tt> in Esqueleto. You may find these
--   <tt>hlint</tt> rules helpful to enforce this:
--   
--   <pre>
--   - error: {lhs: v Database.Esqueleto.==. Database.Esqueleto.nothing, rhs: Database.Esqueleto.isNothing v, name: Use Esqueleto's isNothing}
--   - error: {lhs: v Database.Esqueleto.==. Database.Esqueleto.val Nothing, rhs: Database.Esqueleto.isNothing v, name: Use Esqueleto's isNothing}
--   - error: {lhs: v Database.Esqueleto.!=. Database.Esqueleto.nothing, rhs: not_ (Database.Esqueleto.isNothing v), name: Use Esqueleto's not isNothing}
--   - error: {lhs: v Database.Esqueleto.!=. Database.Esqueleto.val Nothing, rhs: not_ (Database.Esqueleto.isNothing v), name: Use Esqueleto's not isNothing}
--   </pre>
isNothing :: PersistField typ => SqlExpr (Value (Maybe typ)) -> SqlExpr (Value Bool)

-- | An alias for <a>isNothing</a> that avoids clashing with the function
--   from <a>Data.Maybe</a> <a>isNothing</a>.
isNothing_ :: PersistField typ => SqlExpr (Value (Maybe typ)) -> SqlExpr (Value Bool)

-- | Analogous to <a>Just</a>, promotes a value of type <tt>typ</tt> into
--   one of type <tt>Maybe typ</tt>. It should hold that <tt><a>val</a> .
--   Just === just . <a>val</a></tt>.
--   
--   This function will try not to produce a nested <a>Maybe</a>. This is
--   in accord with how SQL represents <tt>NULL</tt>. That means that
--   <tt><a>just</a> . <a>just</a> = <a>just</a></tt>. This behavior was
--   changed in v3.6.0.0. If you want to produce nested <a>Maybe</a>, see
--   <a>just'</a>.
just :: NullableFieldProjection typ typ' => SqlExpr (Value typ) -> SqlExpr (Value (Maybe typ'))

-- | <tt>NULL</tt> value.
nothing :: SqlExpr (Value (Maybe typ))

-- | Join nested <a>Maybe</a>s in a <a>Value</a> into one. This is useful
--   when calling aggregate functions on nullable fields.
--   
--   As of v3.6.0.0, this function will attempt to work on both
--   <tt><a>SqlExpr</a> (<a>Value</a> (<a>Maybe</a> a))</tt> as well as
--   <tt><a>SqlExpr</a> (<a>Value</a> (<a>Maybe</a> (<a>Maybe</a> a)))</tt>
--   inputs to make transitioning to <a>NullableFieldProjection</a> easier.
--   This may make type inference worse in some cases. If you want the
--   monomorphic variant, see <a>joinV'</a>
joinV :: NullableFieldProjection typ typ' => SqlExpr (Value (Maybe typ)) -> SqlExpr (Value (Maybe typ'))

-- | Project an SqlExpression that may be null, guarding against null
--   cases.
withNonNull :: PersistField typ => SqlExpr (Value (Maybe typ)) -> (SqlExpr (Value typ) -> SqlQuery a) -> SqlQuery a

-- | <tt>COUNT(*)</tt> value.
countRows :: Num a => SqlExpr (Value a)

-- | <tt>COUNT</tt>.
count :: Num a => SqlExpr (Value typ) -> SqlExpr (Value a)

-- | <tt>COUNT(DISTINCT x)</tt>.
countDistinct :: Num a => SqlExpr (Value typ) -> SqlExpr (Value a)
not_ :: SqlExpr (Value Bool) -> SqlExpr (Value Bool)

-- | This operator produces the SQL operator <tt>=</tt>, which is used to
--   compare values for equality.
--   
--   Example:
--   
--   <pre>
--   query :: UserId -&gt; SqlPersistT IO [Entity User]
--   query userId = select $ do
--       user &lt;- from $ table @User
--       where_ (user ^. UserId ==. val userId)
--       pure user
--   </pre>
--   
--   This would generate the following SQL:
--   
--   <pre>
--   SELECT user.*
--   FROM user
--   WHERE user.id = ?
--   </pre>
(==.) :: PersistField typ => SqlExpr (Value typ) -> SqlExpr (Value typ) -> SqlExpr (Value Bool)
infix 4 ==.

-- | This operator translates to the SQL operator <tt>&gt;=</tt>.
--   
--   Example:
--   
--   <pre>
--   where_ $ user ^. UserAge &gt;=. val 21
--   </pre>
(>=.) :: PersistField typ => SqlExpr (Value typ) -> SqlExpr (Value typ) -> SqlExpr (Value Bool)
infix 4 >=.

-- | This operator translates to the SQL operator <tt>&gt;</tt>.
--   
--   Example:
--   
--   <pre>
--   where_ $ user ^. UserAge &gt;. val 20
--   </pre>
(>.) :: PersistField typ => SqlExpr (Value typ) -> SqlExpr (Value typ) -> SqlExpr (Value Bool)
infix 4 >.

-- | This operator translates to the SQL operator <tt>&lt;=</tt>.
--   
--   Example:
--   
--   <pre>
--   where_ $ val 21 &lt;=. user ^. UserAge
--   </pre>
(<=.) :: PersistField typ => SqlExpr (Value typ) -> SqlExpr (Value typ) -> SqlExpr (Value Bool)
infix 4 <=.

-- | This operator translates to the SQL operator <tt>&lt;</tt>.
--   
--   Example:
--   
--   <pre>
--   where_ $ val 20 &lt;. user ^. UserAge
--   </pre>
(<.) :: PersistField typ => SqlExpr (Value typ) -> SqlExpr (Value typ) -> SqlExpr (Value Bool)
infix 4 <.

-- | This operator translates to the SQL operator <tt>!=</tt>.
--   
--   Example:
--   
--   <pre>
--   where_ $ user ^. UserName !=. val <a>Bob</a>
--   </pre>
(!=.) :: PersistField typ => SqlExpr (Value typ) -> SqlExpr (Value typ) -> SqlExpr (Value Bool)
infix 4 !=.

-- | This operator translates to the SQL operator <tt>AND</tt>.
--   
--   Example:
--   
--   <pre>
--   where_ $
--           user ^. UserName ==. val <a>Matt</a>
--       &amp;&amp;. user ^. UserAge &gt;=. val 21
--   </pre>
(&&.) :: SqlExpr (Value Bool) -> SqlExpr (Value Bool) -> SqlExpr (Value Bool)
infixr 3 &&.

-- | This operator translates to the SQL operator <tt>AND</tt>.
--   
--   Example:
--   
--   <pre>
--   where_ $
--           user ^. UserName ==. val <a>Matt</a>
--       ||. user ^. UserName ==. val <a>John</a>
--   </pre>
(||.) :: SqlExpr (Value Bool) -> SqlExpr (Value Bool) -> SqlExpr (Value Bool)
infixr 2 ||.

-- | <tt>a <a>between</a> (b, c)</tt> translates to the SQL expression
--   <tt>a &gt;= b AND a &lt;= c</tt>. It does not use a SQL
--   <tt>BETWEEN</tt> operator.
--   
--   @since: 3.1.0
between :: PersistField a => SqlExpr (Value a) -> (SqlExpr (Value a), SqlExpr (Value a)) -> SqlExpr (Value Bool)

-- | This operator translates to the SQL operator <tt>+</tt>.
--   
--   This does not require or assume anything about the SQL values.
--   Interpreting what <tt>+.</tt> means for a given type is left to the
--   database engine.
--   
--   Example:
--   
--   <pre>
--   user ^. UserAge +. val 10
--   </pre>
(+.) :: PersistField a => SqlExpr (Value a) -> SqlExpr (Value a) -> SqlExpr (Value a)
infixl 6 +.

-- | This operator translates to the SQL operator <tt>-</tt>.
--   
--   This does not require or assume anything about the SQL values.
--   Interpreting what <tt>-.</tt> means for a given type is left to the
--   database engine.
--   
--   Example:
--   
--   <pre>
--   user ^. UserAge -. val 10
--   </pre>
(-.) :: PersistField a => SqlExpr (Value a) -> SqlExpr (Value a) -> SqlExpr (Value a)
infixl 6 -.

-- | This operator translates to the SQL operator <tt>/</tt>.
--   
--   This does not require or assume anything about the SQL values.
--   Interpreting what <tt>/.</tt> means for a given type is left to the
--   database engine.
--   
--   Example:
--   
--   <pre>
--   user ^. UserAge /. val 10
--   </pre>
(/.) :: PersistField a => SqlExpr (Value a) -> SqlExpr (Value a) -> SqlExpr (Value a)
infixl 7 /.

-- | This operator translates to the SQL operator <tt>*</tt>.
--   
--   This does not require or assume anything about the SQL values.
--   Interpreting what <tt>*.</tt> means for a given type is left to the
--   database engine.
--   
--   Example:
--   
--   <pre>
--   user ^. UserAge *. val 10
--   </pre>
(*.) :: PersistField a => SqlExpr (Value a) -> SqlExpr (Value a) -> SqlExpr (Value a)
infixl 7 *.
round_ :: (PersistField a, Num a, PersistField b, Num b) => SqlExpr (Value a) -> SqlExpr (Value b)
ceiling_ :: (PersistField a, Num a, PersistField b, Num b) => SqlExpr (Value a) -> SqlExpr (Value b)
floor_ :: (PersistField a, Num a, PersistField b, Num b) => SqlExpr (Value a) -> SqlExpr (Value b)
min_ :: PersistField a => SqlExpr (Value a) -> SqlExpr (Value (Maybe (Nullable a)))
max_ :: PersistField a => SqlExpr (Value a) -> SqlExpr (Value (Maybe (Nullable a)))
sum_ :: (PersistField a, PersistField b) => SqlExpr (Value a) -> SqlExpr (Value (Maybe b))
avg_ :: (PersistField a, PersistField b) => SqlExpr (Value a) -> SqlExpr (Value (Maybe b))

-- | Allow a number of one type to be used as one of another type via an
--   implicit cast. An explicit cast is not made, this function changes
--   only the types on the Haskell side.
--   
--   <i>Caveat</i>: Trying to use <tt>castNum</tt> from <tt>Double</tt> to
--   <tt>Int</tt> will not result in an integer, the original fractional
--   number will still be used! Use <a>round_</a>, <a>ceiling_</a> or
--   <a>floor_</a> instead.
--   
--   <i>Safety</i>: This operation is mostly safe due to the <a>Num</a>
--   constraint between the types and the fact that RDBMSs usually allow
--   numbers of different types to be used interchangeably. However, there
--   may still be issues with the query not being accepted by the RDBMS or
--   <tt>persistent</tt> not being able to parse it.
castNum :: (Num a, Num b) => SqlExpr (Value a) -> SqlExpr (Value b)

-- | Same as <a>castNum</a>, but for nullable values.
castNumM :: (Num a, Num b) => SqlExpr (Value (Maybe a)) -> SqlExpr (Value (Maybe b))

-- | <tt>COALESCE</tt> function. Evaluates the arguments in order and
--   returns the value of the first non-NULL SqlExpression, or NULL
--   (Nothing) otherwise. Some RDBMSs (such as SQLite) require at least two
--   arguments; please refer to the appropriate documentation.
coalesce :: (PersistField a, NullableFieldProjection a a') => [SqlExpr (Value (Maybe a))] -> SqlExpr (Value (Maybe a'))

-- | Like <tt>coalesce</tt>, but takes a non-nullable SqlExpression placed
--   at the end of the SqlExpression list, which guarantees a non-NULL
--   result.
coalesceDefault :: PersistField a => [SqlExpr (Value (Maybe a))] -> SqlExpr (Value a) -> SqlExpr (Value a)

-- | <tt>LOWER</tt> function.
lower_ :: SqlString s => SqlExpr (Value s) -> SqlExpr (Value s)

-- | <tt>UPPER</tt> function. @since 3.3.0
upper_ :: SqlString s => SqlExpr (Value s) -> SqlExpr (Value s)

-- | <tt>TRIM</tt> function. @since 3.3.0
trim_ :: SqlString s => SqlExpr (Value s) -> SqlExpr (Value s)

-- | <tt>LTRIM</tt> function. @since 3.3.0
ltrim_ :: SqlString s => SqlExpr (Value s) -> SqlExpr (Value s)

-- | <tt>RTRIM</tt> function. @since 3.3.0
rtrim_ :: SqlString s => SqlExpr (Value s) -> SqlExpr (Value s)

-- | <tt>LENGTH</tt> function. @since 3.3.0
length_ :: (SqlString s, Num a) => SqlExpr (Value s) -> SqlExpr (Value a)

-- | <tt>LEFT</tt> function. @since 3.3.0
left_ :: (SqlString s, Num a) => (SqlExpr (Value s), SqlExpr (Value a)) -> SqlExpr (Value s)

-- | <tt>RIGHT</tt> function. @since 3.3.0
right_ :: (SqlString s, Num a) => (SqlExpr (Value s), SqlExpr (Value a)) -> SqlExpr (Value s)

-- | <tt>LIKE</tt> operator.
like :: SqlString s => SqlExpr (Value s) -> SqlExpr (Value s) -> SqlExpr (Value Bool)
infixr 2 `like`

-- | <tt>ILIKE</tt> operator (case-insensitive <tt>LIKE</tt>).
--   
--   Supported by PostgreSQL only. Deprecated in version 3.6.0 in favor of
--   the version available from <a>Database.Esqueleto.PostgreSQL</a>.

-- | <i>Deprecated: Since 3.6.0: <a>ilike</a> is only supported on
--   Postgres. Please import it from 'Database.Esqueleto.PostgreSQL.</i>
ilike :: SqlString s => SqlExpr (Value s) -> SqlExpr (Value s) -> SqlExpr (Value Bool)
infixr 2 `ilike`

-- | The string <tt><a>%</a></tt>. May be useful while using <a>like</a>
--   and concatenation (<a>concat_</a> or <a>++.</a>, depending on your
--   database). Note that you always have to type the parenthesis, for
--   example:
--   
--   <pre>
--   name `<a>like</a>` (%) ++. <a>val</a> "John" ++. (%)
--   </pre>
(%) :: SqlString s => SqlExpr (Value s)

-- | The <tt>CONCAT</tt> function with a variable number of parameters.
--   Supported by MySQL and PostgreSQL. SQLite supports this in versions
--   after 3.44.0, and <tt>persistent-sqlite</tt> supports this in versions
--   <tt>2.13.3.0</tt> and after.
concat_ :: SqlString s => [SqlExpr (Value s)] -> SqlExpr (Value s)

-- | The <tt>||</tt> string concatenation operator (named after Haskell's
--   <a>++</a> in order to avoid naming clash with <a>||.</a>).
--   
--   Supported by SQLite and PostgreSQL.
--   
--   MySQL support requires setting the SQL mode to
--   <tt>PIPES_AS_CONCAT</tt> or <tt>ANSI</tt> - see <a>this StackOverflow
--   answer</a>.
(++.) :: SqlString s => SqlExpr (Value s) -> SqlExpr (Value s) -> SqlExpr (Value s)
infixr 5 ++.

-- | Cast a string type into <a>Text</a>. This function is very useful if
--   you want to use <tt>newtype</tt>s, or if you want to apply functions
--   such as <a>like</a> to strings of different types.
--   
--   <i>Safety:</i> This is a slightly unsafe function, especially if you
--   have defined your own instances of <a>SqlString</a>. Also, since
--   <a>Maybe</a> is an instance of <a>SqlString</a>, it's possible to turn
--   a nullable value into a non-nullable one. Avoid using this function if
--   possible.
castString :: (SqlString s, SqlString r) => SqlExpr (Value s) -> SqlExpr (Value r)

-- | Execute a subquery <tt>SELECT</tt> in an SqlExpression. Returns a list
--   of values.
subList_select :: PersistField a => SqlQuery (SqlExpr (Value a)) -> SqlExpr (ValueList a)

-- | Lift a list of constant value from Haskell-land to the query.
valList :: PersistField typ => [typ] -> SqlExpr (ValueList typ)

-- | Same as <a>just</a> but for <a>ValueList</a>. Most of the time you
--   won't need it, though, because you can use <a>just</a> from inside
--   <a>subList_select</a> or <a>Just</a> from inside <a>valList</a>.
justList :: SqlExpr (ValueList typ) -> SqlExpr (ValueList (Maybe typ))

-- | <tt>IN</tt> operator. For example if you want to select all
--   <tt>Person</tt>s by a list of IDs:
--   
--   <pre>
--   SELECT *
--   FROM Person
--   WHERE Person.id IN (?)
--   </pre>
--   
--   In <tt>esqueleto</tt>, we may write the same query above as:
--   
--   <pre>
--   select $
--   <a>from</a> $ \person -&gt; do
--   <a>where_</a> $ person <a>^.</a> PersonId `<tt>in_</tt>` <a>valList</a> personIds
--   return person
--   </pre>
--   
--   Where <tt>personIds</tt> is of type <tt>[Key Person]</tt>.
in_ :: PersistField typ => SqlExpr (Value typ) -> SqlExpr (ValueList typ) -> SqlExpr (Value Bool)

-- | <tt>NOT IN</tt> operator.
notIn :: PersistField typ => SqlExpr (Value typ) -> SqlExpr (ValueList typ) -> SqlExpr (Value Bool)

-- | <tt>EXISTS</tt> operator. For example:
--   
--   <pre>
--   select $
--   <a>from</a> $ \person -&gt; do
--   <a>where_</a> $ <a>exists</a> $
--            <a>from</a> $ \post -&gt; do
--            <a>where_</a> (post <a>^.</a> BlogPostAuthorId <a>==.</a> person <a>^.</a> PersonId)
--   return person
--   </pre>
exists :: SqlQuery () -> SqlExpr (Value Bool)

-- | <tt>NOT EXISTS</tt> operator.
notExists :: SqlQuery () -> SqlExpr (Value Bool)

-- | <tt>SET</tt> clause used on <tt>UPDATE</tt>s. Note that while it's not
--   a type error to use this function on a <tt>SELECT</tt>, it will most
--   certainly result in a runtime error.
set :: PersistEntity val => SqlExpr (Entity val) -> [SqlExpr (Entity val) -> SqlExpr Update] -> SqlQuery ()
(=.) :: (PersistEntity val, PersistField typ) => EntityField val typ -> SqlExpr (Value typ) -> SqlExpr (Entity val) -> SqlExpr Update
infixr 3 =.
(+=.) :: (PersistEntity val, PersistField a) => EntityField val a -> SqlExpr (Value a) -> SqlExpr (Entity val) -> SqlExpr Update
infixr 3 +=.
(-=.) :: (PersistEntity val, PersistField a) => EntityField val a -> SqlExpr (Value a) -> SqlExpr (Entity val) -> SqlExpr Update
infixr 3 -=.
(*=.) :: (PersistEntity val, PersistField a) => EntityField val a -> SqlExpr (Value a) -> SqlExpr (Entity val) -> SqlExpr Update
infixr 3 *=.
(/=.) :: (PersistEntity val, PersistField a) => EntityField val a -> SqlExpr (Value a) -> SqlExpr (Entity val) -> SqlExpr Update
infixr 3 /=.

-- | <tt>CASE</tt> statement. For example:
--   
--   <pre>
--   select $
--   return $
--   <a>case_</a>
--      [ <a>when_</a>
--          (<a>exists</a> $
--          <a>from</a> $ \p -&gt; do
--          <a>where_</a> (p <a>^.</a> PersonName <a>==.</a> <a>val</a> "Mike"))
--        <a>then_</a>
--          (<a>subSelect</a> $
--          <a>from</a> $ \v -&gt; do
--          let sub =
--                  <a>from</a> $ \c -&gt; do
--                  <a>where_</a> (c <a>^.</a> PersonName <a>==.</a> <a>val</a> "Mike")
--                  return (c <a>^.</a> PersonFavNum)
--          <a>where_</a> (<a>just</a> (v <a>^.</a> PersonFavNum) &gt;. <a>subSelect</a> sub)
--          return $ <a>count</a> (v <a>^.</a> PersonName) +. <a>val</a> (1 :: Int)) ]
--      (<a>else_</a> $ <a>val</a> (-1))
--   </pre>
--   
--   This query is a bit complicated, but basically it checks if a person
--   named <tt>"Mike"</tt> exists, and if that person does, run the
--   subquery to find out how many people have a ranking (by Fav Num)
--   higher than <tt>"Mike"</tt>.
--   
--   <b>NOTE:</b> There are a few things to be aware about this statement.
--   
--   <ul>
--   <li>This only implements the full CASE statement, it does not
--   implement the "simple" CASE statement.</li>
--   <li>At least one <a>when_</a> and <a>then_</a> is mandatory otherwise
--   it will emit an error.</li>
--   <li>The <a>else_</a> is also mandatory, unlike the SQL statement in
--   which if the <tt>ELSE</tt> is omitted it will return a <tt>NULL</tt>.
--   You can reproduce this via <a>nothing</a>.</li>
--   </ul>
case_ :: PersistField a => [(SqlExpr (Value Bool), SqlExpr (Value a))] -> SqlExpr (Value a) -> SqlExpr (Value a)

-- | Convert an entity's key into another entity's.
--   
--   This function is to be used when you change an entity's <tt>Id</tt> to
--   be that of another entity. For example:
--   
--   <pre>
--   Bar
--     barNum Int
--   Foo
--     bar BarId
--     fooNum Int
--     Primary bar
--   </pre>
--   
--   In this example, Bar is said to be the BaseEnt(ity), and Foo the
--   child. To model this in Esqueleto, declare:
--   
--   <pre>
--   instance ToBaseId Foo where
--     type BaseEnt Foo = Bar
--     toBaseIdWitness barId = FooKey barId
--   </pre>
--   
--   Now you're able to write queries such as:
--   
--   <pre>
--   <a>select</a> $
--   <a>from</a> $ (bar `<tt>InnerJoin</tt>` foo) -&gt; do
--   <a>on</a> (<a>toBaseId</a> (foo <a>^.</a> FooId) <a>==.</a> bar <a>^.</a> BarId)
--   return (bar, foo)
--   </pre>
--   
--   Note: this function may be unsafe to use in conditions not like the
--   one of the example above.
toBaseId :: ToBaseId ent => SqlExpr (Value (Key ent)) -> SqlExpr (Value (Key (BaseEnt ent)))

-- | Like <a>toBaseId</a>, but works on <a>Maybe</a> keys.
toBaseIdMaybe :: ToBaseId ent => SqlExpr (Value (Maybe (Key ent))) -> SqlExpr (Value (Maybe (Key (BaseEnt ent))))

-- | The inverse of <a>toBaseId</a>. Note that this is somewhat less "safe"
--   than <a>toBaseId</a>. Calling <a>toBaseId</a> will usually mean that a
--   foreign key constraint is present that guarantees the presence of the
--   base ID. <a>fromBaseId</a> has no such guarantee. Consider the code
--   example given in <a>toBaseId</a>:
--   
--   <pre>
--   Bar
--     barNum Int
--   Foo
--     bar BarId
--     fooNum Int
--     Primary bar
--   </pre>
--   
--   <pre>
--   instance ToBaseId Foo where
--     type BaseEnt Foo = Bar
--     toBaseIdWitness barId = FooKey barId
--   </pre>
--   
--   The type of <a>toBaseId</a> for <tt>Foo</tt> would be:
--   
--   <pre>
--   toBaseId :: SqlExpr (Value FooId) -&gt; SqlExpr (Value BarId)
--   </pre>
--   
--   The foreign key constraint on <tt>Foo</tt> means that every
--   <tt>FooId</tt> points to a <tt>BarId</tt> in the database. However,
--   <a>fromBaseId</a> will not have this:
--   
--   <pre>
--   fromBaseId :: SqlExpr (Value BarId) -&gt; SqlExpr (Value FooId)
--   </pre>
fromBaseId :: ToBaseId ent => SqlExpr (Value (Key (BaseEnt ent))) -> SqlExpr (Value (Key ent))

-- | As <a>fromBaseId</a>, but works on <a>Maybe</a> keys.
fromBaseIdMaybe :: ToBaseId ent => SqlExpr (Value (Maybe (Key (BaseEnt ent)))) -> SqlExpr (Value (Maybe (Key ent)))

-- | Execute a subquery <tt>SELECT</tt> in a <a>SqlExpr</a>. The query
--   passed to this function will only return a single result - it has a
--   <tt>LIMIT 1</tt> passed in to the query to make it safe, and the
--   return type is <a>Maybe</a> to indicate that the subquery might result
--   in 0 rows.
--   
--   If you find yourself writing <tt><a>joinV</a> . <a>subSelect</a></tt>,
--   then consider using <a>subSelectMaybe</a>.
--   
--   If you're performing a <a>countRows</a>, then you can use
--   <a>subSelectCount</a> which is safe.
--   
--   If you know that the subquery will always return exactly one row (eg a
--   foreign key constraint guarantees that you'll get exactly one row),
--   then consider <a>subSelectUnsafe</a>, along with a comment explaining
--   why it is safe.
subSelect :: (PersistField a, NullableFieldProjection a a') => SqlQuery (SqlExpr (Value a)) -> SqlExpr (Value (Maybe a'))

-- | Execute a subquery <tt>SELECT</tt> in a <a>SqlExpr</a>. This function
--   is a shorthand for the common <tt><a>joinV</a> . <a>subSelect</a></tt>
--   idiom, where you are calling <a>subSelect</a> on an expression that
--   would be <a>Maybe</a> already.
--   
--   As an example, you would use this function when calling <a>sum_</a> or
--   <a>max_</a>, which have <a>Maybe</a> in the result type (for a 0 row
--   query).
subSelectMaybe :: PersistField a => SqlQuery (SqlExpr (Value (Maybe a))) -> SqlExpr (Value (Maybe a))

-- | Performs a <tt>COUNT</tt> of the given query in a <tt>subSelect</tt>
--   manner. This is always guaranteed to return a result value, and is
--   completely safe.
subSelectCount :: (Num a, PersistField a) => SqlQuery ignored -> SqlExpr (Value a)

-- | Performs a sub-select using the given foreign key on the entity. This
--   is useful to extract values that are known to be present by the
--   database schema.
--   
--   As an example, consider the following persistent definition:
--   
--   <pre>
--   User
--     profile ProfileId
--   
--   Profile
--     name    Text
--   </pre>
--   
--   The following query will return the name of the user.
--   
--   <pre>
--   getUserWithName =
--       <a>select</a> $
--       <a>from</a> $ user -&gt;
--       <a>pure</a> (user, <a>subSelectForeign</a> user UserProfile (^. ProfileName)
--   </pre>
subSelectForeign :: (BackendCompatible SqlBackend (PersistEntityBackend val1), PersistEntity val1, PersistEntity val2, PersistField a) => SqlExpr (Entity val2) -> EntityField val2 (Key val1) -> (SqlExpr (Entity val1) -> SqlExpr (Value a)) -> SqlExpr (Value a)

-- | Execute a subquery <tt>SELECT</tt> in a <a>SqlExpr</a> that returns a
--   list. This is an alias for <a>subList_select</a> and is provided for
--   symmetry with the other safe subselect functions.
subSelectList :: PersistField a => SqlQuery (SqlExpr (Value a)) -> SqlExpr (ValueList a)

-- | Execute a subquery <tt>SELECT</tt> in a <a>SqlExpr</a>. This function
--   is unsafe, because it can throw runtime exceptions in two cases:
--   
--   <ol>
--   <li>If the query passed has 0 result rows, then it will return a
--   <tt>NULL</tt> value. The <tt>persistent</tt> parsing operations will
--   fail on an unexpected <tt>NULL</tt>.</li>
--   <li>If the query passed returns more than one row, then the SQL engine
--   will fail with an error like "More than one row returned by a subquery
--   used as an expression".</li>
--   </ol>
--   
--   This function is safe if you guarantee that exactly one row will be
--   returned, or if the result already has a <a>Maybe</a> type for some
--   reason.
--   
--   For variants with the safety encoded already, see <a>subSelect</a> and
--   <a>subSelectMaybe</a>. For the most common safe use of this, see
--   <a>subSelectCount</a>.
subSelectUnsafe :: PersistField a => SqlQuery (SqlExpr (Value a)) -> SqlExpr (Value a)

-- | Class that enables one to use <a>toBaseId</a> to convert an entity's
--   key on a query into another (cf. <a>toBaseId</a>).
class ToBaseId ent where {
    
    -- | e.g. <tt>type BaseEnt MyBase = MyChild</tt>
    type BaseEnt ent;
}

-- | Convert from the key of the BaseEnt(ity) to the key of the child
--   entity. This function is not actually called, but that it typechecks
--   proves this operation is safe.
toBaseIdWitness :: ToBaseId ent => Key (BaseEnt ent) -> Key ent

-- | Syntax sugar for <a>case_</a>.
when_ :: expr (Value Bool) -> () -> expr a -> (expr (Value Bool), expr a)

-- | Syntax sugar for <a>case_</a>.
then_ :: ()

-- | Syntax sugar for <a>case_</a>.
else_ :: expr a -> expr a

-- | A single value (as opposed to a whole entity). You may use
--   <tt>(<a>^.</a>)</tt> or <tt>(<a>?.</a>)</tt> to get a <a>Value</a>
--   from an <a>Entity</a>.
newtype Value a
Value :: a -> Value a
[unValue] :: Value a -> a

-- | A list of single values. There's a limited set of functions able to
--   work with this data type (such as <a>subList_select</a>,
--   <a>valList</a>, <a>in_</a> and <a>exists</a>).
newtype ValueList a
ValueList :: a -> ValueList a

-- | Phantom type used by <a>orderBy</a>, <a>asc</a> and <a>desc</a>.
data OrderBy

-- | Phantom type used by <a>distinctOn</a> and <a>don</a>.
data DistinctOn

-- | Different kinds of locking clauses supported by <a>locking</a>.
--   
--   Note that each RDBMS has different locking support. The constructors
--   of this datatype specify only the <i>syntax</i> of the locking
--   mechanism, not its <i>semantics</i>. For example, even though both
--   MySQL and PostgreSQL support <a>ForUpdate</a>, there are no guarantees
--   that they will behave the same.
data LockingKind

-- | <tt>FOR UPDATE</tt> syntax. Supported by MySQL, Oracle and PostgreSQL.

-- | <i>Deprecated: The constructors for <a>LockingKind</a> are deprecated
--   in v3.6.0.0. Instead, please refer to the smart constructors
--   <a>forUpdate</a> and <a>forUpdateSkipLocked</a>.</i>
ForUpdate :: LockingKind

-- | <tt>FOR UPDATE SKIP LOCKED</tt> syntax. Supported by MySQL, Oracle and
--   PostgreSQL.

-- | <i>Deprecated: The constructors for <a>LockingKind</a> are deprecated
--   in v3.6.0.0. Instead, please refer to the smart constructors
--   <a>forUpdate</a> and <a>forUpdateSkipLocked</a>.</i>
ForUpdateSkipLocked :: LockingKind

-- | <tt>FOR SHARE</tt> syntax. Supported by PostgreSQL.

-- | <i>Deprecated: The constructors for <a>LockingKind</a> are deprecated
--   in v3.6.0.0. Instead, please refer to the smart constructor
--   <tt>forShare</tt> exported from Database.Esqueleto.PostgreSQL.</i>
ForShare :: LockingKind

-- | <tt>LOCK IN SHARE MODE</tt> syntax. Supported by MySQL.

-- | <i>Deprecated: The constructors for <a>LockingKind</a> are deprecated
--   in v3.6.0.0. Instead, please refer to the smart constructors
--   <tt>lockInShareMode</tt> exported from Database.Esqueleto.MySQL.</i>
LockInShareMode :: LockingKind

-- | Lockable entity
--   
--   Example use:
--   
--   <pre>
--   select $ do
--       (p :&amp; bp) &lt;- from $
--           table <tt>Person
--           <tt>innerJoin</tt> table </tt>BlogPost
--               <a>on</a> do
--                   (p :&amp; bp) -&gt; p ^. PersonId ==. b ^. BlogPostAuthorId
--       forUpdateOf (p :&amp; b) skipLocked
--       return p
--   </pre>
class LockableEntity a
flattenLockableEntity :: LockableEntity a => a -> NonEmpty LockableSqlExpr

-- | Phantom class of data types that are treated as strings by the RDBMS.
--   It has no methods because it's only used to avoid type errors such as
--   trying to concatenate integers.
--   
--   If you have a custom data type or <tt>newtype</tt>, feel free to make
--   it an instance of this class.
class PersistField a => SqlString a

-- | Data type that represents an <tt>INNER JOIN</tt> (see
--   <a>LeftOuterJoin</a> for an example).
data InnerJoin a b
InnerJoin :: a -> b -> InnerJoin a b
infixl 2 `InnerJoin`
infixl 2 `InnerJoin`

-- | Data type that represents a <tt>CROSS JOIN</tt> (see
--   <a>LeftOuterJoin</a> for an example).
data CrossJoin a b
CrossJoin :: a -> b -> CrossJoin a b
infixl 2 `CrossJoin`
infixl 2 `CrossJoin`

-- | Data type that represents a <tt>LEFT OUTER JOIN</tt>. For example,
--   
--   <pre>
--   select $
--   <a>from</a> $ \(person `<tt>LeftOuterJoin</tt>` pet) -&gt;
--     ...
--   </pre>
--   
--   is translated into
--   
--   <pre>
--   SELECT ...
--   FROM Person LEFT OUTER JOIN Pet
--   ...
--   </pre>
--   
--   See also: <a>from</a>.
data LeftOuterJoin a b
LeftOuterJoin :: a -> b -> LeftOuterJoin a b
infixl 2 `LeftOuterJoin`
infixl 2 `LeftOuterJoin`

-- | Data type that represents a <tt>RIGHT OUTER JOIN</tt> (see
--   <a>LeftOuterJoin</a> for an example).
data RightOuterJoin a b
RightOuterJoin :: a -> b -> RightOuterJoin a b
infixl 2 `RightOuterJoin`
infixl 2 `RightOuterJoin`

-- | Data type that represents a <tt>FULL OUTER JOIN</tt> (see
--   <a>LeftOuterJoin</a> for an example).
data FullOuterJoin a b
FullOuterJoin :: a -> b -> FullOuterJoin a b
infixl 2 `FullOuterJoin`
infixl 2 `FullOuterJoin`

-- | (Internal) A kind of <tt>JOIN</tt>.
data JoinKind

-- | <pre>
--   INNER JOIN
--   </pre>
InnerJoinKind :: JoinKind

-- | <pre>
--   CROSS JOIN
--   </pre>
CrossJoinKind :: JoinKind

-- | <pre>
--   LEFT OUTER JOIN
--   </pre>
LeftOuterJoinKind :: JoinKind

-- | <pre>
--   RIGHT OUTER JOIN
--   </pre>
RightOuterJoinKind :: JoinKind

-- | <pre>
--   FULL OUTER JOIN
--   </pre>
FullOuterJoinKind :: JoinKind

-- | Exception thrown whenever <a>on</a> is used to create an <tt>ON</tt>
--   clause but no matching <tt>JOIN</tt> is found.
data OnClauseWithoutMatchingJoinException
OnClauseWithoutMatchingJoinException :: String -> OnClauseWithoutMatchingJoinException

-- | Get the first table of a given type from a chain of tables joined with
--   <a>(:&amp;)</a>.
--   
--   This can make it easier to write queries with a large number of join
--   clauses:
--   
--   <pre>
--   select $ do
--   (people :&amp; followers :&amp; blogPosts) &lt;-
--       from $ table @Person
--       `innerJoin` table @Follow
--       `on` (\(person :&amp; follow) -&gt;
--               person ^. PersonId ==. follow ^. FollowFollowed)
--       `innerJoin` table @BlogPost
--       `on` (\((getTable @Follow -&gt; follow) :&amp; blogPost) -&gt;
--               blogPost ^. BlogPostAuthorId ==. follow ^. FollowFollower)
--   where_ (people1 ^. PersonName ==. val "John")
--   pure (followers, people2)
--   </pre>
--   
--   This example is a bit trivial, but once you've joined five or six
--   tables it becomes enormously helpful. The above example uses a
--   <tt>ViewPattern</tt> to call the function and assign the variable
--   directly, but you can also imagine it being written like this:
--   
--   <pre>
--   `on` (\(prev :&amp; blogPost) -&gt;
--           let
--               follow = getTable @Follow prev
--            in
--               blogPost ^. BlogPostAuthorId ==. follow ^. FollowFollower)
--   </pre>
--   
--   This function will pluck out the first table that matches the applied
--   type, so if you join on the same table multiple times, it will always
--   select the first one provided.
--   
--   The <a>(:&amp;)</a> operator associates so that the left hand side can
--   be a wildcard for an arbitrary amount of nesting, and the "most
--   recent" or "newest" table in a join sequence is always available on
--   the rightmost - so <tt>(prev :&amp; bar)</tt> is a pattern that
--   matches <tt>bar</tt> table (the most recent table added) and
--   <tt>prev</tt> tables (all prior tables in the join match).
--   
--   By calling <a>getTable</a> on the <tt>prev</tt>, you can select
--   exactly the table you want, allowing you to omit a large number of
--   spurious pattern matches. Consider a query that does several <tt>LEFT
--   JOIN</tt> on a first table:
--   
--   <pre>
--   SELECT *
--   FROM person
--   LEFT JOIN car
--     ON person.id = car.person_id
--   LEFT JOIN bike
--     ON person.id = bike.person_id
--   LEFT JOIN food
--     ON person.id = food.person_id
--   LEFT JOIN address
--     ON person.id = address.person_id
--   </pre>
--   
--   The final <a>on</a> clause in esqueleto would look like this:
--   
--   <pre>
--   `on` do
--       \(person :&amp; _car :&amp; _bike :&amp; _food :&amp; address) -&gt;
--           person.id ==. address.personId
--   </pre>
--   
--   First, we can change it to a <tt>prev :&amp; newest</tt> match. We can
--   do this because of the operator associativity. This is kind of like
--   how a list <tt>:</tt> operator associates, but in the other direction:
--   <tt>a : (b : c) = a : b : c</tt>.
--   
--   <pre>
--   `on` do
--       \(prev :&amp; address) -&gt;
--           let (person :&amp; _car :&amp; _bike :&amp; _food) = prev
--            in person.id ==. address.personId
--   </pre>
--   
--   Then, we can use <a>getTable</a> to select the <tt>Person</tt> table
--   directly, instead of pattern matching manually.
--   
--   <pre>
--   `on` do
--       \(prev :&amp; address) -&gt;
--           let person = getTable @Person prev
--            in person.id ==. address.personId
--   </pre>
--   
--   Finally, we can use a <tt>ViewPattern</tt> language extension to
--   "inline" the access.
--   
--   <pre>
--   `on` do
--       \((getTable @Person -&gt; person) :&amp; address) -&gt;
--          person.id ==. address.personId
--   </pre>
--   
--   With this form, you do not need to be concerned about the number and
--   wildcard status of tables that do not matter to the specific
--   <tt>ON</tt> clause.
getTable :: GetFirstTable (SqlExpr (Entity t)) ts => ts -> SqlExpr (Entity t)

-- | A variant of <a>getTable</a> that operates on possibly-null entities.
getTableMaybe :: GetFirstTable (SqlExpr (Maybe (Entity t))) ts => ts -> SqlExpr (Maybe (Entity t))

-- | Typeclass for selecting tables using type application syntax.
--   
--   If you have a long chain of tables joined with <a>(:&amp;)</a>, like
--   <tt>a :&amp; b :&amp; c :&amp; d</tt>, then <tt>getTable @c (a :&amp;
--   b :&amp; c :&amp; d)</tt> will give you the <tt>c</tt> table back.
--   
--   Note that this typeclass will only select the first table of the given
--   type; it may be less useful if there's multiple tables of the same
--   type.
class GetFirstTable t ts

-- | Get the first table of type <tt>t</tt> from the tables <tt>ts</tt>.
getFirstTable :: GetFirstTable t ts => ts -> t

-- | SQL backend for <tt>esqueleto</tt> using <a>SqlPersistT</a>.
data SqlQuery a

-- | An expression on the SQL backend.
--   
--   Raw expression: Contains a <a>SqlExprMeta</a> and a function for
--   building the expr. It recieves a parameter telling it whether it is in
--   a parenthesized context, and takes information about the SQL
--   connection (mainly for escaping names) and returns both an string
--   (<a>Builder</a>) and a list of values to be interpolated by the SQL
--   backend.
data SqlExpr a

-- | Constraint synonym for <tt>persistent</tt> entities whose backend is
--   <a>SqlBackend</a>.
type SqlEntity ent = (PersistEntity ent, PersistEntityBackend ent ~ SqlBackend)

-- | Execute an <tt>esqueleto</tt> <tt>SELECT</tt> query inside
--   <tt>persistent</tt>'s <a>SqlPersistT</a> monad and return a list of
--   rows.
--   
--   We've seen that <a>from</a> has some magic about which kinds of things
--   you may bring into scope. This <a>select</a> function also has some
--   magic for which kinds of things you may bring back to Haskell-land by
--   using <tt>SqlQuery</tt>'s <tt>return</tt>:
--   
--   <ul>
--   <li>You may return a <tt>SqlExpr (<a>Entity</a> v)</tt> for an entity
--   <tt>v</tt> (i.e., like the <tt>*</tt> in SQL), which is then returned
--   to Haskell-land as just <tt>Entity v</tt>.</li>
--   <li>You may return a <tt>SqlExpr (Maybe (Entity v))</tt> for an entity
--   <tt>v</tt> that may be <tt>NULL</tt>, which is then returned to
--   Haskell-land as <tt>Maybe (Entity v)</tt>. Used for <tt>OUTER
--   JOIN</tt>s.</li>
--   <li>You may return a <tt>SqlExpr (<a>Value</a> t)</tt> for a value
--   <tt>t</tt> (i.e., a single column), where <tt>t</tt> is any instance
--   of <a>PersistField</a>, which is then returned to Haskell-land as
--   <tt>Value t</tt>. You may use <tt>Value</tt> to return projections of
--   an <tt>Entity</tt> (see <tt>(<a>^.</a>)</tt> and <tt>(<a>?.</a>)</tt>)
--   or to return any other value calculated on the query (e.g.,
--   <a>countRows</a> or <a>subSelect</a>).</li>
--   </ul>
--   
--   The <tt>SqlSelect a r</tt> class has functional dependencies that
--   allow type information to flow both from <tt>a</tt> to <tt>r</tt> and
--   vice-versa. This means that you'll almost never have to give any type
--   signatures for <tt>esqueleto</tt> queries. For example, the query
--   <tt><a>select</a> $ from $ \p -&gt; return p</tt> alone is ambiguous,
--   but in the context of
--   
--   <pre>
--   do ps &lt;- <a>select</a> $
--            <a>from</a> $ \p -&gt;
--            return p
--      liftIO $ mapM_ (putStrLn . personName . entityVal) ps
--   </pre>
--   
--   we are able to infer from that single <tt>personName . entityVal</tt>
--   function composition that the <tt>p</tt> inside the query is of type
--   <tt>SqlExpr (Entity Person)</tt>.
select :: forall a r (m :: Type -> Type) backend. (SqlSelect a r, MonadIO m, SqlBackendCanRead backend) => SqlQuery a -> ReaderT backend m [r]

-- | Execute an <tt>esqueleto</tt> <tt>SELECT</tt> query inside
--   <tt>persistent</tt>'s <a>SqlPersistT</a> monad and return the first
--   entry wrapped in a <tt>Maybe</tt>. @since 3.5.1.0
--   
--   <h3><b>Example usage</b></h3>
--   
--   <pre>
--   firstPerson :: MonadIO m =&gt; SqlPersistT m (Maybe (Entity Person))
--   firstPerson =
--    <a>selectOne</a> $ do
--        person &lt;- <a>from</a> $ <tt>table</tt> @Person
--        return person
--   </pre>
--   
--   The above query is equivalent to a <a>select</a> combined with
--   <a>limit</a> but you would still have to transform the results from a
--   list:
--   
--   <pre>
--   firstPerson :: MonadIO m =&gt; SqlPersistT m [Entity Person]
--   firstPerson =
--    <a>select</a> $ do
--        person &lt;- <a>from</a> $ <tt>table</tt> @Person
--        <a>limit</a> 1
--        return person
--   </pre>
selectOne :: forall a r (m :: Type -> Type) backend. (SqlSelect a r, MonadIO m, SqlBackendCanRead backend) => SqlQuery a -> ReaderT backend m (Maybe r)

-- | Execute an <tt>esqueleto</tt> <tt>SELECT</tt> query inside
--   <tt>persistent</tt>'s <a>SqlPersistT</a> monad and return a
--   <a>Source</a> of rows.
selectSource :: forall a r backend (m :: Type -> Type). (SqlSelect a r, BackendCompatible SqlBackend backend, IsPersistBackend backend, PersistQueryRead backend, PersistStoreRead backend, PersistUniqueRead backend, MonadResource m) => SqlQuery a -> ConduitT () r (ReaderT backend m) ()

-- | Execute an <tt>esqueleto</tt> <tt>DELETE</tt> query inside
--   <tt>persistent</tt>'s <a>SqlPersistT</a> monad. Note that currently
--   there are no type checks for statements that should not appear on a
--   <tt>DELETE</tt> query.
--   
--   Example of usage:
--   
--   <pre>
--   <a>delete</a> $
--   <a>from</a> $ \appointment -&gt;
--   <a>where_</a> (appointment <a>^.</a> AppointmentDate <a>&lt;.</a> <a>val</a> now)
--   </pre>
--   
--   Unlike <a>select</a>, there is a useful way of using <a>delete</a>
--   that will lead to type ambiguities. If you want to delete all rows
--   (i.e., no <a>where_</a> clause), you'll have to use a type signature:
--   
--   <pre>
--   <a>delete</a> $
--   <a>from</a> $ \(appointment :: <a>SqlExpr</a> (<a>Entity</a> Appointment)) -&gt;
--   return ()
--   </pre>
--   
--   <h4><a>Database.Esqueleto.Experimental</a>:</h4>
--   
--   <pre>
--   delete $ do
--     userFeature &lt;- from $ table @UserFeature
--     where_ ((userFeature ^. UserFeatureFeature) <a>notIn</a> valList allKnownFeatureFlags)
--   </pre>
delete :: forall (m :: Type -> Type) backend. (MonadIO m, SqlBackendCanWrite backend) => SqlQuery () -> ReaderT backend m ()

-- | Same as <a>delete</a>, but returns the number of rows affected.
deleteCount :: forall (m :: Type -> Type) backend. (MonadIO m, SqlBackendCanWrite backend) => SqlQuery () -> ReaderT backend m Int64

-- | Execute an <tt>esqueleto</tt> <tt>UPDATE</tt> query inside
--   <tt>persistent</tt>'s <a>SqlPersistT</a> monad. Note that currently
--   there are no type checks for statements that should not appear on a
--   <tt>UPDATE</tt> query.
--   
--   Example of usage:
--   
--   <pre>
--   <a>update</a> $ \p -&gt; do
--   <a>set</a> p [ PersonAge <a>=.</a> <a>just</a> (<a>val</a> thisYear) -. p <a>^.</a> PersonBorn ]
--   <a>where_</a> $ isNothing (p <a>^.</a> PersonAge)
--   </pre>
update :: forall (m :: Type -> Type) val backend. (MonadIO m, PersistEntity val, BackendCompatible SqlBackend (PersistEntityBackend val), SqlBackendCanWrite backend) => (SqlExpr (Entity val) -> SqlQuery ()) -> ReaderT backend m ()

-- | Same as <a>update</a>, but returns the number of rows affected.
updateCount :: forall (m :: Type -> Type) val backend. (MonadIO m, PersistEntity val, BackendCompatible SqlBackend (PersistEntityBackend val), SqlBackendCanWrite backend) => (SqlExpr (Entity val) -> SqlQuery ()) -> ReaderT backend m Int64

-- | Insert a <a>PersistField</a> for every selected value.
insertSelect :: forall (m :: Type -> Type) a backend. (MonadIO m, PersistEntity a, SqlBackendCanWrite backend) => SqlQuery (SqlExpr (Insertion a)) -> ReaderT backend m ()

-- | Insert a <a>PersistField</a> for every selected value, return the
--   count afterward
insertSelectCount :: forall (m :: Type -> Type) a backend. (MonadIO m, PersistEntity a, SqlBackendCanWrite backend) => SqlQuery (SqlExpr (Insertion a)) -> ReaderT backend m Int64

-- | Apply a <a>PersistField</a> constructor to <tt>SqlExpr Value</tt>
--   arguments.
(<#) :: (a -> b) -> SqlExpr (Value a) -> SqlExpr (Insertion b)

-- | Apply extra <tt>SqlExpr Value</tt> arguments to a <a>PersistField</a>
--   constructor
(<&>) :: SqlExpr (Insertion (a -> b)) -> SqlExpr (Value a) -> SqlExpr (Insertion b)

-- | Renders a <a>SqlQuery</a> into a <a>Text</a> value along with the list
--   of <a>PersistValue</a>s that would be supplied to the database for
--   <tt>?</tt> placeholders.
--   
--   You must ensure that the <a>Mode</a> you pass to this function
--   corresponds with the actual <a>SqlQuery</a>. If you pass a query that
--   uses incompatible features (like an <tt>INSERT</tt> statement with a
--   <tt>SELECT</tt> mode) then you'll get a weird result.
renderQueryToText :: forall a r backend (m :: Type -> Type). (SqlSelect a r, BackendCompatible SqlBackend backend, Monad m) => Mode -> SqlQuery a -> ReaderT backend m (Text, [PersistValue])

-- | Renders a <a>SqlQuery</a> into a <a>Text</a> value along with the list
--   of <a>PersistValue</a>s that would be supplied to the database for
--   <tt>?</tt> placeholders.
renderQuerySelect :: forall a r backend (m :: Type -> Type). (SqlSelect a r, BackendCompatible SqlBackend backend, Monad m) => SqlQuery a -> ReaderT backend m (Text, [PersistValue])

-- | Renders a <a>SqlQuery</a> into a <a>Text</a> value along with the list
--   of <a>PersistValue</a>s that would be supplied to the database for
--   <tt>?</tt> placeholders.
renderQueryUpdate :: forall a r backend (m :: Type -> Type). (SqlSelect a r, BackendCompatible SqlBackend backend, Monad m) => SqlQuery a -> ReaderT backend m (Text, [PersistValue])

-- | Renders a <a>SqlQuery</a> into a <a>Text</a> value along with the list
--   of <a>PersistValue</a>s that would be supplied to the database for
--   <tt>?</tt> placeholders.
renderQueryDelete :: forall a r backend (m :: Type -> Type). (SqlSelect a r, BackendCompatible SqlBackend backend, Monad m) => SqlQuery a -> ReaderT backend m (Text, [PersistValue])

-- | Renders a <a>SqlQuery</a> into a <a>Text</a> value along with the list
--   of <a>PersistValue</a>s that would be supplied to the database for
--   <tt>?</tt> placeholders.
renderQueryInsertInto :: forall a r backend (m :: Type -> Type). (SqlSelect a r, BackendCompatible SqlBackend backend, Monad m) => SqlQuery a -> ReaderT backend m (Text, [PersistValue])

-- | <tt>valkey i = <a>val</a> . <a>toSqlKey</a></tt>
--   (<a>https://github.com/prowdsponsor/esqueleto/issues/9</a>).
valkey :: (ToBackendKey SqlBackend entity, PersistField (Key entity)) => Int64 -> SqlExpr (Value (Key entity))

-- | <tt>valJ</tt> is like <tt>val</tt> but for something that is already a
--   <tt>Value</tt>. The use case it was written for was, given a
--   <tt>Value</tt> lift the <tt>Key</tt> for that <tt>Value</tt> into the
--   query expression in a type safe way. However, the implementation is
--   more generic than that so we call it <tt>valJ</tt>.
--   
--   Its important to note that the input entity and the output entity are
--   constrained to be the same by the type signature on the function
--   (<a>https://github.com/prowdsponsor/esqueleto/pull/69</a>).
valJ :: PersistField (Key entity) => Value (Key entity) -> SqlExpr (Value (Key entity))

-- | Avoid N+1 queries and join entities into a map structure.
--   
--   This function is useful to call on the result of a single
--   <tt>JOIN</tt>. For example, suppose you have this query:
--   
--   <pre>
--   getFoosAndNestedBarsFromParent
--       :: ParentId
--       -&gt; SqlPersistT IO [(Entity Foo, Maybe (Entity Bar))]
--   getFoosAndNestedBarsFromParent parentId =
--       <a>select</a> $ do
--           (foo :&amp; bar) &lt;- from $
--               table <tt>Foo
--               <a>`LeftOuterJoin`</a>
--               table </tt>Bar
--                   <a>`on`</a> do
--                       \(foo :&amp; bar) -&gt;
--                           foo ^. FooId ==. bar ?. BarFooId
--           where_ $
--               foo ^. FooParentId ==. val parentId
--           pure (foo, bar)
--   </pre>
--   
--   This is a natural result type for SQL - a list of tuples. However,
--   it's not what we usually want in Haskell - each <tt>Foo</tt> in the
--   list will be represented multiple times, once for each <tt>Bar</tt>.
--   
--   We can write <tt><a>fmap</a> <a>associateJoin</a></tt> and it will
--   translate it into a <tt>Map</tt> that is keyed on the <a>Key</a> of
--   the left <a>Entity</a>, and the value is a tuple of the entity's value
--   as well as the list of each coresponding entity.
--   
--   <pre>
--   getFoosAndNestedBarsFromParentHaskellese
--       :: ParentId
--       -&gt; SqlPersistT (Map (Key Foo) (Foo, [Maybe (Entity Bar)]))
--   getFoosAndNestedBarsFromParentHaskellese parentId =
--       <a>fmap</a> <a>associateJoin</a> $ getFoosdAndNestedBarsFromParent parentId
--   </pre>
--   
--   What if you have multiple joins?
--   
--   Let's use <a>associateJoin</a> with a *two* join query.
--   
--   <pre>
--   userPostComments
--       :: SqlQuery (SqlExpr (Entity User, Entity Post, Entity Comment))
--   userPostsComment = do
--       (u :&amp; p :&amp; c) &lt;- from $
--           table <tt>User
--           <a>`InnerJoin`</a>
--           table </tt>Post
--               <a>on</a> do
--                   \(u :&amp; p) -&gt;
--                       u ^. UserId ==. p ^. PostUserId
--           <a>`InnerJoin`</a>
--           table @Comment
--               <a>`on`</a> do
--                   \(_ :&amp; p :&amp; c) -&gt;
--                       p ^. PostId ==. c ^. CommentPostId
--       pure (u, p, c)
--   </pre>
--   
--   This query returns a User, with all of the users Posts, and then all
--   of the Comments on that post.
--   
--   First, we *nest* the tuple.
--   
--   <pre>
--   nest :: (a, b, c) -&gt; (a, (b, c))
--   nest (a, b, c) = (a, (b, c))
--   </pre>
--   
--   This makes the return of the query conform to the input expected from
--   <a>associateJoin</a>.
--   
--   <pre>
--   nestedUserPostComments
--       :: SqlPersistT IO [(Entity User, (Entity Post, Entity Comment))]
--   nestedUserPostComments =
--       fmap nest $ select userPostsComments
--   </pre>
--   
--   Now, we can call <a>associateJoin</a> on it.
--   
--   <pre>
--   associateUsers
--       :: [(Entity User, (Entity Post, Entity Comment))]
--       -&gt; Map UserId (User, [(Entity Post, Entity Comment)])
--   associateUsers =
--       associateJoin
--   </pre>
--   
--   Next, we'll use the <a>Functor</a> instances for <tt>Map</tt> and
--   tuple to call <a>associateJoin</a> on the <tt>[(Entity Post, Entity
--   Comment)]</tt>.
--   
--   <pre>
--   associatePostsAndComments
--       :: Map UserId (User, [(Entity Post, Entity Comment)])
--       -&gt; Map UserId (User, Map PostId (Post, [Entity Comment]))
--   associatePostsAndComments =
--       fmap (fmap associateJoin)
--   </pre>
--   
--   For more reading on this topic, see <a>this Foxhound Systems blog
--   post</a>.
associateJoin :: forall e1 e0. Ord (Key e0) => [(Entity e0, e1)] -> Map (Key e0) (e0, [e1])

-- | Synonym for <a>delete</a> that does not clash with
--   <tt>esqueleto</tt>'s <a>delete</a>.
deleteKey :: forall backend val (m :: Type -> Type). (PersistStore backend, BaseBackend backend ~ PersistEntityBackend val, MonadIO m, PersistEntity val) => Key val -> ReaderT backend m ()

-- | Persistent serialized Haskell records to the database. A Database
--   <a>Entity</a> (A row in SQL, a document in MongoDB, etc) corresponds
--   to a <a>Key</a> plus a Haskell record.
--   
--   For every Haskell record type stored in the database there is a
--   corresponding <a>PersistEntity</a> 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 <a>PersistEntity</a>, with each query returning
--   different types of Haskell records.
--   
--   Some advanced type system capabilities are used to make this process
--   type-safe. Persistent users usually don't need to understand the class
--   associated data and functions.
class (PersistField Key record, ToJSON Key record, FromJSON Key record, Show Key record, Read Key record, Eq Key record, Ord Key record) => PersistEntity record where {
    
    -- | Persistent allows multiple different backends (databases).
    type PersistEntityBackend record;
    
    -- | By default, a backend will automatically generate the key Instead you
    --   can specify a Primary key made up of unique values.
    data Key record;
    
    -- | An <a>EntityField</a> is parameterised by the Haskell record it
    --   belongs to and the additional type of that field.
    --   
    --   As of <tt>persistent-2.11.0.0</tt>, it's possible to use the
    --   <tt>OverloadedLabels</tt> language extension to refer to
    --   <a>EntityField</a> values polymorphically. See the documentation on
    --   <a>SymbolToField</a> for more information.
    data EntityField record :: Type -> Type;
    
    -- | Unique keys besides the <a>Key</a>.
    data Unique record;
}

-- | A lower-level key operation.
keyToValues :: PersistEntity record => Key record -> [PersistValue]

-- | A lower-level key operation.
keyFromValues :: PersistEntity record => [PersistValue] -> Either Text (Key record)

-- | A meta-operation to retrieve the <a>Key</a> <a>EntityField</a>.
persistIdField :: PersistEntity record => EntityField record (Key record)

-- | Retrieve the <a>EntityDef</a> meta-data for the record.
entityDef :: PersistEntity record => proxy record -> EntityDef

-- | Return meta-data for a given <a>EntityField</a>.
persistFieldDef :: PersistEntity record => EntityField record typ -> FieldDef

-- | A meta-operation to get the database fields of a record.
toPersistFields :: PersistEntity record => record -> [PersistValue]

-- | A lower-level operation to convert from database values to a Haskell
--   record.
fromPersistValues :: PersistEntity record => [PersistValue] -> Either Text record

-- | This function allows you to build an <tt><a>Entity</a> a</tt> by
--   specifying an action that returns a value for the field in the
--   callback function. Let's look at an example.
--   
--   <pre>
--   parseFromEnvironmentVariables :: IO (Entity User)
--   parseFromEnvironmentVariables =
--       tabulateEntityA $ \userField -&gt;
--           case userField of
--               UserName -&gt;
--                   getEnv <a>USER_NAME</a>
--               UserAge -&gt; do
--                   ageVar &lt;- getEnv <a>USER_AGE</a>
--                   case readMaybe ageVar of
--                       Just age -&gt;
--                           pure age
--                       Nothing -&gt;
--                           error $ "Failed to parse Age from: " &lt;&gt; ageVar
--               UserAddressId -&gt; do
--                   addressVar &lt;- getEnv <a>USER_ADDRESS_ID</a>
--                   pure $ AddressKey addressVar
--   </pre>
tabulateEntityA :: (PersistEntity record, Applicative f) => (forall a. () => EntityField record a -> f a) -> f (Entity record)

-- | Like <a>tabulateEntityA</a>, but works with any <a>Apply</a> f. This
--   works because all entities have at least one field, and so we can
--   tabulate things into semigroup-like shapes instead.
tabulateEntityApply :: (PersistEntity record, Apply f) => (forall a. () => EntityField record a -> f a) -> f (Entity record)

-- | A meta operation to retrieve all the <a>Unique</a> keys.
persistUniqueKeys :: PersistEntity record => record -> [Unique record]

-- | A lower level operation.
persistUniqueToFieldNames :: PersistEntity record => Unique record -> NonEmpty (FieldNameHS, FieldNameDB)

-- | A lower level operation.
persistUniqueToValues :: PersistEntity record => Unique record -> [PersistValue]

-- | Use a <a>PersistField</a> as a lens.
fieldLens :: PersistEntity record => EntityField record field -> forall (f :: Type -> Type). Functor f => (field -> f field) -> Entity record -> f (Entity record)

-- | Extract a <tt><a>Key</a> record</tt> from a <tt>record</tt> value.
--   Currently, this is only defined for entities using the
--   <tt>Primary</tt> syntax for natural/composite keys. In a future
--   version of <tt>persistent</tt> which incorporates the ID directly into
--   the entity, this will always be Just.
keyFromRecordM :: PersistEntity record => Maybe (record -> Key record)

-- | By default, a backend will automatically generate the key Instead you
--   can specify a Primary key made up of unique values.
data family Key record
class (Show BackendKey backend, Read BackendKey backend, Eq BackendKey backend, Ord BackendKey backend, PersistStoreRead backend, PersistField BackendKey backend, ToJSON BackendKey backend, FromJSON BackendKey backend) => PersistStoreWrite backend

-- | Create a new record in the database, returning an automatically
--   created key (in SQL an auto-increment id).
--   
--   <h3><b>Example usage</b></h3>
--   
--   Using <a>schema-1</a> and <a>dataset-1</a>, let's insert a new user
--   <tt>John</tt>.
--   
--   <pre>
--   insertJohn :: MonadIO m =&gt; ReaderT SqlBackend m (Key User)
--   insertJohn = insert $ User "John" 30
--   </pre>
--   
--   <pre>
--   johnId &lt;- insertJohn
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will produce this:
--   
--   <pre>
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |40   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   |3    |John  |30   |
--   +-----+------+-----+
--   </pre>
insert :: forall record (m :: Type -> Type). (PersistStoreWrite backend, MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => record -> ReaderT backend m (Key record)

-- | Same as <a>insert</a>, but doesn't return a <tt>Key</tt>.
--   
--   <h3><b>Example usage</b></h3>
--   
--   with <a>schema-1</a> and <a>dataset-1</a>,
--   
--   <pre>
--   insertJohn :: MonadIO m =&gt; ReaderT SqlBackend m (Key User)
--   insertJohn = insert_ $ User "John" 30
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will produce this:
--   
--   <pre>
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |40   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   |3    |John  |30   |
--   +-----+------+-----+
--   </pre>
insert_ :: forall record (m :: Type -> Type). (PersistStoreWrite backend, MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => record -> ReaderT backend m ()

-- | Create multiple records in the database and return their <a>Key</a>s.
--   
--   If you don't need the inserted <a>Key</a>s, use <a>insertMany_</a>.
--   
--   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
--   <tt>mapM insert</tt>.
--   
--   <h3><b>Example usage</b></h3>
--   
--   with <a>schema-1</a> and <a>dataset-1</a>,
--   
--   <pre>
--   insertUsers :: MonadIO m =&gt; ReaderT SqlBackend m [Key User]
--   insertUsers = insertMany [User "John" 30, User "Nick" 32, User "Jane" 20]
--   </pre>
--   
--   <pre>
--   userIds &lt;- insertUsers
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will produce this:
--   
--   <pre>
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |40   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   |3    |John  |30   |
--   +-----+------+-----+
--   |4    |Nick  |32   |
--   +-----+------+-----+
--   |5    |Jane  |20   |
--   +-----+------+-----+
--   </pre>
insertMany :: forall record (m :: Type -> Type). (PersistStoreWrite backend, MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => [record] -> ReaderT backend m [Key record]

-- | Same as <a>insertMany</a>, but doesn't return any <a>Key</a>s.
--   
--   The MongoDB, PostgreSQL, SQLite and MySQL backends insert all records
--   in one database query.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>,
--   
--   <pre>
--   insertUsers_ :: MonadIO m =&gt; ReaderT SqlBackend m ()
--   insertUsers_ = insertMany_ [User "John" 30, User "Nick" 32, User "Jane" 20]
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will produce this:
--   
--   <pre>
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |40   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   |3    |John  |30   |
--   +-----+------+-----+
--   |4    |Nick  |32   |
--   +-----+------+-----+
--   |5    |Jane  |20   |
--   +-----+------+-----+
--   </pre>
insertMany_ :: forall record (m :: Type -> Type). (PersistStoreWrite backend, MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => [record] -> ReaderT backend m ()

-- | Same as <a>insertMany_</a>, but takes an <a>Entity</a> 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.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>,
--   
--   <pre>
--   insertUserEntityMany :: MonadIO m =&gt; ReaderT SqlBackend m ()
--   insertUserEntityMany = insertEntityMany [SnakeEntity, EvaEntity]
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will produce this:
--   
--   <pre>
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |40   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   |3    |Snake |38   |
--   +-----+------+-----+
--   |4    |Eva   |38   |
--   +-----+------+-----+
--   </pre>
insertEntityMany :: forall record (m :: Type -> Type). (PersistStoreWrite backend, MonadIO m, PersistRecordBackend record backend) => [Entity record] -> ReaderT backend m ()

-- | Create a new record in the database using the given key.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>,
--   
--   <pre>
--   insertAliceKey :: MonadIO m =&gt; Key User -&gt; ReaderT SqlBackend m ()
--   insertAliceKey key = insertKey key $ User "Alice" 20
--   </pre>
--   
--   <pre>
--   insertAliceKey $ UserKey {unUserKey = SqlBackendKey {unSqlBackendKey = 3}}
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will produce this:
--   
--   <pre>
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |40   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   |3    |Alice |20   |
--   +-----+------+-----+
--   </pre>
insertKey :: forall record (m :: Type -> Type). (PersistStoreWrite backend, MonadIO m, PersistRecordBackend record backend) => Key record -> record -> ReaderT backend m ()

-- | Put the record in the database with the given key. Unlike
--   <a>replace</a>, if a record with the given key does not exist then a
--   new record will be inserted.
--   
--   <h3><b>Example usage</b></h3>
--   
--   We try to explain <tt>upsertBy</tt> using <a>schema-1</a> and
--   <a>dataset-1</a>.
--   
--   First, we insert Philip to <a>dataset-1</a>.
--   
--   <pre>
--   insertPhilip :: MonadIO m =&gt; ReaderT SqlBackend m (Key User)
--   insertPhilip = insert $ User "Philip" 42
--   </pre>
--   
--   <pre>
--   philipId &lt;- insertPhilip
--   </pre>
--   
--   This query will produce:
--   
--   <pre>
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |40   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   |3    |Philip|42   |
--   +-----+------+-----+
--   </pre>
--   
--   <pre>
--   repsertHaskell :: MonadIO m =&gt; Key record -&gt; ReaderT SqlBackend m ()
--   repsertHaskell id = repsert id $ User "Haskell" 81
--   </pre>
--   
--   <pre>
--   repsertHaskell philipId
--   </pre>
--   
--   This query will replace Philip's record with Haskell's one:
--   
--   <pre>
--   +-----+-----------------+--------+
--   |id   |name             |age     |
--   +-----+-----------------+--------+
--   |1    |SPJ              |40      |
--   +-----+-----------------+--------+
--   |2    |Simon            |41      |
--   +-----+-----------------+--------+
--   |3    |Philip -&gt; Haskell|42 -&gt; 81|
--   +-----+-----------------+--------+
--   </pre>
--   
--   <a>repsert</a> inserts the given record if the key doesn't exist.
--   
--   <pre>
--   repsertXToUnknown :: MonadIO m =&gt; ReaderT SqlBackend m ()
--   repsertXToUnknown = repsert unknownId $ User "X" 999
--   </pre>
--   
--   For example, applying the above query to <a>dataset-1</a> will produce
--   this:
--   
--   <pre>
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |40   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   |3    |X     |999  |
--   +-----+------+-----+
--   </pre>
repsert :: forall record (m :: Type -> Type). (PersistStoreWrite backend, MonadIO m, PersistRecordBackend record backend) => Key record -> record -> ReaderT backend m ()

-- | Put many entities into the database.
--   
--   Batch version of <a>repsert</a> for SQL backends.
--   
--   Useful when migrating data from one entity to another and want to
--   preserve ids.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>,
--   
--   <pre>
--   repsertManyUsers :: MonadIO m =&gt;ReaderT SqlBackend m ()
--   repsertManyusers = repsertMany [(simonId, User "Philip" 20), (unknownId999, User "Mr. X" 999)]
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will produce this:
--   
--   <pre>
--   +-----+----------------+---------+
--   |id   |name            |age      |
--   +-----+----------------+---------+
--   |1    |SPJ             |40       |
--   +-----+----------------+---------+
--   |2    |Simon -&gt; Philip |41 -&gt; 20 |
--   +-----+----------------+---------+
--   |999  |Mr. X           |999      |
--   +-----+----------------+---------+
--   </pre>
repsertMany :: forall record (m :: Type -> Type). (PersistStoreWrite backend, 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
--   <a>insertKey</a> or <a>repsert</a> in these cases.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1 schama-1</a> and <a>dataset-1</a>,
--   
--   <pre>
--   replaceSpj :: MonadIO m =&gt; User -&gt; ReaderT SqlBackend m ()
--   replaceSpj record = replace spjId record
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will produce this:
--   
--   <pre>
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |Mike  |45   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   </pre>
replace :: forall record (m :: Type -> Type). (PersistStoreWrite backend, MonadIO m, PersistRecordBackend record backend) => Key record -> record -> ReaderT backend m ()

-- | Update individual fields on a specific record, and retrieve the
--   updated value from the database.
--   
--   Note that this function will throw an exception if the given key is
--   not found in the database.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>,
--   
--   <pre>
--   updateGetSpj :: MonadIO m =&gt; [Update User] -&gt; ReaderT SqlBackend m User
--   updateGetSpj updates = updateGet spjId updates
--   </pre>
--   
--   <pre>
--   spj &lt;- updateGetSpj [UserAge +=. 100]
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will produce this:
--   
--   <pre>
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |140  |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   </pre>
updateGet :: forall record (m :: Type -> Type). (PersistStoreWrite backend, MonadIO m, PersistRecordBackend record backend) => Key record -> [Update record] -> ReaderT backend m record
data PersistFilter
Eq :: PersistFilter
Ne :: PersistFilter
Gt :: PersistFilter
Lt :: PersistFilter
Ge :: PersistFilter
Le :: PersistFilter
In :: PersistFilter
NotIn :: PersistFilter
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

-- | Get a record by identifier, if available.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>,
--   
--   <pre>
--   getSpj :: MonadIO m =&gt; ReaderT SqlBackend m (Maybe User)
--   getSpj = get spjId
--   </pre>
--   
--   <pre>
--   mspj &lt;- getSpj
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will get this:
--   
--   <pre>
--   +------+-----+
--   | name | age |
--   +------+-----+
--   | SPJ  |  40 |
--   +------+-----+
--   </pre>
get :: forall record (m :: Type -> Type). (PersistStoreRead backend, MonadIO m, PersistRecordBackend record backend) => Key record -> ReaderT backend m (Maybe record)

-- | Get many records by their respective identifiers, if available.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>:
--   
--   <pre>
--   getUsers :: MonadIO m =&gt; ReaderT SqlBackend m (Map (Key User) User)
--   getUsers = getMany allkeys
--   </pre>
--   
--   <pre>
--   musers &lt;- getUsers
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will get these
--   records:
--   
--   <pre>
--   +----+-------+-----+
--   | id | name  | age |
--   +----+-------+-----+
--   |  1 | SPJ   |  40 |
--   +----+-------+-----+
--   |  2 | Simon |  41 |
--   +----+-------+-----+
--   </pre>
getMany :: forall record (m :: Type -> Type). (PersistStoreRead backend, MonadIO m, PersistRecordBackend record backend) => [Key record] -> ReaderT backend m (Map (Key record) record)

-- | Some functions in this module (<a>insertUnique</a>, <a>insertBy</a>,
--   and <a>replaceUnique</a>) first query the unique indexes to check for
--   conflicts. You could instead optimistically attempt to perform the
--   operation (e.g. <a>replace</a> instead of <a>replaceUnique</a>).
--   However,
--   
--   <ul>
--   <li>there is some fragility to trying to catch the correct exception
--   and determing the column of failure;</li>
--   <li>an exception will automatically abort the current SQL
--   transaction.</li>
--   </ul>
class (PersistUniqueRead backend, PersistStoreWrite backend) => PersistUniqueWrite backend

-- | Delete a specific record by unique key. Does nothing if no record
--   matches.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>,
--   
--   <pre>
--   deleteBySpjName :: MonadIO m =&gt; ReaderT SqlBackend m ()
--   deleteBySpjName = deleteBy (UniqueUserName "SPJ")
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will produce this:
--   
--   <pre>
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   </pre>
deleteBy :: forall record (m :: Type -> Type). (PersistUniqueWrite backend, MonadIO m, PersistRecordBackend record backend) => Unique record -> ReaderT backend m ()

-- | Like <a>insert</a>, but returns <a>Nothing</a> when the record
--   couldn't be inserted because of a uniqueness constraint.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>, we try to insert the
--   following two records:
--   
--   <pre>
--   linusId &lt;- insertUnique $ User "Linus" 48
--   spjId   &lt;- insertUnique $ User "SPJ" 90
--   </pre>
--   
--   <pre>
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |40   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   |3    |Linus |48   |
--   +-----+------+-----+
--   </pre>
--   
--   Linus's record was inserted to <a>dataset-1</a>, while SPJ wasn't
--   because SPJ already exists in <a>dataset-1</a>.
insertUnique :: forall record (m :: Type -> Type). (PersistUniqueWrite backend, MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => record -> ReaderT backend m (Maybe (Key record))

-- | Same as <a>insertUnique</a> but doesn't return a <tt>Key</tt>.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>, we try to insert the
--   following two records:
--   
--   <pre>
--   linusId &lt;- insertUnique_ $ User "Linus" 48
--   spjId   &lt;- insertUnique_ $ User "SPJ" 90
--   </pre>
--   
--   <pre>
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |40   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   |3    |Linus |48   |
--   +-----+------+-----+
--   </pre>
--   
--   Linus's record was inserted to <a>dataset-1</a>, while SPJ wasn't
--   because SPJ already exists in <a>dataset-1</a>.
insertUnique_ :: forall record (m :: Type -> Type). (PersistUniqueWrite backend, MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => record -> ReaderT backend m (Maybe ())

-- | Update based on a uniqueness constraint or insert:
--   
--   <ul>
--   <li>insert the new record if it does not exist;</li>
--   <li>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.</li>
--   </ul>
--   
--   <h3><b>Example usage</b></h3>
--   
--   First, we try to explain <a>upsert</a> using <a>schema-1</a> and
--   <a>dataset-1</a>.
--   
--   <pre>
--   upsertSpj :: MonadIO m =&gt; [Update User] -&gt; ReaderT SqlBackend m (Maybe (Entity User))
--   upsertSpj updates = upsert (User "SPJ" 999) updates
--   </pre>
--   
--   <pre>
--   mSpjEnt &lt;- upsertSpj [UserAge +=. 15]
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will produce this:
--   
--   <pre>
--   +-----+-----+--------+
--   |id   |name |age     |
--   +-----+-----+--------+
--   |1    |SPJ  |40 -&gt; 55|
--   +-----+-----+--------+
--   |2    |Simon|41      |
--   +-----+-----+--------+
--   </pre>
--   
--   <pre>
--   upsertX :: MonadIO m =&gt; [Update User] -&gt; ReaderT SqlBackend m (Maybe (Entity User))
--   upsertX updates = upsert (User "X" 999) updates
--   </pre>
--   
--   <pre>
--   mXEnt &lt;- upsertX [UserAge +=. 15]
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will produce this:
--   
--   <pre>
--   +-----+-----+--------+
--   |id   |name |age     |
--   +-----+-----+--------+
--   |1    |SPJ  |40      |
--   +-----+-----+--------+
--   |2    |Simon|41      |
--   +-----+-----+--------+
--   |3    |X    |999     |
--   +-----+-----+--------+
--   </pre>
--   
--   Next, what if the schema has two uniqueness constraints? Let's check
--   it out using <a>schema-2</a>:
--   
--   <pre>
--   mSpjEnt &lt;- upsertSpj [UserAge +=. 15]
--   </pre>
--   
--   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
--   <a>upsertBy</a> to select the unique key we want.
upsert :: forall record (m :: Type -> Type). (PersistUniqueWrite backend, MonadIO m, PersistRecordBackend record backend, OnlyOneUniqueKey record, SafeToInsert record) => record -> [Update record] -> ReaderT backend m (Entity record)

-- | Update based on a given uniqueness constraint or insert:
--   
--   <ul>
--   <li>insert the new record if it does not exist;</li>
--   <li>update the existing record that matches the given uniqueness
--   constraint.</li>
--   </ul>
--   
--   <h3><b>Example usage</b></h3>
--   
--   We try to explain <a>upsertBy</a> using <a>schema-2</a> and
--   <a>dataset-1</a>.
--   
--   <pre>
--   upsertBySpjName :: MonadIO m =&gt; User -&gt; [Update User] -&gt; ReaderT SqlBackend m (Entity User)
--   upsertBySpjName record updates = upsertBy (UniqueUserName "SPJ") record updates
--   </pre>
--   
--   <pre>
--   mSpjEnt &lt;- upsertBySpjName (Person "X" 999) [PersonAge += .15]
--   </pre>
--   
--   The above query will alter <a>dataset-1</a> to:
--   
--   <pre>
--   +-----+-----+--------+
--   |id   |name |age     |
--   +-----+-----+--------+
--   |1    |SPJ  |40 -&gt; 55|
--   +-----+-----+--------+
--   |2    |Simon|41      |
--   +-----+-----+--------+
--   </pre>
--   
--   <pre>
--   upsertBySimonAge :: MonadIO m =&gt; User -&gt; [Update User] -&gt; ReaderT SqlBackend m (Entity User)
--   upsertBySimonAge record updates = upsertBy (UniqueUserName "SPJ") record updates
--   </pre>
--   
--   <pre>
--   mPhilipEnt &lt;- upsertBySimonAge (User "X" 999) [UserName =. "Philip"]
--   </pre>
--   
--   The above query will alter <a>dataset-1</a> to:
--   
--   <pre>
--   +----+-----------------+-----+
--   | id |      name       | age |
--   +----+-----------------+-----+
--   |  1 | SPJ             |  40 |
--   +----+-----------------+-----+
--   |  2 | Simon -&gt; Philip |  41 |
--   +----+-----------------+-----+
--   </pre>
--   
--   <pre>
--   upsertByUnknownName :: MonadIO m =&gt; User -&gt; [Update User] -&gt; ReaderT SqlBackend m (Entity User)
--   upsertByUnknownName record updates = upsertBy (UniqueUserName "Unknown") record updates
--   </pre>
--   
--   <pre>
--   mXEnt &lt;- upsertByUnknownName (User "X" 999) [UserAge +=. 15]
--   </pre>
--   
--   This query will alter <a>dataset-1</a> to:
--   
--   <pre>
--   +-----+-----+-----+
--   |id   |name |age  |
--   +-----+-----+-----+
--   |1    |SPJ  |40   |
--   +-----+-----+-----+
--   |2    |Simon|41   |
--   +-----+-----+-----+
--   |3    |X    |999  |
--   +-----+-----+-----+
--   </pre>
upsertBy :: forall record (m :: Type -> Type). (PersistUniqueWrite backend, MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => Unique record -> record -> [Update record] -> ReaderT backend m (Entity record)

-- | Put many records into db
--   
--   <ul>
--   <li>insert new records that do not exist (or violate any unique
--   constraints)</li>
--   <li>replace existing records (matching any unique constraint)</li>
--   </ul>
putMany :: forall record (m :: Type -> Type). (PersistUniqueWrite backend, MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => [record] -> ReaderT backend m ()

-- | Insert a value, checking for conflicts with any unique constraints. If
--   a duplicate exists in the database, it is returned as <a>Left</a>.
--   Otherwise, the new 'Key is returned as <a>Right</a>.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-2</a> and <a>dataset-1</a>, we have following lines of
--   code:
--   
--   <pre>
--   l1 &lt;- insertBy $ User "SPJ" 20
--   l2 &lt;- insertBy $ User "XXX" 41
--   l3 &lt;- insertBy $ User "SPJ" 40
--   r1 &lt;- insertBy $ User "XXX" 100
--   </pre>
--   
--   First three lines return <a>Left</a> because there're duplicates in
--   given record's uniqueness constraints. While the last line returns a
--   new key as <a>Right</a>.
insertBy :: forall record backend (m :: Type -> Type). (MonadIO m, PersistUniqueWrite backend, PersistRecordBackend record backend, AtLeastOneUniqueKey record, SafeToInsert record) => record -> ReaderT backend m (Either (Entity record) (Key record))

-- | Given a list of old entity definitions and a new <a>EntityDef</a> in
--   <tt>val</tt>, this creates a <a>Migration</a> to update the old list
--   of definitions with the new one.
migrate :: [EntityDef] -> EntityDef -> Migration

-- | Report a single error in a <a>Migration</a>.
reportError :: Text -> Migration

-- | Unique keys besides the <a>Key</a>.
data family Unique record

-- | A single column (see <tt>rawSql</tt>). Any <tt>PersistField</tt> may
--   be used here, including <a>PersistValue</a> (which does not do any
--   processing).
newtype Single a
Single :: a -> Single a
[unSingle] :: Single a -> a
data Column
Column :: !FieldNameDB -> !Bool -> !SqlType -> !Maybe Text -> !Maybe Text -> !Maybe ConstraintNameDB -> !Maybe Integer -> !Maybe ColumnReference -> Column
[cName] :: Column -> !FieldNameDB
[cNull] :: Column -> !Bool
[cSqlType] :: Column -> !SqlType
[cDefault] :: Column -> !Maybe Text
[cGenerated] :: Column -> !Maybe Text
[cDefaultConstraintName] :: Column -> !Maybe ConstraintNameDB
[cMaxLen] :: Column -> !Maybe Integer
[cReference] :: Column -> !Maybe ColumnReference

-- | Execute a raw SQL statement and return its results as a list. If you
--   do not expect a return value, use of <a>rawExecute</a> is recommended.
--   
--   If you're using <a>Entity</a><tt>s</tt> (which is quite likely), then
--   you <i>must</i> use entity selection placeholders (double question
--   mark, <tt>??</tt>). These <tt>??</tt> placeholders are then replaced
--   for the names of the columns that we need for your entities. You'll
--   receive an error if you don't use the placeholders. Please see the
--   <a>Entity</a><tt>s</tt> documentation for more details.
--   
--   You may put value placeholders (question marks, <tt>?</tt>) in your
--   SQL query. These placeholders are then replaced by the values you pass
--   on the second parameter, already correctly escaped. You may want to
--   use <a>toPersistValue</a> to help you constructing the placeholder
--   values.
--   
--   Since you're giving a raw SQL statement, you don't get any guarantees
--   regarding safety. If <a>rawSql</a> is not able to parse the results of
--   your query back, then an exception is raised. However, most common
--   problems are mitigated by using the entity selection placeholder
--   <tt>??</tt>, and you shouldn't see any error at all if you're not
--   using <a>Single</a>.
--   
--   Some example of <a>rawSql</a> based on this schema:
--   
--   <pre>
--   share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
--   Person
--       name String
--       age Int Maybe
--       deriving Show
--   BlogPost
--       title String
--       authorId PersonId
--       deriving Show
--   |]
--   </pre>
--   
--   Examples based on the above schema:
--   
--   <pre>
--   getPerson :: MonadIO m =&gt; ReaderT SqlBackend m [Entity Person]
--   getPerson = rawSql "select ?? from person where name=?" [PersistText "john"]
--   
--   getAge :: MonadIO m =&gt; ReaderT SqlBackend m [Single Int]
--   getAge = rawSql "select person.age from person where name=?" [PersistText "john"]
--   
--   getAgeName :: MonadIO m =&gt; ReaderT SqlBackend m [(Single Int, Single Text)]
--   getAgeName = rawSql "select person.age, person.name from person where name=?" [PersistText "john"]
--   
--   getPersonBlog :: MonadIO m =&gt; ReaderT SqlBackend m [(Entity Person, Entity BlogPost)]
--   getPersonBlog = rawSql "select ??,?? from person,blog_post where person.id = blog_post.author_id" []
--   </pre>
--   
--   Minimal working program for PostgreSQL backend based on the above
--   concepts:
--   
--   <pre>
--   {-# LANGUAGE EmptyDataDecls             #-}
--   {-# LANGUAGE FlexibleContexts           #-}
--   {-# LANGUAGE GADTs                      #-}
--   {-# LANGUAGE GeneralizedNewtypeDeriving #-}
--   {-# LANGUAGE MultiParamTypeClasses      #-}
--   {-# LANGUAGE OverloadedStrings          #-}
--   {-# LANGUAGE QuasiQuotes                #-}
--   {-# LANGUAGE TemplateHaskell            #-}
--   {-# LANGUAGE TypeFamilies               #-}
--   
--   import           Control.Monad.IO.Class  (liftIO)
--   import           Control.Monad.Logger    (runStderrLoggingT)
--   import           Database.Persist
--   import           Control.Monad.Reader
--   import           Data.Text
--   import           Database.Persist.Sql
--   import           Database.Persist.Postgresql
--   import           Database.Persist.TH
--   
--   share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
--   Person
--       name String
--       age Int Maybe
--       deriving Show
--   |]
--   
--   conn = "host=localhost dbname=new_db user=postgres password=postgres port=5432"
--   
--   getPerson :: MonadIO m =&gt; ReaderT SqlBackend m [Entity Person]
--   getPerson = rawSql "select ?? from person where name=?" [PersistText "sibi"]
--   
--   liftSqlPersistMPool y x = liftIO (runSqlPersistMPool y x)
--   
--   main :: IO ()
--   main = runStderrLoggingT $ withPostgresqlPool conn 10 $ liftSqlPersistMPool $ do
--            runMigration migrateAll
--            xs &lt;- getPerson
--            liftIO (print xs)
--   </pre>
rawSql :: forall a (m :: Type -> Type) backend. (RawSql a, MonadIO m, BackendCompatible SqlBackend backend) => Text -> [PersistValue] -> ReaderT backend m [a]

-- | Represents a value containing all the configuration options for a
--   specific backend. This abstraction makes it easier to write code that
--   can easily swap backends.
class PersistConfig c where {
    type PersistConfigBackend c :: Type -> Type -> Type -> Type;
    type PersistConfigPool c;
}

-- | Load the config settings from a <a>Value</a>, most likely taken from a
--   YAML config file.
loadConfig :: PersistConfig c => Value -> Parser c

-- | Modify the config settings based on environment variables.
applyEnv :: PersistConfig c => c -> IO c

-- | Create a new connection pool based on the given config settings.
createPoolConfig :: PersistConfig c => c -> IO (PersistConfigPool c)

-- | Run a database action by taking a connection from the pool.
runPool :: (PersistConfig c, MonadUnliftIO m) => c -> PersistConfigBackend c m a -> PersistConfigPool c -> m a
type family PersistConfigBackend c :: Type -> Type -> Type -> Type
type family PersistConfigPool c

-- | An <a>ConstraintNameHS</a> represents the Haskell-side name that
--   <tt>persistent</tt> will use for a constraint.
newtype ConstraintNameHS
ConstraintNameHS :: Text -> ConstraintNameHS
[unConstraintNameHS] :: ConstraintNameHS -> Text

-- | A <a>ConstraintNameDB</a> represents the datastore-side name that
--   <tt>persistent</tt> will use for a constraint.
newtype ConstraintNameDB
ConstraintNameDB :: Text -> ConstraintNameDB
[unConstraintNameDB] :: ConstraintNameDB -> Text

-- | An <a>EntityNameDB</a> represents the datastore-side name that
--   <tt>persistent</tt> will use for an entity.
newtype EntityNameDB
EntityNameDB :: Text -> EntityNameDB
[unEntityNameDB] :: EntityNameDB -> Text

-- | An <a>EntityNameHS</a> represents the Haskell-side name that
--   <tt>persistent</tt> will use for an entity.
newtype EntityNameHS
EntityNameHS :: Text -> EntityNameHS
[unEntityNameHS] :: EntityNameHS -> Text

-- | A <a>FieldNameHS</a> represents the Haskell-side name that
--   <tt>persistent</tt> will use for a field.
newtype FieldNameHS
FieldNameHS :: Text -> FieldNameHS
[unFieldNameHS] :: FieldNameHS -> Text

-- | A <a>FieldNameDB</a> represents the datastore-side name that
--   <tt>persistent</tt> will use for a field.
newtype FieldNameDB
FieldNameDB :: Text -> FieldNameDB
[unFieldNameDB] :: FieldNameDB -> Text

-- | Convenience operations for working with '-NameDB' types.
class DatabaseName a
escapeWith :: DatabaseName a => (Text -> str) -> a -> str

-- | A type that determines how a backend should handle the literal.
data LiteralType

-- | The accompanying value will be escaped before inserting into the
--   database. This is the correct default choice to use.
Escaped :: LiteralType

-- | The accompanying value will not be escaped when inserting into the
--   database. This is potentially dangerous - use this with care.
Unescaped :: LiteralType

-- | The <a>DbSpecific</a> constructor corresponds to the legacy
--   <a>PersistDbSpecific</a> 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.
DbSpecific :: LiteralType

-- | A raw value which can be stored in any backend and can be marshalled
--   to and from a <tt>PersistField</tt>.
data PersistValue
PersistText :: Text -> PersistValue
PersistByteString :: ByteString -> PersistValue
PersistInt64 :: Int64 -> PersistValue
PersistDouble :: Double -> PersistValue
PersistRational :: Rational -> PersistValue
PersistBool :: Bool -> PersistValue
PersistDay :: Day -> PersistValue
PersistTimeOfDay :: TimeOfDay -> PersistValue
PersistUTCTime :: UTCTime -> PersistValue
PersistNull :: PersistValue
PersistList :: [PersistValue] -> PersistValue
PersistMap :: [(Text, PersistValue)] -> PersistValue

-- | Intended especially for MongoDB backend
PersistObjectId :: ByteString -> PersistValue

-- | Intended especially for PostgreSQL backend for text arrays
PersistArray :: [PersistValue] -> PersistValue

-- | This constructor is used to specify some raw literal value for the
--   backend. The <a>LiteralType</a> value specifies how the value should
--   be escaped. This can be used to make special, custom types avaialable
--   in the back end.
PersistLiteral_ :: LiteralType -> ByteString -> PersistValue

-- | This pattern synonym used to be a data constructor on
--   <a>PersistValue</a>, but was changed into a catch-all pattern synonym
--   to allow backwards compatiblity with database types. See the
--   documentation on <a>PersistDbSpecific</a> for more details.
pattern PersistLiteral :: ByteString -> PersistValue

-- | This pattern synonym used to be a data constructor on
--   <a>PersistValue</a>, but was changed into a catch-all pattern synonym
--   to allow backwards compatiblity with database types. See the
--   documentation on <a>PersistDbSpecific</a> for more details.
pattern PersistLiteralEscaped :: ByteString -> PersistValue

-- | This pattern synonym used to be a data constructor for the
--   <a>PersistValue</a> 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 <a>PersistLiteral_</a> directly.
--   
--   If you use this, it will overlap a patern match on the
--   'PersistLiteral_, <a>PersistLiteral</a>, and
--   <a>PersistLiteralEscaped</a> patterns. If you need to disambiguate
--   between these constructors, pattern match on <a>PersistLiteral_</a>
--   directly.
pattern PersistDbSpecific :: ByteString -> PersistValue
fromPersistValueText :: PersistValue -> Either Text Text

-- | Please refer to the documentation for the database in question for a
--   full overview of the semantics of the varying isolation levels
data IsolationLevel
ReadUncommitted :: IsolationLevel
ReadCommitted :: IsolationLevel
RepeatableRead :: IsolationLevel
Serializable :: IsolationLevel

-- | A <a>FieldDef</a> represents the inormation that <tt>persistent</tt>
--   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.
data FieldDef
FieldDef :: !FieldNameHS -> !FieldNameDB -> !FieldType -> !SqlType -> ![FieldAttr] -> !Bool -> !ReferenceDef -> !FieldCascade -> !Maybe Text -> !Maybe Text -> !Bool -> FieldDef

-- | The 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
--   <a>FieldDef</a> that contains a <tt><a>FieldNameHS</a> "name"</tt> for
--   a type <tt>User</tt> will have a record field <tt>userName</tt>.
[fieldHaskell] :: FieldDef -> !FieldNameHS

-- | The name of the field in the database. For SQL databases, this
--   corresponds to the column name.
[fieldDB] :: FieldDef -> !FieldNameDB

-- | The type of the field in Haskell.
[fieldType] :: FieldDef -> !FieldType

-- | The type of the field in a SQL database.
[fieldSqlType] :: FieldDef -> !SqlType

-- | User annotations for a field. These are provided with the <tt>!</tt>
--   operator.
[fieldAttrs] :: FieldDef -> ![FieldAttr]

-- | If this is <a>True</a>, then the Haskell datatype will have a strict
--   record field. The default value for this is <a>True</a>.
[fieldStrict] :: FieldDef -> !Bool
[fieldReference] :: FieldDef -> !ReferenceDef

-- | Defines how operations on the field cascade on to the referenced
--   tables. This doesn't have any meaning if the <a>fieldReference</a> is
--   set to <a>NoReference</a> or <a>SelfReference</a>. The cascade option
--   here should be the same as the one obtained in the
--   <a>fieldReference</a>.
[fieldCascade] :: FieldDef -> !FieldCascade

-- | Optional comments for a <tt>Field</tt>.
[fieldComments] :: FieldDef -> !Maybe Text

-- | Whether or not the field is a <tt>GENERATED</tt> column, and
--   additionally the expression to use for generation.
[fieldGenerated] :: FieldDef -> !Maybe Text

-- | <a>True</a> if the field is an implicit ID column. <a>False</a>
--   otherwise.
[fieldIsImplicitIdColumn] :: FieldDef -> !Bool
data PersistUpdate
Assign :: PersistUpdate
Add :: PersistUpdate
Subtract :: PersistUpdate
Multiply :: PersistUpdate
Divide :: PersistUpdate
BackendSpecificUpdate :: Text -> PersistUpdate
type family BackendSpecificUpdate backend record
data UpdateException
KeyNotFound :: String -> UpdateException
UpsertError :: String -> UpdateException

-- | 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.
data SqlType
SqlString :: SqlType
SqlInt32 :: SqlType
SqlInt64 :: SqlType
SqlReal :: SqlType
SqlNumeric :: Word32 -> Word32 -> SqlType
SqlBool :: SqlType
SqlDay :: SqlType
SqlTime :: SqlType

-- | Always uses UTC timezone
SqlDayTime :: SqlType
SqlBlob :: SqlType

-- | a backend-specific name
SqlOther :: Text -> SqlType
data PersistException

-- | Generic Exception
PersistError :: Text -> PersistException
PersistMarshalError :: Text -> PersistException
PersistInvalidField :: Text -> PersistException
PersistForeignConstraintUnmet :: Text -> PersistException
PersistMongoDBError :: Text -> PersistException
PersistMongoDBUnsupported :: Text -> PersistException

-- | An action that might happen on a deletion or update on a foreign key
--   change.
data CascadeAction
Cascade :: CascadeAction
Restrict :: CascadeAction
SetNull :: CascadeAction
SetDefault :: CascadeAction

-- | 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 <a>Nothing</a> in either of the field values means that
--   the user has not specified a <a>CascadeAction</a>. An unspecified
--   <a>CascadeAction</a> is defaulted to <a>Restrict</a> when doing
--   migrations.
data FieldCascade
FieldCascade :: !Maybe CascadeAction -> !Maybe CascadeAction -> FieldCascade
[fcOnUpdate] :: FieldCascade -> !Maybe CascadeAction
[fcOnDelete] :: FieldCascade -> !Maybe CascadeAction
data ForeignDef
ForeignDef :: !EntityNameHS -> !EntityNameDB -> !ConstraintNameHS -> !ConstraintNameDB -> !FieldCascade -> ![(ForeignFieldDef, ForeignFieldDef)] -> ![Attr] -> Bool -> Bool -> ForeignDef
[foreignRefTableHaskell] :: ForeignDef -> !EntityNameHS
[foreignRefTableDBName] :: ForeignDef -> !EntityNameDB
[foreignConstraintNameHaskell] :: ForeignDef -> !ConstraintNameHS
[foreignConstraintNameDBName] :: ForeignDef -> !ConstraintNameDB

-- | Determine how the field will cascade on updates and deletions.
[foreignFieldCascade] :: ForeignDef -> !FieldCascade
[foreignFields] :: ForeignDef -> ![(ForeignFieldDef, ForeignFieldDef)]
[foreignAttrs] :: ForeignDef -> ![Attr]
[foreignNullable] :: ForeignDef -> Bool

-- | Determines if the reference is towards a Primary Key or not.
[foreignToPrimary] :: ForeignDef -> Bool

-- | Used instead of FieldDef to generate a smaller amount of code
type ForeignFieldDef = (FieldNameHS, FieldNameDB)
data CompositeDef
CompositeDef :: !NonEmpty FieldDef -> ![Attr] -> CompositeDef
[compositeFields] :: CompositeDef -> !NonEmpty FieldDef
[compositeAttrs] :: CompositeDef -> ![Attr]

-- | Type for storing the Uniqueness constraint in the Schema. Assume you
--   have the following schema with a uniqueness constraint:
--   
--   <pre>
--   Person
--     name String
--     age Int
--     UniqueAge age
--   </pre>
--   
--   This will be represented as:
--   
--   <pre>
--   UniqueDef
--       { uniqueHaskell = ConstraintNameHS (packPTH <a>UniqueAge</a>)
--       , uniqueDBName = ConstraintNameDB (packPTH "unique_age")
--       , uniqueFields = [(FieldNameHS (packPTH "age"), FieldNameDB (packPTH "age"))]
--       , uniqueAttrs = []
--       }
--   </pre>
data UniqueDef
UniqueDef :: !ConstraintNameHS -> !ConstraintNameDB -> !NonEmpty (FieldNameHS, FieldNameDB) -> ![Attr] -> UniqueDef
[uniqueHaskell] :: UniqueDef -> !ConstraintNameHS
[uniqueDBName] :: UniqueDef -> !ConstraintNameDB
[uniqueFields] :: UniqueDef -> !NonEmpty (FieldNameHS, FieldNameDB)
[uniqueAttrs] :: UniqueDef -> ![Attr]

-- | An EmbedFieldDef is the same as a FieldDef But it is only used for
--   embeddedFields so it only has data needed for embedding
data EmbedFieldDef
EmbedFieldDef :: FieldNameDB -> Maybe (Either SelfEmbed EntityNameHS) -> EmbedFieldDef
[emFieldDB] :: EmbedFieldDef -> FieldNameDB
[emFieldEmbed] :: EmbedFieldDef -> Maybe (Either SelfEmbed EntityNameHS)

-- | An EmbedEntityDef is the same as an EntityDef But it is only used for
--   fieldReference so it only has data needed for embedding
data EmbedEntityDef
EmbedEntityDef :: EntityNameHS -> [EmbedFieldDef] -> EmbedEntityDef
[embeddedHaskell] :: EmbedEntityDef -> EntityNameHS
[embeddedFields] :: EmbedEntityDef -> [EmbedFieldDef]

-- | There are 3 kinds of references 1) composite (to fields that exist in
--   the record) 2) single field 3) embedded
data ReferenceDef
NoReference :: ReferenceDef

-- | A 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
ForeignRef :: !EntityNameHS -> ReferenceDef
EmbedRef :: EntityNameHS -> ReferenceDef

-- | A SelfReference stops an immediate cycle which causes non-termination
--   at compile-time (issue #311).
SelfReference :: ReferenceDef

-- | A <a>FieldType</a> describes a field parsed from the QuasiQuoter and
--   is used to determine the Haskell type in the generated code.
--   
--   <tt>name Text</tt> parses into <tt>FTTypeCon Nothing <a>Text</a></tt>
--   
--   <tt>name T.Text</tt> parses into <tt>FTTypeCon (Just <a>T</a>
--   <a>Text</a>)</tt>
--   
--   <tt>name (Jsonb User)</tt> parses into:
--   
--   <pre>
--   FTApp (FTTypeCon Nothing <a>Jsonb</a>) (FTTypeCon Nothing <a>User</a>)
--   </pre>
data FieldType

-- | Optional module and name.
FTTypeCon :: Maybe Text -> Text -> FieldType
FTLit :: FieldTypeLit -> FieldType
FTTypePromoted :: Text -> FieldType
FTApp :: FieldType -> FieldType -> FieldType
FTList :: FieldType -> FieldType

-- | 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 <a>FieldAttr</a> is extensible through its constructor
--   <a>FieldAttrOther</a>.
data FieldAttr

-- | The <a>Maybe</a> keyword goes after the type. This indicates that the
--   column is nullable, and the generated Haskell code will have a
--   <tt><a>Maybe</a></tt> type for it.
--   
--   Example:
--   
--   <pre>
--   User
--       name Text Maybe
--   </pre>
FieldAttrMaybe :: FieldAttr

-- | This indicates that the column is nullable, but should not have a
--   <a>Maybe</a> type. For this to work out, you need to ensure that the
--   <tt>PersistField</tt> instance for the type in question can support a
--   <a>PersistNull</a> value.
--   
--   <pre>
--   data What = NoWhat | Hello Text
--   
--   instance PersistField What where
--       fromPersistValue PersistNull =
--           pure NoWhat
--       fromPersistValue pv =
--           Hello <a>$</a> fromPersistValue pv
--   
--   instance PersistFieldSql What where
--       sqlType _ = SqlString
--   
--   User
--       what What nullable
--   </pre>
FieldAttrNullable :: FieldAttr

-- | This 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.
--   
--   <pre>
--   User
--       oldName Text MigrationOnly
--       newName Text
--   </pre>
FieldAttrMigrationOnly :: FieldAttr

-- | A <tt>SafeToRemove</tt> attribute is not present on the Haskell
--   datatype, and the backend migrations should attempt to drop the column
--   without triggering any unsafe migration warnings.
--   
--   Useful after you've used <tt>MigrationOnly</tt> to remove a column
--   from the database in phases.
--   
--   <pre>
--   User
--       oldName Text SafeToRemove
--       newName Text
--   </pre>
FieldAttrSafeToRemove :: FieldAttr

-- | This attribute indicates that we should not create a foreign key
--   reference from a column. By default, <tt>persistent</tt> will try and
--   create a foreign key reference for a column if it can determine that
--   the type of the column is a <tt><tt>Key</tt> entity</tt> or an
--   <tt>EntityId</tt> and the <tt>Entity</tt>'s name was present in
--   <tt>mkPersist</tt>.
--   
--   This is useful if you want to use the explicit foreign key syntax.
--   
--   <pre>
--   Post
--       title    Text
--   
--   Comment
--       postId   PostId      noreference
--       Foreign Post fk_comment_post postId
--   </pre>
FieldAttrNoreference :: FieldAttr

-- | This is set to specify precisely the database table the column refers
--   to.
--   
--   <pre>
--   Post
--       title    Text
--   
--   Comment
--       postId   PostId references="post"
--   </pre>
--   
--   You should not need this - <tt>persistent</tt> should be capable of
--   correctly determining the target table's name. If you do need this,
--   please file an issue describing why.
FieldAttrReference :: Text -> FieldAttr

-- | Specify a name for the constraint on the foreign key reference for
--   this table.
--   
--   <pre>
--   Post
--       title    Text
--   
--   Comment
--       postId   PostId constraint="my_cool_constraint_name"
--   </pre>
FieldAttrConstraint :: Text -> FieldAttr

-- | Specify the default value for a column.
--   
--   <pre>
--   User
--       createdAt    UTCTime     default="NOW()"
--   </pre>
--   
--   Note that a <tt>default=</tt> attribute does not mean you can omit the
--   value while inserting.
FieldAttrDefault :: Text -> FieldAttr

-- | Specify a custom SQL type for the column. Generally, you should define
--   a custom datatype with a custom <tt>PersistFieldSql</tt> instance
--   instead of using this.
--   
--   <pre>
--   User
--       uuid     Text    sqltype=<a>UUID</a>
--   </pre>
FieldAttrSqltype :: Text -> FieldAttr

-- | Set a maximum length for a column. Useful for VARCHAR and indexes.
--   
--   <pre>
--   User
--       name     Text    maxlen=200
--   
--       UniqueName name
--   </pre>
FieldAttrMaxlen :: Integer -> FieldAttr

-- | Specify the database name of the column.
--   
--   <pre>
--   User
--       blarghle     Int     sql="b_l_a_r_g_h_l_e"
--   </pre>
--   
--   Useful for performing phased migrations, where one column is renamed
--   to another column over time.
FieldAttrSql :: Text -> FieldAttr

-- | A grab bag of random attributes that were unrecognized by the parser.
FieldAttrOther :: Text -> FieldAttr
type Attr = Text
type ExtraLine = [Text]

-- | The definition for the entity's primary key ID.
data EntityIdDef

-- | The entity has a single key column, and it is a surrogate key - that
--   is, you can't go from <tt>rec -&gt; Key rec</tt>.
EntityIdField :: !FieldDef -> EntityIdDef

-- | The entity has a natural key. This means you can write <tt>rec -&gt;
--   Key rec</tt> because all the key fields are present on the datatype.
--   
--   A natural key can have one or more columns.
EntityIdNaturalKey :: !CompositeDef -> EntityIdDef

-- | An <a>EntityDef</a> represents the information that
--   <tt>persistent</tt> knows about an Entity. It uses this information to
--   generate the Haskell datatype, the SQL migrations, and other relevant
--   conversions.
data EntityDef

-- | The reason why a field is <tt>nullable</tt> is very important. A field
--   that is nullable because of a <tt>Maybe</tt> tag will have its type
--   changed from <tt>A</tt> to <tt>Maybe A</tt>. OTOH, a field that is
--   nullable because of a <tt>nullable</tt> tag will remain with the same
--   type.
data WhyNullable
ByMaybeAttr :: WhyNullable
ByNullableAttr :: WhyNullable
data IsNullable
Nullable :: !WhyNullable -> IsNullable
NotNullable :: IsNullable

-- | A <a>Checkmark</a> 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.
--   
--   <i>NOTE:</i> You need to mark any <tt>Checkmark</tt> fields as
--   <tt>nullable</tt> (see the following example).
--   
--   For example, suppose there's a <tt>Location</tt> entity that
--   represents where a user has lived:
--   
--   <pre>
--   Location
--       user    UserId
--       name    Text
--       current Checkmark nullable
--   
--       UniqueLocation user current
--   </pre>
--   
--   The <tt>UniqueLocation</tt> constraint allows any number of
--   <a>Inactive</a> <tt>Location</tt>s to be <tt>current</tt>. However,
--   there may be at most one <tt>current</tt> <tt>Location</tt> per user
--   (i.e., either zero or one per user).
--   
--   This data type works because of the way that SQL treats
--   <tt>NULL</tt>able fields within uniqueness constraints. The SQL
--   standard says that <tt>NULL</tt> values should be considered
--   different, so we represent <a>Inactive</a> as SQL <tt>NULL</tt>, thus
--   allowing any number of <a>Inactive</a> records. On the other hand, we
--   represent <a>Active</a> as <tt>TRUE</tt>, so the uniqueness constraint
--   will disallow more than one <a>Active</a> record.
--   
--   <i>Note:</i> There may be DBMSs that do not respect the SQL standard's
--   treatment of <tt>NULL</tt> values on uniqueness constraints, please
--   check if this data type works before relying on it.
--   
--   The SQL <tt>BOOLEAN</tt> type is used because it's the smallest data
--   type available. Note that we never use <tt>FALSE</tt>, just
--   <tt>TRUE</tt> and <tt>NULL</tt>. Provides the same behavior <tt>Maybe
--   ()</tt> would if <tt>()</tt> was a valid <tt>PersistField</tt>.
data Checkmark

-- | When used on a uniqueness constraint, there may be at most one
--   <a>Active</a> record.
Active :: Checkmark

-- | When used on a uniqueness constraint, there may be any number of
--   <a>Inactive</a> records.
Inactive :: Checkmark
fieldAttrsContainsNullable :: [FieldAttr] -> IsNullable

-- | Return the <tt>[<a>FieldDef</a>]</tt> for the entity keys.
entitiesPrimary :: EntityDef -> NonEmpty FieldDef
entityPrimary :: EntityDef -> Maybe CompositeDef

-- | Returns a <a>NonEmpty</a> list of <a>FieldDef</a> that correspond with
--   the key columns for an <a>EntityDef</a>.
keyAndEntityFields :: EntityDef -> NonEmpty FieldDef

-- | Returns a <a>NonEmpty</a> list of <a>FieldDef</a> that correspond with
--   the key columns for an <a>EntityDef</a> including those fields that
--   are marked as <tt>MigrationOnly</tt> (and therefore only present in
--   the database) or <tt>SafeToRemove</tt> (and a migration will drop the
--   column if it exists in the database).
--   
--   For fields on the Haskell type use <a>keyAndEntityFieldsDatabase</a>
keyAndEntityFieldsDatabase :: EntityDef -> NonEmpty FieldDef

-- | Parse raw field attributes into structured form. Any unrecognized
--   attributes will be preserved, identically as they are encountered, as
--   <a>FieldAttrOther</a> values.
parseFieldAttrs :: [Text] -> [FieldAttr]
isFieldNotGenerated :: FieldDef -> Bool

-- | Returns <a>True</a> if the <a>FieldDef</a> does not have a
--   <tt>MigrationOnly</tt> or <tt>SafeToRemove</tt> flag from the
--   QuasiQuoter.
isHaskellField :: FieldDef -> Bool

-- | A <a>FieldCascade</a> that does nothing.
noCascade :: FieldCascade

-- | Renders a <a>FieldCascade</a> value such that it can be used in SQL
--   migrations.
renderFieldCascade :: FieldCascade -> Text

-- | Render a <a>CascadeAction</a> to <a>Text</a> such that it can be used
--   in a SQL command.
renderCascadeAction :: CascadeAction -> Text

-- | A <a>Statement</a> is a representation of a database query that has
--   been prepared and stored on the server side.
data Statement
Statement :: IO () -> IO () -> ([PersistValue] -> IO Int64) -> (forall (m :: Type -> Type). MonadIO m => [PersistValue] -> Acquire (ConduitM () [PersistValue] m ())) -> Statement
[stmtFinalize] :: Statement -> IO ()
[stmtReset] :: Statement -> IO ()
[stmtExecute] :: Statement -> [PersistValue] -> IO Int64
[stmtQuery] :: Statement -> forall (m :: Type -> Type). MonadIO m => [PersistValue] -> Acquire (ConduitM () [PersistValue] m ())
data InsertSqlResult
ISRSingle :: Text -> InsertSqlResult
ISRInsertGet :: Text -> Text -> InsertSqlResult
ISRManyKeys :: Text -> [PersistValue] -> InsertSqlResult
type LogFunc = Loc -> LogSource -> LogLevel -> LogStr -> IO ()

-- | Replace the <a>FieldDef</a> <a>FieldAttr</a> with the new list.
setFieldAttrs :: [FieldAttr] -> FieldDef -> FieldDef

-- | Modify the list of field attributes.
overFieldAttrs :: ([FieldAttr] -> [FieldAttr]) -> FieldDef -> FieldDef

-- | Add an attribute to the list of field attributes.
addFieldAttr :: FieldAttr -> FieldDef -> FieldDef

-- | Check if the field definition is nullable
isFieldNullable :: FieldDef -> IsNullable

-- | Check if the field is `Maybe a`
isFieldMaybe :: FieldDef -> Bool

-- | Retrieve the list of <a>UniqueDef</a> from an <a>EntityDef</a>. This
--   does not include a <tt>Primary</tt> key, if one is defined. A future
--   version of <tt>persistent</tt> will include a <tt>Primary</tt> key
--   among the <tt>Unique</tt> constructors for the <tt>Entity</tt>.
getEntityUniquesNoPrimaryKey :: EntityDef -> [UniqueDef]

-- | Retrieve the list of <a>UniqueDef</a> from an <a>EntityDef</a>. 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
--   <a>getEntityUniquesNoPrimaryKey</a>.
getEntityUniques :: EntityDef -> [UniqueDef]

-- | Retrieve the Haskell name of the given entity.
getEntityHaskellName :: EntityDef -> EntityNameHS

-- | Return the database name for the given entity.
getEntityDBName :: EntityDef -> EntityNameDB
getEntityExtra :: EntityDef -> Map Text [[Text]]

setEntityDBName :: EntityNameDB -> EntityDef -> EntityDef
getEntityComments :: EntityDef -> Maybe Text

getEntityForeignDefs :: EntityDef -> [ForeignDef]

-- | Retrieve the list of <a>FieldDef</a> that makes up the fields of the
--   entity.
--   
--   This does not return the fields for an <tt>Id</tt> column or an
--   implicit <tt>id</tt>. It will return the key columns if you used the
--   <tt>Primary</tt> syntax for defining the primary key.
--   
--   This does not return fields that are marked <tt>SafeToRemove</tt> or
--   <tt>MigrationOnly</tt> - so it only returns fields that are
--   represented in the Haskell type. If you need those fields, use
--   <a>getEntityFieldsDatabase</a>.
getEntityFields :: EntityDef -> [FieldDef]

-- | This returns all of the <a>FieldDef</a> defined for the
--   <a>EntityDef</a>, including those fields that are marked as
--   <tt>MigrationOnly</tt> (and therefore only present in the database) or
--   <tt>SafeToRemove</tt> (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
--   <a>getEntityFields</a>.
getEntityFieldsDatabase :: EntityDef -> [FieldDef]

isEntitySum :: EntityDef -> Bool

getEntityId :: EntityDef -> EntityIdDef

getEntityIdField :: EntityDef -> Maybe FieldDef

-- | Set an <a>entityId</a> to be the given <a>FieldDef</a>.
setEntityId :: FieldDef -> EntityDef -> EntityDef

setEntityIdDef :: EntityIdDef -> EntityDef -> EntityDef

getEntityKeyFields :: EntityDef -> NonEmpty FieldDef

-- | Perform a mapping function over all of the entity fields, as
--   determined by <a>getEntityFieldsDatabase</a>.
overEntityFields :: ([FieldDef] -> [FieldDef]) -> EntityDef -> EntityDef

-- | Gets the <tt>Source</tt> of the definition of the entity.
--   
--   Note that as of this writing the span covers the entire file or
--   quasiquote where the item is defined due to parsing limitations. This
--   may be changed in a future release to be more accurate.
getEntitySpan :: EntityDef -> Maybe SourceSpan

-- | Prior to <tt>persistent-2.11.0</tt>, we provided an instance of
--   <a>PersistField</a> for the <a>Natural</a> type. This was in error,
--   because <a>Natural</a> represents an infinite value, and databases
--   don't have reasonable types for this.
--   
--   The instance for <a>Natural</a> used the <a>Int64</a> 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 <a>Word</a> series of types
--   from <a>Data.Word</a>. These have a bounded size, are guaranteed to be
--   non-negative, and are quite efficient for the database to store.
newtype OverflowNatural
OverflowNatural :: Natural -> OverflowNatural
[unOverflowNatural] :: OverflowNatural -> Natural

-- | This class teaches Persistent how to take a custom type and marshal it
--   to and from a <a>PersistValue</a>, allowing it to be stored in a
--   database.
--   
--   <h4><b>Examples</b></h4>
--   
--   <h5>Simple Newtype</h5>
--   
--   You can use <tt>newtype</tt> to add more type safety/readability to a
--   basis type like <a>ByteString</a>. In these cases, just derive
--   <a>PersistField</a> and <tt>PersistFieldSql</tt>:
--   
--   <pre>
--   {-# LANGUAGE GeneralizedNewtypeDeriving #-}
--   
--   newtype HashedPassword = HashedPassword <a>ByteString</a>
--     deriving (Eq, Show, <a>PersistField</a>, PersistFieldSql)
--   </pre>
--   
--   <h5>Smart Constructor Newtype</h5>
--   
--   In this example, we create a <a>PersistField</a> instance for a
--   newtype following the "Smart Constructor" pattern.
--   
--   <pre>
--   {-# LANGUAGE GeneralizedNewtypeDeriving #-}
--   import qualified <a>Data.Text</a> as T
--   import qualified <a>Data.Char</a> as C
--   
--   -- | An American Social Security Number
--   newtype SSN = SSN <a>Text</a>
--    deriving (Eq, Show, PersistFieldSql)
--   
--   mkSSN :: <a>Text</a> -&gt; <a>Either</a> <a>Text</a> SSN
--   mkSSN t = if (T.length t == 9) &amp;&amp; (T.all C.isDigit t)
--    then <a>Right</a> $ SSN t
--    else <a>Left</a> $ "Invalid SSN: " &lt;&gt; t
--   
--   instance <a>PersistField</a> SSN where
--     <a>toPersistValue</a> (SSN t) = <a>PersistText</a> t
--     <a>fromPersistValue</a> (<a>PersistText</a> t) = mkSSN t
--     -- Handle cases where the database does not give us PersistText
--     <a>fromPersistValue</a> x = <a>Left</a> $ "File.hs: When trying to deserialize an SSN: expected PersistText, received: " &lt;&gt; T.pack (show x)
--   </pre>
--   
--   Tips:
--   
--   <ul>
--   <li>This file contain dozens of <a>PersistField</a> instances you can
--   look at for examples.</li>
--   <li>Typically custom <a>PersistField</a> instances will only accept a
--   single <a>PersistValue</a> constructor in
--   <a>fromPersistValue</a>.</li>
--   <li>Internal <a>PersistField</a> instances accept a wide variety of
--   <a>PersistValue</a>s to accomodate e.g. storing booleans as integers,
--   booleans or strings.</li>
--   <li>If you're making a custom instance and using a SQL database,
--   you'll also need <tt>PersistFieldSql</tt> to specify the type of the
--   database column.</li>
--   </ul>
class PersistField a
toPersistValue :: PersistField a => a -> PersistValue
fromPersistValue :: PersistField a => PersistValue -> Either Text a

-- | A type class which is used to witness that a type is safe to insert
--   into the database without providing a primary key.
--   
--   The <tt>TemplateHaskell</tt> function <tt>mkPersist</tt> 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 <tt>Primary</tt> natural key, then this works fine. But
--   if the entity has an <tt>Id</tt> column with no <tt>default=</tt>,
--   then this does a <a>TypeError</a> and forces the user to use
--   <tt>insertKey</tt>.
class SafeToInsert a

-- | This type class is used with the <tt>OverloadedLabels</tt> extension
--   to provide a more convenient means of using the <a>EntityField</a>
--   type. <a>EntityField</a> definitions are prefixed with the type name
--   to avoid ambiguity, but this ambiguity can result in verbose code.
--   
--   If you have a table <tt>User</tt> with a <tt>name Text</tt> field,
--   then the corresponding <a>EntityField</a> is <tt>UserName</tt>. With
--   this, we can write <tt>#name :: <a>EntityField</a> User Text</tt>.
--   
--   What's more fun is that the type is more general: it's actually <tt>
--   #name :: (<a>SymbolToField</a> "name" rec typ) =&gt; EntityField rec
--   typ </tt>
--   
--   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.
class SymbolToField (sym :: Symbol) rec typ | sym rec -> typ
symbolToField :: SymbolToField sym rec typ => EntityField rec typ

-- | Datatype that represents an entity, with both its <a>Key</a> and its
--   Haskell record representation.
--   
--   When using a SQL-based backend (such as SQLite or PostgreSQL), an
--   <a>Entity</a> may take any number of columns depending on how many
--   fields it has. In order to reconstruct your entity on the Haskell
--   side, <tt>persistent</tt> needs all of your entity columns and in the
--   right order. Note that you don't need to worry about this when using
--   <tt>persistent</tt>'s API since everything is handled correctly behind
--   the scenes.
--   
--   However, if you want to issue a raw SQL command that returns an
--   <a>Entity</a>, then you have to be careful with the column order.
--   While you could use <tt>SELECT Entity.* WHERE ...</tt> 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 <tt>persistent</tt>
--   expects (for example, if you add a new field in the middle of you
--   entity definition and then use the migration code --
--   <tt>persistent</tt> 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 <a>rawSql</a> (from the
--   <a>Database.Persist.Sql</a> module) with its /entity selection
--   placeholder/ (a double question mark <tt>??</tt>). Using
--   <tt>rawSql</tt> the query above must be written as <tt>SELECT ?? WHERE
--   ..</tt>. Then <tt>rawSql</tt> will replace <tt>??</tt> with the list
--   of all columns that we need from your entity in the right order. If
--   your query returns two entities (i.e. <tt>(Entity backend a, Entity
--   backend b)</tt>), then you must you use <tt>SELECT ??, ?? WHERE
--   ...</tt>, and so on.
data Entity record
Entity :: Key record -> record -> Entity record
[entityKey] :: Entity record -> Key record
[entityVal] :: Entity record -> record

-- | Value to filter with. Highly dependant on the type of filter used.
data FilterValue typ
[FilterValue] :: forall typ. typ -> FilterValue typ
[FilterValues] :: forall typ. [typ] -> FilterValue typ
[UnsafeValue] :: forall a typ. PersistField a => a -> FilterValue typ

-- | Persistent allows multiple different backends (databases).
type family PersistEntityBackend record

-- | An <a>EntityField</a> is parameterised by the Haskell record it
--   belongs to and the additional type of that field.
--   
--   As of <tt>persistent-2.11.0.0</tt>, it's possible to use the
--   <tt>OverloadedLabels</tt> language extension to refer to
--   <a>EntityField</a> values polymorphically. See the documentation on
--   <a>SymbolToField</a> for more information.
data family EntityField record :: Type -> Type

-- | Construct an <tt><a>Entity</a> record</tt> by providing a value for
--   each of the record's fields.
--   
--   These constructions are equivalent:
--   
--   <pre>
--   entityMattConstructor, entityMattTabulate :: Entity User
--   entityMattConstructor =
--       Entity
--           { entityKey = toSqlKey 123
--           , entityVal =
--               User
--                   { userName = <a>Matt</a>
--                   , userAge = 33
--                   }
--           }
--   
--   entityMattTabulate =
--       tabulateEntity $ \case
--           UserId -&gt;
--               toSqlKey 123
--           UserName -&gt;
--               <a>Matt</a>
--           UserAge -&gt;
--               33
--   </pre>
--   
--   This is a specialization of <a>tabulateEntityA</a>, which allows you
--   to construct an <a>Entity</a> by providing an <a>Applicative</a>
--   action for each field instead of a regular function.
tabulateEntity :: PersistEntity record => (forall a. () => EntityField record a -> a) -> Entity record

-- | Get list of values corresponding to given entity.
entityValues :: PersistEntity record => Entity record -> [PersistValue]

-- | Predefined <tt>toJSON</tt>. The resulting JSON looks like <tt>{"key":
--   1, "value": {"name": ...}}</tt>.
--   
--   The typical usage is:
--   
--   <pre>
--   instance ToJSON (Entity User) where
--       toJSON = keyValueEntityToJSON
--   </pre>
keyValueEntityToJSON :: (PersistEntity record, ToJSON record) => Entity record -> Value

-- | Predefined <tt>parseJSON</tt>. The input JSON looks like <tt>{"key":
--   1, "value": {"name": ...}}</tt>.
--   
--   The typical usage is:
--   
--   <pre>
--   instance FromJSON (Entity User) where
--       parseJSON = keyValueEntityFromJSON
--   </pre>
keyValueEntityFromJSON :: (PersistEntity record, FromJSON record) => Value -> Parser (Entity record)

-- | Predefined <tt>toJSON</tt>. The resulting JSON looks like <tt>{"id":
--   1, "name": ...}</tt>.
--   
--   The typical usage is:
--   
--   <pre>
--   instance ToJSON (Entity User) where
--       toJSON = entityIdToJSON
--   </pre>
entityIdToJSON :: (PersistEntity record, ToJSON record) => Entity record -> Value

-- | Predefined <tt>parseJSON</tt>. The input JSON looks like <tt>{"id": 1,
--   "name": ...}</tt>.
--   
--   The typical usage is:
--   
--   <pre>
--   instance FromJSON (Entity User) where
--       parseJSON = entityIdFromJSON
--   </pre>
entityIdFromJSON :: (PersistEntity record, FromJSON record) => Value -> Parser (Entity record)

-- | Convenience function for getting a free <a>PersistField</a> instance
--   from a type with JSON instances.
--   
--   Example usage in combination with <a>fromPersistValueJSON</a>:
--   
--   <pre>
--   instance PersistField MyData where
--     fromPersistValue = fromPersistValueJSON
--     toPersistValue = toPersistValueJSON
--   </pre>
toPersistValueJSON :: ToJSON a => a -> PersistValue

-- | Convenience function for getting a free <a>PersistField</a> 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 <a>toPersistValueJSON</a>:
--   
--   <pre>
--   instance PersistField MyData where
--     fromPersistValue = fromPersistValueJSON
--     toPersistValue = toPersistValueJSON
--   </pre>
fromPersistValueJSON :: FromJSON a => PersistValue -> Either Text a
class PersistCore backend where {
    data BackendKey backend;
}
data family BackendKey backend

-- | <a>ToBackendKey</a> converts a <a>PersistEntity</a> <a>Key</a> into a
--   <a>BackendKey</a> This can be used by each backend to convert between
--   a <a>Key</a> and a plain Haskell type. For Sql, that is done with
--   <tt>toSqlKey</tt> and <tt>fromSqlKey</tt>.
--   
--   By default, a <a>PersistEntity</a> uses the default <a>BackendKey</a>
--   for its Key and is an instance of ToBackendKey
--   
--   A <a>Key</a> that instead uses a custom type will not be an instance
--   of <a>ToBackendKey</a>.
class (PersistEntity record, PersistEntityBackend record ~ backend, PersistCore backend) => ToBackendKey backend record
toBackendKey :: ToBackendKey backend record => Key record -> BackendKey backend
fromBackendKey :: ToBackendKey backend record => BackendKey backend -> Key record

-- | A convenient alias for common type signatures
type PersistRecordBackend record backend = (PersistEntity record, PersistEntityBackend record ~ BaseBackend backend)

-- | This class witnesses that two backend are compatible, and that you can
--   convert from the <tt>sub</tt> backend into the <tt>sup</tt> backend.
--   This is similar to the <a>HasPersistBackend</a> and
--   <a>IsPersistBackend</a> classes, but where you don't want to fix the
--   type associated with the <a>PersistEntityBackend</a> of a record.
--   
--   Generally speaking, where you might have:
--   
--   <pre>
--   foo ::
--     ( <a>PersistEntity</a> record
--     , <a>PersistEntityBackend</a> record ~ <a>BaseBackend</a> backend
--     , <tt>IsSqlBackend</tt> backend
--     )
--   </pre>
--   
--   this can be replaced with:
--   
--   <pre>
--   foo ::
--     ( <a>PersistEntity</a> record,
--     , <a>PersistEntityBackend</a> record ~ backend
--     , <a>BackendCompatible</a> <tt>SqlBackend</tt> backend
--     )
--   </pre>
--   
--   This works for <tt>SqlReadBackend</tt> because of the <tt>instance
--   <a>BackendCompatible</a> <tt>SqlBackend</tt>
--   <tt>SqlReadBackend</tt></tt>, without needing to go through the
--   <a>BaseBackend</a> type family.
--   
--   Likewise, functions that are currently hardcoded to use
--   <tt>SqlBackend</tt> can be generalized:
--   
--   <pre>
--   -- before:
--   asdf :: <a>ReaderT</a> <tt>SqlBackend</tt> m ()
--   asdf = pure ()
--   
--   -- after:
--   asdf' :: <a>BackendCompatible</a> SqlBackend backend =&gt; ReaderT backend m ()
--   asdf' = <a>withCompatibleBackend</a> asdf
--   </pre>
class BackendCompatible sup sub
projectBackend :: BackendCompatible sup sub => sub -> sup

-- | Class which witnesses that <tt>backend</tt> is essentially the same as
--   <tt>BaseBackend backend</tt>. That is, they're isomorphic and
--   <tt>backend</tt> is just some wrapper over <tt>BaseBackend
--   backend</tt>.
class HasPersistBackend backend => IsPersistBackend backend

-- | Class which allows the plucking of a <tt>BaseBackend backend</tt> from
--   some larger type. For example, <tt> instance HasPersistBackend
--   (SqlReadBackend, Int) where type BaseBackend (SqlReadBackend, Int) =
--   SqlBackend persistBackend = unSqlReadBackend . fst </tt>
class HasPersistBackend backend where {
    type BaseBackend backend;
}
persistBackend :: HasPersistBackend backend => backend -> BaseBackend backend
type family BaseBackend backend

-- | Run a query against a larger backend by plucking out <tt>BaseBackend
--   backend</tt>
--   
--   This is a helper for reusing existing queries when expanding the
--   backend type.
withBaseBackend :: forall backend (m :: Type -> Type) a. HasPersistBackend backend => ReaderT (BaseBackend backend) m a -> ReaderT backend m a

-- | Run a query against a compatible backend, by projecting the backend
--   
--   This is a helper for using queries which run against a specific
--   backend type that your backend is compatible with.
withCompatibleBackend :: forall sup sub (m :: Type -> Type) a. BackendCompatible sup sub => ReaderT sup m a -> ReaderT sub m a
liftPersist :: (MonadIO m, MonadReader backend m) => ReaderT backend IO b -> m b

-- | Same as <a>get</a>, but for a non-null (not Maybe) foreign key. Unsafe
--   unless your database is enforcing that the foreign key is valid.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>,
--   
--   <pre>
--   getJustSpj :: MonadIO m =&gt; ReaderT SqlBackend m User
--   getJustSpj = getJust spjId
--   </pre>
--   
--   <pre>
--   spj &lt;- getJust spjId
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will get this
--   record:
--   
--   <pre>
--   +----+------+-----+
--   | id | name | age |
--   +----+------+-----+
--   |  1 | SPJ  |  40 |
--   +----+------+-----+
--   </pre>
--   
--   <pre>
--   getJustUnknown :: MonadIO m =&gt; ReaderT SqlBackend m User
--   getJustUnknown = getJust unknownId
--   </pre>
--   
--   mrx &lt;- getJustUnknown
--   
--   This just throws an error.
getJust :: forall record backend (m :: Type -> Type). (PersistStoreRead backend, PersistRecordBackend record backend, MonadIO m) => Key record -> ReaderT backend m record

-- | Same as <a>getJust</a>, but returns an <a>Entity</a> instead of just
--   the record.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>,
--   
--   <pre>
--   getJustEntitySpj :: MonadIO m =&gt; ReaderT SqlBackend m (Entity User)
--   getJustEntitySpj = getJustEntity spjId
--   </pre>
--   
--   <pre>
--   spjEnt &lt;- getJustEntitySpj
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will get this
--   entity:
--   
--   <pre>
--   +----+------+-----+
--   | id | name | age |
--   +----+------+-----+
--   |  1 | SPJ  |  40 |
--   +----+------+-----+
--   </pre>
getJustEntity :: forall record backend (m :: Type -> Type). (PersistEntityBackend record ~ BaseBackend backend, MonadIO m, PersistEntity record, PersistStoreRead backend) => Key record -> ReaderT backend m (Entity record)

-- | Curry this to make a convenience function that loads an associated
--   model.
--   
--   <pre>
--   foreign = belongsTo foreignId
--   </pre>
belongsTo :: forall ent1 ent2 backend (m :: Type -> Type). (PersistStoreRead backend, PersistEntity ent1, PersistRecordBackend ent2 backend, MonadIO m) => (ent1 -> Maybe (Key ent2)) -> ent1 -> ReaderT backend m (Maybe ent2)

-- | Same as <a>belongsTo</a>, but uses <tt>getJust</tt> and therefore is
--   similarly unsafe.
belongsToJust :: forall ent1 ent2 backend (m :: Type -> Type). (PersistStoreRead backend, PersistEntity ent1, PersistRecordBackend ent2 backend, MonadIO m) => (ent1 -> Key ent2) -> ent1 -> ReaderT backend m ent2

-- | Like <tt>insert</tt>, but returns the complete <tt>Entity</tt>.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>,
--   
--   <pre>
--   insertHaskellEntity :: MonadIO m =&gt; ReaderT SqlBackend m (Entity User)
--   insertHaskellEntity = insertEntity $ User "Haskell" 81
--   </pre>
--   
--   <pre>
--   haskellEnt &lt;- insertHaskellEntity
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will produce this:
--   
--   <pre>
--   +----+---------+-----+
--   | id |  name   | age |
--   +----+---------+-----+
--   |  1 | SPJ     |  40 |
--   +----+---------+-----+
--   |  2 | Simon   |  41 |
--   +----+---------+-----+
--   |  3 | Haskell |  81 |
--   +----+---------+-----+
--   </pre>
insertEntity :: forall e backend (m :: Type -> Type). (PersistStoreWrite backend, PersistRecordBackend e backend, SafeToInsert e, MonadIO m, HasCallStack) => e -> ReaderT backend m (Entity e)

-- | Like <tt>get</tt>, but returns the complete <tt>Entity</tt>.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>,
--   
--   <pre>
--   getSpjEntity :: MonadIO m =&gt; ReaderT SqlBackend m (Maybe (Entity User))
--   getSpjEntity = getEntity spjId
--   </pre>
--   
--   <pre>
--   mSpjEnt &lt;- getSpjEntity
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will get this
--   entity:
--   
--   <pre>
--   +----+------+-----+
--   | id | name | age |
--   +----+------+-----+
--   |  1 | SPJ  |  40 |
--   +----+------+-----+
--   </pre>
getEntity :: forall e backend (m :: Type -> Type). (PersistStoreRead backend, PersistRecordBackend e backend, MonadIO m) => Key e -> ReaderT backend m (Maybe (Entity e))

-- | Like <a>insertEntity</a> but just returns the record instead of
--   <a>Entity</a>.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>,
--   
--   <pre>
--   insertDaveRecord :: MonadIO m =&gt; ReaderT SqlBackend m User
--   insertDaveRecord = insertRecord $ User "Dave" 50
--   </pre>
--   
--   <pre>
--   dave &lt;- insertDaveRecord
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will produce this:
--   
--   <pre>
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |40   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   |3    |Dave  |50   |
--   +-----+------+-----+
--   </pre>
insertRecord :: forall record backend (m :: Type -> Type). (PersistEntityBackend record ~ BaseBackend backend, PersistEntity record, MonadIO m, PersistStoreWrite backend, SafeToInsert record, HasCallStack) => record -> ReaderT backend m record

-- | A <a>SqlBackend</a> represents a handle or connection to a database.
--   It contains functions and values that allow databases to have more
--   optimized implementations, as well as references that benefit
--   performance and sharing.
--   
--   Instead of using the <a>SqlBackend</a> constructor directly, use the
--   <a>mkSqlBackend</a> function.
--   
--   A <a>SqlBackend</a> is *not* thread-safe. You should not assume that a
--   <a>SqlBackend</a> can be shared among threads and run concurrent
--   queries. This *will* result in problems. Instead, you should create a
--   <tt><tt>Pool</tt> <a>SqlBackend</a></tt>, known as a
--   <tt>ConnectionPool</tt>, and pass that around in multi-threaded
--   applications.
--   
--   To run actions in the <tt>persistent</tt> library, you should use the
--   <tt>runSqlConn</tt> function. If you're using a multithreaded
--   application, use the <tt>runSqlPool</tt> function.
data SqlBackend

-- | 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 <tt>TypeError</tt> instances for records that
--   have 0 unique keys.
class PersistEntity record => AtLeastOneUniqueKey record
requireUniquesP :: AtLeastOneUniqueKey record => record -> NonEmpty (Unique record)

-- | This is an error message. It is used when an entity has multiple
--   unique keys, and the function expects a single unique key.
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 writing instances of
--   <a>OnlyOneUniqueKey</a> for an entity that has no unique keys.
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 class is used to ensure that <a>upsert</a> is only called on
--   records that have a single <a>Unique</a> key. The quasiquoter
--   automatically generates working instances for appropriate records, and
--   generates <tt>TypeError</tt> instances for records that have 0 or
--   multiple unique keys.
class PersistEntity record => OnlyOneUniqueKey record
onlyUniqueP :: OnlyOneUniqueKey record => record -> Unique record

-- | Queries against <a>Unique</a> keys (other than the id <a>Key</a>).
--   
--   Please read the general Persistent documentation to learn how to
--   create <a>Unique</a> keys.
--   
--   Using this with an Entity without a Unique key leads to undefined
--   behavior. A few of these functions require a <i>single</i>
--   <a>Unique</a>, so using an Entity with multiple <a>Unique</a>s is also
--   undefined. In these cases persistent's goal is to throw an exception
--   as soon as possible, but persistent is still transitioning to that.
--   
--   SQL backends automatically create uniqueness constraints, but for
--   MongoDB you must manually place a unique index on a field to have a
--   uniqueness constraint.
class PersistStoreRead backend => PersistUniqueRead backend

-- | Get a record by unique key, if available. Returns also the identifier.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>:
--   
--   <pre>
--   getBySpjName :: MonadIO m  =&gt; ReaderT SqlBackend m (Maybe (Entity User))
--   getBySpjName = getBy $ UniqueUserName "SPJ"
--   </pre>
--   
--   <pre>
--   mSpjEnt &lt;- getBySpjName
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will get this
--   entity:
--   
--   <pre>
--   +----+------+-----+
--   | id | name | age |
--   +----+------+-----+
--   |  1 | SPJ  |  40 |
--   +----+------+-----+
--   </pre>
getBy :: forall record (m :: Type -> Type). (PersistUniqueRead backend, MonadIO m, PersistRecordBackend record backend) => Unique record -> ReaderT backend m (Maybe (Entity record))

-- | Returns True if a record with this unique key exists, otherwise False.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>:
--   
--   <pre>
--   existsBySpjName :: MonadIO m  =&gt; ReaderT SqlBackend m Bool
--   existsBySpjName = existsBy $ UniqueUserName "SPJ"
--   </pre>
--   
--   <pre>
--   spjEntExists &lt;- existsBySpjName
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will return the
--   value True.
existsBy :: forall record (m :: Type -> Type). (PersistUniqueRead backend, MonadIO m, PersistRecordBackend record backend) => Unique record -> ReaderT backend m Bool

-- | Given a proxy for a <a>PersistEntity</a> record, this returns the sole
--   <a>UniqueDef</a> for that entity.
onlyOneUniqueDef :: (OnlyOneUniqueKey record, Monad proxy) => proxy record -> UniqueDef

-- | Like <a>insertEntity</a>, but returns <a>Nothing</a> when the record
--   couldn't be inserted because of a uniqueness constraint.
--   
--   <h3><b>Example usage</b></h3>
--   
--   We use <a>schema-2</a> and <a>dataset-1</a> here.
--   
--   <pre>
--   insertUniqueSpjEntity :: MonadIO m =&gt; ReaderT SqlBackend m (Maybe (Entity User))
--   insertUniqueSpjEntity = insertUniqueEntity $ User "SPJ" 50
--   </pre>
--   
--   <pre>
--   mSpjEnt &lt;- insertUniqueSpjEntity
--   </pre>
--   
--   The above query results <a>Nothing</a> as SPJ already exists.
--   
--   <pre>
--   insertUniqueAlexaEntity :: MonadIO m =&gt; ReaderT SqlBackend m (Maybe (Entity User))
--   insertUniqueAlexaEntity = insertUniqueEntity $ User "Alexa" 3
--   </pre>
--   
--   <pre>
--   mAlexaEnt &lt;- insertUniqueSpjEntity
--   </pre>
--   
--   Because there's no such unique keywords of the given record, the above
--   query when applied on <a>dataset-1</a>, will produce this:
--   
--   <pre>
--   +----+-------+-----+
--   | id | name  | age |
--   +----+-------+-----+
--   |  1 | SPJ   |  40 |
--   +----+-------+-----+
--   |  2 | Simon |  41 |
--   +----+-------+-----+
--   |  3 | Alexa |   3 |
--   +----+-------+-----+
--   </pre>
insertUniqueEntity :: forall record backend (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend, PersistUniqueWrite backend, SafeToInsert record) => record -> ReaderT backend m (Maybe (Entity record))

-- | Return the single unique key for a record.
--   
--   <h3><b>Example usage</b></h3>
--   
--   We use shcema-1 and <a>dataset-1</a> here.
--   
--   <pre>
--   onlySimonConst :: MonadIO m =&gt; ReaderT SqlBackend m (Unique User)
--   onlySimonConst = onlyUnique $ User "Simon" 999
--   </pre>
--   
--   <pre>
--   mSimonConst &lt;- onlySimonConst
--   </pre>
--   
--   <tt>mSimonConst</tt> would be Simon's uniqueness constraint. Note that
--   <tt>onlyUnique</tt> doesn't work if there're more than two
--   constraints. It will fail with a type error instead.
onlyUnique :: forall record backend (m :: Type -> Type). (MonadIO m, PersistUniqueWrite backend, PersistRecordBackend record backend, OnlyOneUniqueKey record) => record -> ReaderT backend m (Unique record)

-- | A modification of <a>getBy</a>, which takes the <a>PersistEntity</a>
--   itself instead of a <a>Unique</a> record. Returns a record matching
--   <i>one</i> of the unique keys. This function makes the most sense on
--   entities with a single <a>Unique</a> constructor.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>,
--   
--   getBySpjValue :: MonadIO m =&gt; ReaderT SqlBackend m (Maybe (Entity
--   User)) getBySpjValue = getByValue $ User <a>SPJ</a> 999
--   
--   <pre>
--   mSpjEnt &lt;- getBySpjValue
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will get this
--   record:
--   
--   <pre>
--   +----+------+-----+
--   | id | name | age |
--   +----+------+-----+
--   |  1 | SPJ  |  40 |
--   +----+------+-----+
--   </pre>
getByValue :: forall record (m :: Type -> Type) backend. (MonadIO m, PersistUniqueRead backend, PersistRecordBackend record backend, AtLeastOneUniqueKey record) => record -> ReaderT backend m (Maybe (Entity record))

-- | Attempt to replace the record of the given key with the given new
--   record. First query the unique fields to make sure the replacement
--   maintains uniqueness constraints.
--   
--   Return <a>Nothing</a> if the replacement was made. If uniqueness is
--   violated, return a <a>Just</a> with the <a>Unique</a> violation
replaceUnique :: forall record backend (m :: Type -> Type). (MonadIO m, Eq (Unique record), PersistRecordBackend record backend, PersistUniqueWrite backend) => Key record -> record -> ReaderT backend m (Maybe (Unique record))

-- | Check whether there are any conflicts for unique keys with this entity
--   and existing entities in the database.
--   
--   Returns <a>Nothing</a> if the entity would be unique, and could thus
--   safely be inserted. on a conflict returns the conflicting key
--   
--   <h3><b>Example usage</b></h3>
--   
--   We use <a>schema-1</a> and <a>dataset-1</a> here.
--   
--   This would be <a>Nothing</a>:
--   
--   <pre>
--   mAlanConst &lt;- checkUnique $ User "Alan" 70
--   </pre>
--   
--   While this would be <a>Just</a> because SPJ already exists:
--   
--   <pre>
--   mSpjConst &lt;- checkUnique $ User "SPJ" 60
--   </pre>
checkUnique :: forall record backend (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend, PersistUniqueRead backend) => record -> ReaderT backend m (Maybe (Unique record))

-- | Check whether there are any conflicts for unique keys with this entity
--   and existing entities in the database.
--   
--   Returns <a>Nothing</a> if the entity would stay unique, and could thus
--   safely be updated. on a conflict returns the conflicting key
--   
--   This is similar to <a>checkUnique</a>, except it's useful for updating
--   - when the particular entity already exists, it would normally
--   conflict with itself. This variant ignores those conflicts
--   
--   <h3><b>Example usage</b></h3>
--   
--   We use <a>schema-1</a> and <a>dataset-1</a> here.
--   
--   This would be <a>Nothing</a>:
--   
--   <pre>
--   mAlanConst &lt;- checkUnique $ User "Alan" 70
--   </pre>
--   
--   While this would be <a>Just</a> because SPJ already exists:
--   
--   <pre>
--   mSpjConst &lt;- checkUnique $ User "SPJ" 60
--   </pre>
checkUniqueUpdateable :: forall record backend (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend, PersistUniqueRead backend) => Entity record -> ReaderT backend m (Maybe (Unique record))

-- | Backends supporting conditional write operations
class (PersistQueryRead backend, PersistStoreWrite backend) => PersistQueryWrite backend

-- | Update individual fields on any record matching the given criterion.
updateWhere :: forall (m :: Type -> Type) record. (PersistQueryWrite backend, MonadIO m, PersistRecordBackend record backend) => [Filter record] -> [Update record] -> ReaderT backend m ()

-- | Delete all records matching the given criterion.
deleteWhere :: forall (m :: Type -> Type) record. (PersistQueryWrite backend, MonadIO m, PersistRecordBackend record backend) => [Filter record] -> ReaderT backend m ()

-- | Backends supporting conditional read operations.
class (PersistCore backend, PersistStoreRead backend) => PersistQueryRead backend

-- | Get all records matching the given criterion in the specified order.
--   Returns also the identifiers.
--   
--   NOTE: This function returns an <a>Acquire</a> and a <a>ConduitM</a>,
--   which implies that it streams from the database. It does not. Please
--   use <a>selectList</a> to simplify the code. If you want streaming
--   behavior, consider <tt>persistent-pagination</tt> which efficiently
--   chunks a query into ranges, or investigate a backend-specific
--   streaming solution.
selectSourceRes :: forall record (m1 :: Type -> Type) (m2 :: Type -> Type). (PersistQueryRead backend, PersistRecordBackend record backend, MonadIO m1, MonadIO m2) => [Filter record] -> [SelectOpt record] -> ReaderT backend m1 (Acquire (ConduitM () (Entity record) m2 ()))

-- | Get just the first record for the criterion.
selectFirst :: forall (m :: Type -> Type) record. (PersistQueryRead backend, MonadIO m, PersistRecordBackend record backend) => [Filter record] -> [SelectOpt record] -> ReaderT backend m (Maybe (Entity record))

-- | Get the <a>Key</a>s of all records matching the given criterion.
selectKeysRes :: forall (m1 :: Type -> Type) (m2 :: Type -> Type) record. (PersistQueryRead backend, MonadIO m1, MonadIO m2, PersistRecordBackend record backend) => [Filter record] -> [SelectOpt record] -> ReaderT backend m1 (Acquire (ConduitM () (Key record) m2 ()))

-- | Get the <a>Key</a>s of all records matching the given criterion.
--   
--   For an example, see <a>selectList</a>.
selectKeys :: forall record backend (m :: Type -> Type). (PersistQueryRead backend, MonadResource m, PersistRecordBackend record backend, MonadReader backend m) => [Filter record] -> [SelectOpt record] -> ConduitM () (Key record) m ()

-- | 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.
type PersistStore a = PersistStoreWrite a

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

-- | A backend which is a wrapper around <tt>SqlBackend</tt>.
type IsSqlBackend backend = (IsPersistBackend backend, BaseBackend backend ~ SqlBackend)

-- | Like <tt>SqlPersistT</tt> but compatible with any SQL backend which
--   can handle read and write queries.
type SqlWriteT (m :: Type -> Type) a = forall backend. SqlBackendCanWrite backend => ReaderT backend m a

-- | Like <tt>SqlPersistT</tt> but compatible with any SQL backend which
--   can handle read queries.
type SqlReadT (m :: Type -> Type) a = forall backend. SqlBackendCanRead backend => ReaderT backend m a

-- | A constraint synonym which witnesses that a backend is SQL and can run
--   read and write queries.
type SqlBackendCanWrite backend = (SqlBackendCanRead backend, PersistQueryWrite backend, PersistStoreWrite backend, PersistUniqueWrite backend)

-- | A constraint synonym which witnesses that a backend is SQL and can run
--   read queries.
type SqlBackendCanRead backend = (BackendCompatible SqlBackend backend, PersistQueryRead backend, PersistStoreRead backend, PersistUniqueRead backend)

-- | An SQL backend which can handle read or write queries
--   
--   The constructor was exposed in 2.10.0
newtype SqlWriteBackend
SqlWriteBackend :: SqlBackend -> SqlWriteBackend
[unSqlWriteBackend] :: SqlWriteBackend -> SqlBackend

-- | An SQL backend which can only handle read queries
--   
--   The constructor was exposed in 2.10.0.
newtype SqlReadBackend
SqlReadBackend :: SqlBackend -> SqlReadBackend
[unSqlReadBackend] :: SqlReadBackend -> SqlBackend

-- | Useful for running a write query against an untagged backend with
--   unknown capabilities.
writeToUnknown :: forall (m :: Type -> Type) a. Monad m => ReaderT SqlWriteBackend m a -> ReaderT SqlBackend m a

-- | Useful for running a read query against a backend with read and write
--   capabilities.
readToWrite :: forall (m :: Type -> Type) a. Monad m => ReaderT SqlReadBackend m a -> ReaderT SqlWriteBackend m a

-- | Useful for running a read query against a backend with unknown
--   capabilities.
readToUnknown :: forall (m :: Type -> Type) a. Monad m => ReaderT SqlReadBackend m a -> ReaderT SqlBackend m a

-- | Values to configure a pool of database connections. See
--   <a>Data.Pool</a> for details.
data ConnectionPoolConfig
ConnectionPoolConfig :: Int -> NominalDiffTime -> Int -> ConnectionPoolConfig

-- | How many stripes to divide the pool into. See <a>Data.Pool</a> for
--   details. Default: 1.
[connectionPoolConfigStripes] :: ConnectionPoolConfig -> Int

-- | How long connections can remain idle before being disposed of, in
--   seconds. Default: 600
[connectionPoolConfigIdleTimeout] :: ConnectionPoolConfig -> NominalDiffTime

-- | How many connections should be held in the connection pool. Default:
--   10
[connectionPoolConfigSize] :: ConnectionPoolConfig -> Int
type ConnectionPool = Pool SqlBackend
type SqlPersistM = SqlPersistT NoLoggingT ResourceT IO
type SqlPersistT = ReaderT SqlBackend
data PersistentSqlException
StatementAlreadyFinalized :: Text -> PersistentSqlException
Couldn'tGetSQLConnection :: PersistentSqlException

-- | This value specifies how a field references another table.
data ColumnReference
ColumnReference :: !EntityNameDB -> !ConstraintNameDB -> !FieldCascade -> ColumnReference

-- | The table name that the
[crTableName] :: ColumnReference -> !EntityNameDB

-- | The name of the foreign key constraint.
[crConstraintName] :: ColumnReference -> !ConstraintNameDB

-- | Whether or not updates/deletions to the referenced table cascade to
--   this table.
[crFieldCascade] :: ColumnReference -> !FieldCascade

-- | Initializes a ConnectionPoolConfig with default values. See the
--   documentation of <a>ConnectionPoolConfig</a> for each field's default
--   value.
defaultConnectionPoolConfig :: ConnectionPoolConfig

-- | Record of functions to override the default behavior in
--   <a>mkColumns</a>. It is recommended you initialize this with
--   <a>emptyBackendSpecificOverrides</a> and override the default values,
--   so that as new fields are added, your code still compiles.
--   
--   For added safety, use the <tt>getBackendSpecific*</tt> and
--   <tt>setBackendSpecific*</tt> functions, as a breaking change to the
--   record field labels won't be reflected in a major version bump of the
--   library.
data BackendSpecificOverrides

-- | If the override is defined, then this returns a function that accepts
--   an entity name and field name and provides the <a>ConstraintNameDB</a>
--   for the foreign key constraint.
--   
--   An abstract accessor for the <a>BackendSpecificOverrides</a>
getBackendSpecificForeignKeyName :: BackendSpecificOverrides -> Maybe (EntityNameDB -> FieldNameDB -> ConstraintNameDB)

-- | Set the backend's foreign key generation function to this value.
setBackendSpecificForeignKeyName :: (EntityNameDB -> FieldNameDB -> ConstraintNameDB) -> BackendSpecificOverrides -> BackendSpecificOverrides

-- | Creates an empty <a>BackendSpecificOverrides</a> (i.e. use the default
--   behavior; no overrides)
emptyBackendSpecificOverrides :: BackendSpecificOverrides
defaultAttribute :: [FieldAttr] -> Maybe Text

-- | Create the list of columns for the given entity.
mkColumns :: [EntityDef] -> EntityDef -> BackendSpecificOverrides -> ([Column], [UniqueDef], [ForeignDef])

-- | A more general way to convert instances of <a>ToJSON</a> type class to
--   strict text <a>Text</a>.
toJsonText :: ToJSON j => j -> Text

-- | Tells Persistent what database column type should be used to store a
--   Haskell type.
--   
--   <h4><b>Examples</b></h4>
--   
--   <h5>Simple Boolean Alternative</h5>
--   
--   <pre>
--   data Switch = On | Off
--     deriving (Show, Eq)
--   
--   instance <a>PersistField</a> Switch where
--     <a>toPersistValue</a> s = case s of
--       On -&gt; <a>PersistBool</a> True
--       Off -&gt; <a>PersistBool</a> False
--     <a>fromPersistValue</a> (<a>PersistBool</a> b) = if b then <a>Right</a> On else <a>Right</a> Off
--     <a>fromPersistValue</a> x = Left $ "File.hs: When trying to deserialize a Switch: expected PersistBool, received: " &lt;&gt; T.pack (show x)
--   
--   instance <a>PersistFieldSql</a> Switch where
--     <a>sqlType</a> _ = <a>SqlBool</a>
--   </pre>
--   
--   <h5>Non-Standard Database Types</h5>
--   
--   If your database supports non-standard types, such as Postgres'
--   <tt>uuid</tt>, you can use <a>SqlOther</a> to use them:
--   
--   <pre>
--   import qualified Data.UUID as UUID
--   instance <a>PersistField</a> UUID where
--     <a>toPersistValue</a> = <tt>PersistLiteralEncoded</tt> . toASCIIBytes
--     <a>fromPersistValue</a> (<tt>PersistLiteralEncoded</tt> uuid) =
--       case fromASCIIBytes uuid of
--         <a>Nothing</a> -&gt; <a>Left</a> $ "Model/CustomTypes.hs: Failed to deserialize a UUID; received: " &lt;&gt; T.pack (show uuid)
--         <a>Just</a> uuid' -&gt; <a>Right</a> uuid'
--     <a>fromPersistValue</a> x = Left $ "File.hs: When trying to deserialize a UUID: expected PersistLiteralEncoded, received: "-- &gt;  &lt;&gt; T.pack (show x)
--   
--   instance <a>PersistFieldSql</a> UUID where
--     <a>sqlType</a> _ = <a>SqlOther</a> "uuid"
--   </pre>
--   
--   <h5>User Created Database Types</h5>
--   
--   Similarly, some databases support creating custom types, e.g.
--   Postgres' <a>DOMAIN</a> and <a>ENUM</a> features. You can use
--   <a>SqlOther</a> to specify a custom type:
--   
--   <pre>
--   CREATE DOMAIN ssn AS text
--         CHECK ( value ~ '^[0-9]{9}$');
--   </pre>
--   
--   <pre>
--   instance <tt>PersistFieldSQL</tt> SSN where
--     <a>sqlType</a> _ = <a>SqlOther</a> "ssn"
--   </pre>
--   
--   <pre>
--   CREATE TYPE rainbow_color AS ENUM ('red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet');
--   </pre>
--   
--   <pre>
--   instance <tt>PersistFieldSQL</tt> RainbowColor where
--     <a>sqlType</a> _ = <a>SqlOther</a> "rainbow_color"
--   </pre>
class PersistField a => PersistFieldSql a
sqlType :: PersistFieldSql a => Proxy a -> SqlType

-- | This newtype wrapper is useful when selecting an entity out of the
--   database and you want to provide a prefix to the table being selected.
--   
--   Consider this raw SQL query:
--   
--   <pre>
--   SELECT ??
--   FROM my_long_table_name AS mltn
--   INNER JOIN other_table AS ot
--      ON mltn.some_col = ot.other_col
--   WHERE ...
--   </pre>
--   
--   We don't want to refer to <tt>my_long_table_name</tt> every time, so
--   we create an alias. If we want to select it, we have to tell the raw
--   SQL quasi-quoter that we expect the entity to be prefixed with some
--   other name.
--   
--   We can give the above query a type with this, like:
--   
--   <pre>
--   getStuff :: <a>SqlPersistM</a> [<a>EntityWithPrefix</a> "mltn" MyLongTableName]
--   getStuff = rawSql queryText []
--   </pre>
--   
--   The <a>EntityWithPrefix</a> bit is a boilerplate newtype wrapper, so
--   you can remove it with <a>unPrefix</a>, like this:
--   
--   <pre>
--   getStuff :: <a>SqlPersistM</a> [<a>Entity</a> MyLongTableName]
--   getStuff = <a>unPrefix</a> @"mltn" <a>&lt;$&gt;</a> <tt>rawSql</tt> queryText []
--   </pre>
--   
--   The <tt> symbol is a "type application" and requires the
--   </tt>TypeApplications@ language extension.
newtype EntityWithPrefix (prefix :: Symbol) record
EntityWithPrefix :: Entity record -> EntityWithPrefix (prefix :: Symbol) record
[unEntityWithPrefix] :: EntityWithPrefix (prefix :: Symbol) record -> Entity record

-- | Class for data types that may be retrived from a <tt>rawSql</tt>
--   query.
class RawSql a

-- | Number of columns that this data type needs and the list of
--   substitutions for <tt>SELECT</tt> placeholders <tt>??</tt>.
rawSqlCols :: RawSql a => (Text -> Text) -> a -> (Int, [Text])

-- | A string telling the user why the column count is what it is.
rawSqlColCountReason :: RawSql a => a -> String

-- | Transform a row of the result into the data type.
rawSqlProcessRow :: RawSql a => [PersistValue] -> Either Text a

-- | A helper function to tell GHC what the <a>EntityWithPrefix</a> prefix
--   should be. This allows you to use a type application to specify the
--   prefix, instead of specifying the etype on the result.
--   
--   As an example, here's code that uses this:
--   
--   <pre>
--   myQuery :: <a>SqlPersistM</a> [<a>Entity</a> Person]
--   myQuery = fmap (unPrefix @"p") <a>$</a> rawSql query []
--     where
--       query = "SELECT ?? FROM person AS p"
--   </pre>
unPrefix :: forall (prefix :: Symbol) record. EntityWithPrefix prefix record -> Entity record
rawQuery :: forall (m :: Type -> Type) env. (MonadResource m, MonadReader env m, BackendCompatible SqlBackend env) => Text -> [PersistValue] -> ConduitM () [PersistValue] m ()
rawQueryRes :: forall (m1 :: Type -> Type) (m2 :: Type -> Type) env. (MonadIO m1, MonadIO m2, BackendCompatible SqlBackend env) => Text -> [PersistValue] -> ReaderT env m1 (Acquire (ConduitM () [PersistValue] m2 ()))

-- | Execute a raw SQL statement
rawExecute :: forall (m :: Type -> Type) backend. (MonadIO m, BackendCompatible SqlBackend backend) => Text -> [PersistValue] -> ReaderT backend m ()

-- | Execute a raw SQL statement and return the number of rows it has
--   modified.
rawExecuteCount :: forall (m :: Type -> Type) backend. (MonadIO m, BackendCompatible SqlBackend backend) => Text -> [PersistValue] -> ReaderT backend m Int64
getStmtConn :: SqlBackend -> Text -> IO Statement

-- | Get a connection from the pool, run the given action, and then return
--   the connection to the pool.
--   
--   This function performs the given action in a transaction. If an
--   exception occurs during the action, then the transaction is rolled
--   back.
--   
--   Note: This function previously timed out after 2 seconds, but this
--   behavior was buggy and caused more problems than it solved. Since
--   version 2.1.2, it performs no timeout checks.
runSqlPool :: forall backend m a. (MonadUnliftIO m, BackendCompatible SqlBackend backend) => ReaderT backend m a -> Pool backend -> m a

-- | Like <a>runSqlPool</a>, but supports specifying an isolation level.
runSqlPoolWithIsolation :: forall backend m a. (MonadUnliftIO m, BackendCompatible SqlBackend backend) => ReaderT backend m a -> Pool backend -> IsolationLevel -> m a

-- | Like <a>runSqlPool</a>, but does not surround the action in a
--   transaction. This action might leave your database in a weird state.
runSqlPoolNoTransaction :: forall backend m a. (MonadUnliftIO m, BackendCompatible SqlBackend backend) => ReaderT backend m a -> Pool backend -> Maybe IsolationLevel -> m a

-- | This function is how <a>runSqlPool</a> and
--   <a>runSqlPoolNoTransaction</a> are defined. In addition to the action
--   to be performed and the <a>Pool</a> of conections to use, we give you
--   the opportunity to provide three actions - initialize, afterwards, and
--   onException.
runSqlPoolWithHooks :: forall backend m a before after onException. (MonadUnliftIO m, BackendCompatible SqlBackend backend) => ReaderT backend m a -> Pool backend -> Maybe IsolationLevel -> (backend -> m before) -> (backend -> m after) -> (backend -> SomeException -> m onException) -> m a

-- | This function is how <a>runSqlPoolWithHooks</a> is defined.
--   
--   It's currently the most general function for using a SQL pool.
runSqlPoolWithExtensibleHooks :: forall backend m a. (MonadUnliftIO m, BackendCompatible SqlBackend backend) => ReaderT backend m a -> Pool backend -> Maybe IsolationLevel -> SqlPoolHooks m backend -> m a

-- | Starts a new transaction on the connection. When the acquired
--   connection is released the transaction is committed and the connection
--   returned to the pool.
--   
--   Upon an exception the transaction is rolled back and the connection
--   destroyed.
--   
--   This is equivalent to <a>runSqlConn</a> but does not incur the
--   <a>MonadUnliftIO</a> constraint, meaning it can be used within, for
--   example, a <tt>Conduit</tt> pipeline.
acquireSqlConn :: (MonadReader backend m, BackendCompatible SqlBackend backend) => m (Acquire backend)

-- | Like <a>acquireSqlConn</a>, but lets you specify an explicit isolation
--   level.
acquireSqlConnWithIsolation :: (MonadReader backend m, BackendCompatible SqlBackend backend) => IsolationLevel -> m (Acquire backend)
runSqlConn :: forall backend m a. (MonadUnliftIO m, BackendCompatible SqlBackend backend) => ReaderT backend m a -> backend -> m a

-- | Like <a>runSqlConn</a>, but supports specifying an isolation level.
runSqlConnWithIsolation :: forall backend m a. (MonadUnliftIO m, BackendCompatible SqlBackend backend) => ReaderT backend m a -> backend -> IsolationLevel -> m a
runSqlPersistM :: BackendCompatible SqlBackend backend => ReaderT backend (NoLoggingT (ResourceT IO)) a -> backend -> IO a
runSqlPersistMPool :: BackendCompatible SqlBackend backend => ReaderT backend (NoLoggingT (ResourceT IO)) a -> Pool backend -> IO a
liftSqlPersistMPool :: forall backend m a. (MonadIO m, BackendCompatible SqlBackend backend) => ReaderT backend (NoLoggingT (ResourceT IO)) a -> Pool backend -> m a
withSqlPool :: forall backend m a. (MonadLoggerIO m, MonadUnliftIO m, BackendCompatible SqlBackend backend) => (LogFunc -> IO backend) -> Int -> (Pool backend -> m a) -> m a

-- | Creates a pool of connections to a SQL database which can be used by
--   the <tt>Pool backend -&gt; m a</tt> function. After the function
--   completes, the connections are destroyed.
withSqlPoolWithConfig :: forall backend m a. (MonadLoggerIO m, MonadUnliftIO m, BackendCompatible SqlBackend backend) => (LogFunc -> IO backend) -> ConnectionPoolConfig -> (Pool backend -> m a) -> m a
createSqlPool :: forall backend m. (MonadLoggerIO m, MonadUnliftIO m, BackendCompatible SqlBackend backend) => (LogFunc -> IO backend) -> Int -> m (Pool backend)

-- | Creates a pool of connections to a SQL database.
createSqlPoolWithConfig :: (MonadLoggerIO m, MonadUnliftIO m, BackendCompatible SqlBackend backend) => (LogFunc -> IO backend) -> ConnectionPoolConfig -> m (Pool backend)

-- | Create a connection and run sql queries within it. This function
--   automatically closes the connection on it's completion.
--   
--   <h3><b>Example usage</b></h3>
--   
--   <pre>
--   {-# LANGUAGE GADTs #-}
--   {-# LANGUAGE ScopedTypeVariables #-}
--   {-# LANGUAGE OverloadedStrings #-}
--   {-# LANGUAGE MultiParamTypeClasses #-}
--   {-# LANGUAGE TypeFamilies#-}
--   {-# LANGUAGE TemplateHaskell#-}
--   {-# LANGUAGE QuasiQuotes#-}
--   {-# LANGUAGE GeneralizedNewtypeDeriving #-}
--   
--   import Control.Monad.IO.Class  (liftIO)
--   import Control.Monad.Logger
--   import Conduit
--   import Database.Persist
--   import Database.Sqlite
--   import Database.Persist.Sqlite
--   import Database.Persist.TH
--   
--   share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
--   Person
--     name String
--     age Int Maybe
--     deriving Show
--   |]
--   
--   openConnection :: LogFunc -&gt; IO SqlBackend
--   openConnection logfn = do
--    conn &lt;- open "/home/sibi/test.db"
--    wrapConnection conn logfn
--   
--   main :: IO ()
--   main = do
--     runNoLoggingT $ runResourceT $ withSqlConn openConnection (\backend -&gt;
--                                         flip runSqlConn backend $ do
--                                           runMigration migrateAll
--                                           insert_ $ Person "John doe" $ Just 35
--                                           insert_ $ Person "Divya" $ Just 36
--                                           (pers :: [Entity Person]) &lt;- selectList [] []
--                                           liftIO $ print pers
--                                           return ()
--                                        )
--   </pre>
--   
--   On executing it, you get this output:
--   
--   <pre>
--   Migrating: CREATE TABLE "person"("id" INTEGER PRIMARY KEY,"name" VARCHAR NOT NULL,"age" INTEGER NULL)
--   [Entity {entityKey = PersonKey {unPersonKey = SqlBackendKey {unSqlBackendKey = 1}}, entityVal = Person {personName = "John doe", personAge = Just 35}},Entity {entityKey = PersonKey {unPersonKey = SqlBackendKey {unSqlBackendKey = 2}}, entityVal = Person {personName = "Hema", personAge = Just 36}}]
--   </pre>
withSqlConn :: forall backend m a. (MonadUnliftIO m, MonadLoggerIO m, BackendCompatible SqlBackend backend) => (LogFunc -> IO backend) -> (backend -> m a) -> m a
close' :: BackendCompatible SqlBackend backend => backend -> IO ()
withRawQuery :: forall (m :: Type -> Type) a. MonadIO m => Text -> [PersistValue] -> ConduitM [PersistValue] Void IO a -> ReaderT SqlBackend m a
toSqlKey :: ToBackendKey SqlBackend record => Int64 -> Key record
fromSqlKey :: ToBackendKey SqlBackend record => Key record -> Int64

-- | get the SQL string for the table that a PersistEntity represents
--   Useful for raw SQL queries
--   
--   Your backend may provide a more convenient tableName function which
--   does not operate in a Monad
getTableName :: forall record (m :: Type -> Type) backend. (PersistEntity record, BackendCompatible SqlBackend backend, Monad m) => record -> ReaderT backend m Text

-- | useful for a backend to implement tableName by adding escaping
tableDBName :: PersistEntity record => record -> EntityNameDB

-- | get the SQL string for the field that an EntityField represents Useful
--   for raw SQL queries
--   
--   Your backend may provide a more convenient fieldName function which
--   does not operate in a Monad
getFieldName :: forall record typ (m :: Type -> Type) backend. (PersistEntity record, PersistEntityBackend record ~ SqlBackend, BackendCompatible SqlBackend backend, Monad m) => EntityField record typ -> ReaderT backend m Text

-- | useful for a backend to implement fieldName by adding escaping
fieldDBName :: PersistEntity record => EntityField record typ -> FieldNameDB

-- | Used when determining how to prefix a column name in a <tt>WHERE</tt>
--   clause.
data FilterTablePrefix

-- | Prefix the column with the table name. This is useful if the column
--   name might be ambiguous.
PrefixTableName :: FilterTablePrefix

-- | Prefix the column name with the <tt>EXCLUDED</tt> keyword. This is
--   used with the Postgresql backend when doing <tt>ON CONFLICT DO
--   UPDATE</tt> clauses - see the documentation on <tt>upsertWhere</tt>
--   and <tt>upsertManyWhere</tt>.
PrefixExcluded :: FilterTablePrefix

-- | Render a <tt>[<a>Filter</a> record]</tt> into a <a>Text</a> value
--   suitable for inclusion into a SQL query.
filterClause :: PersistEntity val => Maybe FilterTablePrefix -> SqlBackend -> [Filter val] -> Text

-- | Render a <tt>[<a>Filter</a> record]</tt> into a <a>Text</a> value
--   suitable for inclusion into a SQL query, as well as the
--   <tt>[<a>PersistValue</a>]</tt> to properly fill in the <tt>?</tt>
--   place holders.
filterClauseWithVals :: PersistEntity val => Maybe FilterTablePrefix -> SqlBackend -> [Filter val] -> (Text, [PersistValue])

-- | Render a <tt>[<a>SelectOpt</a> record]</tt> made up *only* of
--   <a>Asc</a> and <a>Desc</a> constructors into a <a>Text</a> value
--   suitable for inclusion into a SQL query.
orderClause :: PersistEntity val => Maybe FilterTablePrefix -> SqlBackend -> [SelectOpt val] -> Text

-- | Generates sql for limit and offset for postgres, sqlite and mysql.
decorateSQLWithLimitOffset :: Text -> (Int, Int) -> Text -> Text

-- | An exception indicating that Persistent refused to run some unsafe
--   migrations. Contains a list of pairs where the Bool tracks whether the
--   migration was unsafe (True means unsafe), and the Sql is the sql
--   statement for the migration.
newtype PersistUnsafeMigrationException
PersistUnsafeMigrationException :: [(Bool, Sql)] -> PersistUnsafeMigrationException

-- | A <a>Migration</a> is a four level monad stack consisting of:
--   
--   <ul>
--   <li><tt><a>WriterT</a> [<a>Text</a>]</tt> representing a log of errors
--   in the migrations.</li>
--   <li><tt><a>WriterT</a> <a>CautiousMigration</a></tt> representing a
--   list of migrations to run, along with whether or not they are
--   safe.</li>
--   <li><tt><a>ReaderT</a> <a>SqlBackend</a></tt>, aka the
--   <a>SqlPersistT</a> transformer for database interop.</li>
--   <li><tt><a>IO</a></tt> for arbitrary IO.</li>
--   </ul>
type Migration = WriterT [Text] WriterT CautiousMigration ReaderT SqlBackend IO ()

-- | A list of SQL operations, marked with a safety flag. If the
--   <a>Bool</a> is <a>True</a>, then the operation is *unsafe* - it might
--   be destructive, or otherwise not idempotent. If the <a>Bool</a> is
--   <a>False</a>, then the operation is *safe*, and can be run repeatedly
--   without issues.
type CautiousMigration = [(Bool, Sql)]
type Sql = Text

-- | Given a <a>Migration</a>, this parses it and returns either a list of
--   errors associated with the migration or a list of migrations to do.
parseMigration :: forall (m :: Type -> Type). (HasCallStack, MonadIO m) => Migration -> ReaderT SqlBackend m (Either [Text] CautiousMigration)

-- | Like <a>parseMigration</a>, but instead of returning the value in an
--   <a>Either</a> value, it calls <a>error</a> on the error values.
parseMigration' :: forall (m :: Type -> Type). (HasCallStack, MonadIO m) => Migration -> ReaderT SqlBackend m CautiousMigration

-- | Prints a migration.
printMigration :: forall (m :: Type -> Type). (HasCallStack, MonadIO m) => Migration -> ReaderT SqlBackend m ()

-- | Convert a <a>Migration</a> to a list of <a>Text</a> values
--   corresponding to their <a>Sql</a> statements.
showMigration :: forall (m :: Type -> Type). (HasCallStack, MonadIO m) => Migration -> ReaderT SqlBackend m [Text]

-- | Return all of the <a>Sql</a> values associated with the given
--   migration. Calls <a>error</a> if there's a parse error on any
--   migration.
getMigration :: forall (m :: Type -> Type). (MonadIO m, HasCallStack) => Migration -> ReaderT SqlBackend m [Sql]

-- | Runs a migration. If the migration fails to parse or if any of the
--   migrations are unsafe, then this throws a
--   <a>PersistUnsafeMigrationException</a>.
runMigration :: forall (m :: Type -> Type). MonadIO m => Migration -> ReaderT SqlBackend m ()

-- | Same as <a>runMigration</a>, but does not report the individual
--   migrations on stderr. Instead it returns a list of the executed SQL
--   commands.
--   
--   This is a safer/more robust alternative to <a>runMigrationSilent</a>,
--   but may be less silent for some persistent implementations, most
--   notably persistent-postgresql
runMigrationQuiet :: forall (m :: Type -> Type). MonadIO m => Migration -> ReaderT SqlBackend m [Text]

-- | Same as <a>runMigration</a>, but returns a list of the SQL commands
--   executed instead of printing them to stderr.
--   
--   This function silences the migration by remapping <a>stderr</a>. As a
--   result, it is not thread-safe and can clobber output from other parts
--   of the program. This implementation method was chosen to also silence
--   postgresql migration output on stderr, but is not recommended!
runMigrationSilent :: forall (m :: Type -> Type). MonadUnliftIO m => Migration -> ReaderT SqlBackend m [Text]

-- | Like <a>runMigration</a>, but this will perform the unsafe database
--   migrations instead of erroring out.
runMigrationUnsafe :: forall (m :: Type -> Type). MonadIO m => Migration -> ReaderT SqlBackend m ()

-- | Same as <a>runMigrationUnsafe</a>, but returns a list of the SQL
--   commands executed instead of printing them to stderr.
runMigrationUnsafeQuiet :: forall (m :: Type -> Type). (HasCallStack, MonadIO m) => Migration -> ReaderT SqlBackend m [Text]

-- | Report multiple errors in a <a>Migration</a>.
reportErrors :: [Text] -> Migration

-- | Add a migration to the migration plan.
addMigration :: Bool -> Sql -> Migration

-- | Add a <a>CautiousMigration</a> (aka a <tt>[(<a>Bool</a>,
--   <a>Text</a>)]</tt>) to the migration plan.
addMigrations :: CautiousMigration -> Migration

-- | Run an action against the database during a migration. Can be useful
--   for eg creating Postgres extensions:
--   
--   <pre>
--   runSqlCommand $ <a>rawExecute</a> "CREATE EXTENSION IF NOT EXISTS "uuid-ossp";" []
--   </pre>
runSqlCommand :: SqlPersistT IO () -> Migration

-- | Commit the current transaction and begin a new one. This is used when
--   a transaction commit is required within the context of
--   <a>runSqlConn</a> (which brackets its provided action with a
--   transaction begin/commit pair).
transactionSave :: forall (m :: Type -> Type). MonadIO m => ReaderT SqlBackend m ()

-- | Commit the current transaction and begin a new one with the specified
--   isolation level.
transactionSaveWithIsolation :: forall (m :: Type -> Type). MonadIO m => IsolationLevel -> ReaderT SqlBackend m ()

-- | Roll back the current transaction and begin a new one. This rolls back
--   to the state of the last call to <a>transactionSave</a> or the
--   enclosing <a>runSqlConn</a> call.
transactionUndo :: forall (m :: Type -> Type). MonadIO m => ReaderT SqlBackend m ()

-- | Roll back the current transaction and begin a new one with the
--   specified isolation level.
transactionUndoWithIsolation :: forall (m :: Type -> Type). MonadIO m => IsolationLevel -> ReaderT SqlBackend m ()


-- | WARNING
--   
--   This module is introduced in version <tt>3.5.0.0</tt> to provide a
--   smooth migration experience from this legacy syntax to the new and
--   improved syntax. If you've imported this module, it means you've
--   decided to use the old syntax for a little bit longer, rather than
--   migrate to the new stuff. That's fine!
--   
--   But you should know that this module, and all of the legacy syntax,
--   will be completely removed from the library in version
--   <tt>4.0.0.0</tt>.
--   
--   The <tt>esqueleto</tt> EDSL (embedded domain specific language). This
--   module replaces <tt>Database.Persist</tt>, so instead of importing
--   that module you should just import this one:
--   
--   <pre>
--   -- For a module using just esqueleto.
--   import Database.Esqueleto
--   </pre>
--   
--   If you need to use <tt>persistent</tt>'s default support for queries
--   as well, either import it qualified:
--   
--   <pre>
--   -- For a module that mostly uses esqueleto.
--   import Database.Esqueleto
--   import qualified Database.Persist as P
--   </pre>
--   
--   or import <tt>esqueleto</tt> itself qualified:
--   
--   <pre>
--   -- For a module that uses esqueleto just on some queries.
--   import Database.Persist
--   import qualified Database.Esqueleto as E
--   </pre>
--   
--   Other than identifier name clashes, <tt>esqueleto</tt> does not
--   conflict with <tt>persistent</tt> in any way.
module Database.Esqueleto.Legacy

-- | <tt>WHERE</tt> clause: restrict the query's result.
where_ :: SqlExpr (Value Bool) -> SqlQuery ()

-- | An <tt>ON</tt> clause, useful to describe how two tables are related.
--   Cross joins and tuple-joins do not need an <a>on</a> clause, but
--   <a>InnerJoin</a> and the various outer joins do.
--   
--   <a>Database.Esqueleto.Experimental</a> in version 4.0.0.0 of the
--   library. The <tt>Experimental</tt> module has a dramatically improved
--   means for introducing tables and entities that provides more power and
--   less potential for runtime errors.
--   
--   If you don't include an <a>on</a> clause (or include too many!) then a
--   runtime exception will be thrown.
--   
--   As an example, consider this simple join:
--   
--   <pre>
--   <a>select</a> $
--   <a>from</a> $ \(foo `<a>InnerJoin</a>` bar) -&gt; do
--     <a>on</a> (foo <a>^.</a> FooId <a>==.</a> bar <a>^.</a> BarFooId)
--     ...
--   </pre>
--   
--   We need to specify the clause for joining the two columns together. If
--   we had this:
--   
--   <pre>
--   <a>select</a> $
--   <a>from</a> $ \(foo `<tt>CrossJoin</tt>` bar) -&gt; do
--     ...
--   </pre>
--   
--   Then we can safely omit the <a>on</a> clause, because the cross join
--   will make pairs of all records possible.
--   
--   You can do multiple <a>on</a> clauses in a query. This query joins
--   three tables, and has two <a>on</a> clauses:
--   
--   <pre>
--   <a>select</a> $
--   <a>from</a> $ \(foo `<a>InnerJoin</a>` bar `<a>InnerJoin</a>` baz) -&gt; do
--     <a>on</a> (baz <a>^.</a> BazId <a>==.</a> bar <a>^.</a> BarBazId)
--     <a>on</a> (foo <a>^.</a> FooId <a>==.</a> bar <a>^.</a> BarFooId)
--     ...
--   </pre>
--   
--   Old versions of esqueleto required that you provide the <a>on</a>
--   clauses in reverse order. This restriction has been lifted - you can
--   now provide <a>on</a> clauses in any order, and the SQL should work
--   itself out. The above query is now totally equivalent to this:
--   
--   <pre>
--   <a>select</a> $
--   <a>from</a> $ \(foo `<a>InnerJoin</a>` bar `<a>InnerJoin</a>` baz) -&gt; do
--     <a>on</a> (foo <a>^.</a> FooId <a>==.</a> bar <a>^.</a> BarFooId)
--     <a>on</a> (baz <a>^.</a> BazId <a>==.</a> bar <a>^.</a> BarBazId)
--     ...
--   </pre>
on :: SqlExpr (Value Bool) -> SqlQuery ()

-- | <tt>GROUP BY</tt> clause. You can enclose multiple columns in a tuple.
--   
--   <pre>
--   select $ <a>from</a> \(foo `<tt>InnerJoin</tt>` bar) -&gt; do
--     <a>on</a> (foo <a>^.</a> FooBarId <a>==.</a> bar <a>^.</a> BarId)
--     <a>groupBy</a> (bar <a>^.</a> BarId, bar <a>^.</a> BarName)
--     return (bar <a>^.</a> BarId, bar <a>^.</a> BarName, countRows)
--   </pre>
--   
--   With groupBy you can sort by aggregate functions, like so (we used
--   <tt>let</tt> to restrict the more general <a>countRows</a> to
--   <tt>SqlSqlExpr (Value Int)</tt> to avoid ambiguity---the second use of
--   <a>countRows</a> has its type restricted by the <tt>:: Int</tt>
--   below):
--   
--   <pre>
--   r &lt;- select $ <a>from</a> \(foo `<tt>InnerJoin</tt>` bar) -&gt; do
--     <a>on</a> (foo <a>^.</a> FooBarId <a>==.</a> bar <a>^.</a> BarId)
--     <a>groupBy</a> $ bar <a>^.</a> BarName
--     let countRows' = <a>countRows</a>
--     <a>orderBy</a> [<a>asc</a> countRows']
--     return (bar <a>^.</a> BarName, countRows')
--   forM_ r $ \(<a>Value</a> name, <a>Value</a> count) -&gt; do
--     print name
--     print (count :: Int)
--   </pre>
--   
--   <h3>Need more columns?</h3>
--   
--   The <a>ToSomeValues</a> class is defined for <a>SqlExpr</a> and tuples
--   of <a>SqlExpr</a>s. We only have definitions for up to 8 elements in a
--   tuple right now, so it's possible that you may need to have more than
--   8 elements.
--   
--   For example, consider a query with a <a>groupBy</a> call like this:
--   
--   <pre>
--   groupBy (e0, e1, e2, e3, e4, e5, e6, e7)
--   </pre>
--   
--   This is the biggest you can get with a single tuple. However, you can
--   easily nest the tuples to add more:
--   
--   <pre>
--   groupBy ((e0, e1, e2, e3, e4, e5, e6, e7), e8, e9)
--   </pre>
groupBy :: ToSomeValues a => a -> SqlQuery ()

-- | <tt>ORDER BY</tt> clause. See also <a>asc</a> and <a>desc</a>.
--   
--   Multiple calls to <a>orderBy</a> get concatenated on the final query,
--   including <a>distinctOnOrderBy</a>.
orderBy :: [SqlExpr OrderBy] -> SqlQuery ()

-- | Ascending order of this field or SqlExpression.
asc :: PersistField a => SqlExpr (Value a) -> SqlExpr OrderBy

-- | Descending order of this field or SqlExpression.
desc :: PersistField a => SqlExpr (Value a) -> SqlExpr OrderBy

-- | <tt>LIMIT</tt>. Limit the number of returned rows.
limit :: Int64 -> SqlQuery ()

-- | <tt>OFFSET</tt>. Usually used with <a>limit</a>.
offset :: Int64 -> SqlQuery ()

-- | <tt>DISTINCT</tt>. Change the current <tt>SELECT</tt> into <tt>SELECT
--   DISTINCT</tt>. For example:
--   
--   <pre>
--   select $ distinct $
--     <a>from</a> \foo -&gt; do
--     ...
--   </pre>
--   
--   Note that this also has the same effect:
--   
--   <pre>
--   select $
--     <a>from</a> \foo -&gt; do
--     distinct (return ())
--     ...
--   </pre>
distinct :: SqlQuery a -> SqlQuery a

-- | <tt>DISTINCT ON</tt>. Change the current <tt>SELECT</tt> into
--   <tt>SELECT DISTINCT ON (SqlExpressions)</tt>. For example:
--   
--   <pre>
--   select $
--     <a>from</a> \foo -&gt;
--     <a>distinctOn</a> [<a>don</a> (foo ^. FooName), <a>don</a> (foo ^. FooState)] $ do
--     ...
--   </pre>
--   
--   You can also chain different calls to <a>distinctOn</a>. The above is
--   equivalent to:
--   
--   <pre>
--   select $
--     <a>from</a> \foo -&gt;
--     <a>distinctOn</a> [<a>don</a> (foo ^. FooName)] $
--     <a>distinctOn</a> [<a>don</a> (foo ^. FooState)] $ do
--     ...
--   </pre>
--   
--   Each call to <a>distinctOn</a> adds more SqlExpressions. Calls to
--   <a>distinctOn</a> override any calls to <a>distinct</a>.
--   
--   Note that PostgreSQL requires the SqlExpressions on <tt>DISTINCT
--   ON</tt> to be the first ones to appear on a <tt>ORDER BY</tt>. This is
--   not managed automatically by esqueleto, keeping its spirit of trying
--   to be close to raw SQL.
--   
--   Supported by PostgreSQL only.

-- | <i>Deprecated: This function is deprecated, as it is only supported in
--   Postgresql. Please use the variant in <a>PostgreSQL</a> instead.</i>
distinctOn :: [SqlExpr DistinctOn] -> SqlQuery a -> SqlQuery a

-- | Erase an SqlExpression's type so that it's suitable to be used by
--   <a>distinctOn</a>.
don :: SqlExpr (Value a) -> SqlExpr DistinctOn

-- | A convenience function that calls both <a>distinctOn</a> and
--   <a>orderBy</a>. In other words,
--   
--   <pre>
--   <a>distinctOnOrderBy</a> [asc foo, desc bar, desc quux] $ do
--     ...
--   </pre>
--   
--   is the same as:
--   
--   <pre>
--   <a>distinctOn</a> [don foo, don  bar, don  quux] $ do
--     <a>orderBy</a>  [asc foo, desc bar, desc quux]
--     ...
--   </pre>

-- | <i>Deprecated: This function is deprecated, as it is only supported in
--   Postgresql. Please use the function defined in <a>PostgreSQL</a>
--   instead.</i>
distinctOnOrderBy :: [SqlExpr OrderBy] -> SqlQuery a -> SqlQuery a

-- | <tt>HAVING</tt>.
having :: SqlExpr (Value Bool) -> SqlQuery ()

-- | Add a locking clause to the query. Please read <a>LockingKind</a>
--   documentation and your RDBMS manual. Unsafe since not all locking
--   clauses are implemented for every RDBMS
--   
--   If multiple calls to <a>locking</a> are made on the same query, the
--   last one is used.
locking :: LockingKind -> SqlQuery ()

-- | Project a field of an entity.
(^.) :: forall typ val. (PersistEntity val, PersistField typ) => SqlExpr (Entity val) -> EntityField val typ -> SqlExpr (Value typ)
infixl 9 ^.

-- | Project an <a>EntityField</a> of a nullable entity. The result type
--   will be <a>Nullable</a>, meaning that nested <a>Maybe</a> won't be
--   produced here.
--   
--   As of v3.6.0.0, this will attempt to combine nested <a>Maybe</a>. If
--   you want to keep nested <a>Maybe</a>, then see <a>??.</a>.
(?.) :: (PersistEntity val, PersistField typ) => SqlExpr (Maybe (Entity val)) -> EntityField val typ -> SqlExpr (Value (Maybe (Nullable typ)))
infixl 9 ?.

-- | Lift a constant value from Haskell-land to the query.
val :: PersistField typ => typ -> SqlExpr (Value typ)

-- | <tt>IS NULL</tt> comparison.
--   
--   For <tt>IS NOT NULL</tt>, you can negate this with <a>not_</a>, as in
--   <tt>not_ (isNothing (person ^. PersonAge))</tt>
--   
--   Warning: Persistent and Esqueleto have different behavior for <tt>!=
--   Nothing</tt>:
--   
--   TODO: table
--   
--   In SQL, <tt>= NULL</tt> and <tt>!= NULL</tt> return NULL instead of
--   true or false. For this reason, you very likely do not want to use
--   <tt><a>!=.</a> Nothing</tt> in Esqueleto. You may find these
--   <tt>hlint</tt> rules helpful to enforce this:
--   
--   <pre>
--   - error: {lhs: v Database.Esqueleto.==. Database.Esqueleto.nothing, rhs: Database.Esqueleto.isNothing v, name: Use Esqueleto's isNothing}
--   - error: {lhs: v Database.Esqueleto.==. Database.Esqueleto.val Nothing, rhs: Database.Esqueleto.isNothing v, name: Use Esqueleto's isNothing}
--   - error: {lhs: v Database.Esqueleto.!=. Database.Esqueleto.nothing, rhs: not_ (Database.Esqueleto.isNothing v), name: Use Esqueleto's not isNothing}
--   - error: {lhs: v Database.Esqueleto.!=. Database.Esqueleto.val Nothing, rhs: not_ (Database.Esqueleto.isNothing v), name: Use Esqueleto's not isNothing}
--   </pre>
isNothing :: PersistField typ => SqlExpr (Value (Maybe typ)) -> SqlExpr (Value Bool)

-- | Analogous to <a>Just</a>, promotes a value of type <tt>typ</tt> into
--   one of type <tt>Maybe typ</tt>. It should hold that <tt><a>val</a> .
--   Just === just . <a>val</a></tt>.
--   
--   This function will try not to produce a nested <a>Maybe</a>. This is
--   in accord with how SQL represents <tt>NULL</tt>. That means that
--   <tt><a>just</a> . <a>just</a> = <a>just</a></tt>. This behavior was
--   changed in v3.6.0.0. If you want to produce nested <a>Maybe</a>, see
--   <a>just'</a>.
just :: NullableFieldProjection typ typ' => SqlExpr (Value typ) -> SqlExpr (Value (Maybe typ'))

-- | Like <a>just</a>, but this function does not try to collapse nested
--   <a>Maybe</a>. This may be useful if you have type inference problems
--   with <a>just</a>.
just' :: SqlExpr (Value typ) -> SqlExpr (Value (Maybe typ))

-- | <tt>NULL</tt> value.
nothing :: SqlExpr (Value (Maybe typ))

-- | Join nested <a>Maybe</a>s in a <a>Value</a> into one. This is useful
--   when calling aggregate functions on nullable fields.
--   
--   As of v3.6.0.0, this function will attempt to work on both
--   <tt><a>SqlExpr</a> (<a>Value</a> (<a>Maybe</a> a))</tt> as well as
--   <tt><a>SqlExpr</a> (<a>Value</a> (<a>Maybe</a> (<a>Maybe</a> a)))</tt>
--   inputs to make transitioning to <a>NullableFieldProjection</a> easier.
--   This may make type inference worse in some cases. If you want the
--   monomorphic variant, see <a>joinV'</a>
joinV :: NullableFieldProjection typ typ' => SqlExpr (Value (Maybe typ)) -> SqlExpr (Value (Maybe typ'))

-- | Like <a>joinV</a>, but monomorphic: the input type only works on
--   <tt><a>SqlExpr</a> (<a>Value</a> (Maybe (Maybe a)))</tt>.
--   
--   This function may be useful if you have type inference issues with
--   <a>joinV</a>.
joinV' :: SqlExpr (Value (Maybe (Maybe typ))) -> SqlExpr (Value (Maybe typ))

-- | Project an SqlExpression that may be null, guarding against null
--   cases.
withNonNull :: PersistField typ => SqlExpr (Value (Maybe typ)) -> (SqlExpr (Value typ) -> SqlQuery a) -> SqlQuery a

-- | <tt>COUNT(*)</tt> value.
countRows :: Num a => SqlExpr (Value a)

-- | <tt>COUNT</tt>.
count :: Num a => SqlExpr (Value typ) -> SqlExpr (Value a)

-- | <tt>COUNT(DISTINCT x)</tt>.
countDistinct :: Num a => SqlExpr (Value typ) -> SqlExpr (Value a)
not_ :: SqlExpr (Value Bool) -> SqlExpr (Value Bool)

-- | This operator produces the SQL operator <tt>=</tt>, which is used to
--   compare values for equality.
--   
--   Example:
--   
--   <pre>
--   query :: UserId -&gt; SqlPersistT IO [Entity User]
--   query userId = select $ do
--       user &lt;- from $ table @User
--       where_ (user ^. UserId ==. val userId)
--       pure user
--   </pre>
--   
--   This would generate the following SQL:
--   
--   <pre>
--   SELECT user.*
--   FROM user
--   WHERE user.id = ?
--   </pre>
(==.) :: PersistField typ => SqlExpr (Value typ) -> SqlExpr (Value typ) -> SqlExpr (Value Bool)
infix 4 ==.

-- | This operator translates to the SQL operator <tt>&gt;=</tt>.
--   
--   Example:
--   
--   <pre>
--   where_ $ user ^. UserAge &gt;=. val 21
--   </pre>
(>=.) :: PersistField typ => SqlExpr (Value typ) -> SqlExpr (Value typ) -> SqlExpr (Value Bool)
infix 4 >=.

-- | This operator translates to the SQL operator <tt>&gt;</tt>.
--   
--   Example:
--   
--   <pre>
--   where_ $ user ^. UserAge &gt;. val 20
--   </pre>
(>.) :: PersistField typ => SqlExpr (Value typ) -> SqlExpr (Value typ) -> SqlExpr (Value Bool)
infix 4 >.

-- | This operator translates to the SQL operator <tt>&lt;=</tt>.
--   
--   Example:
--   
--   <pre>
--   where_ $ val 21 &lt;=. user ^. UserAge
--   </pre>
(<=.) :: PersistField typ => SqlExpr (Value typ) -> SqlExpr (Value typ) -> SqlExpr (Value Bool)
infix 4 <=.

-- | This operator translates to the SQL operator <tt>&lt;</tt>.
--   
--   Example:
--   
--   <pre>
--   where_ $ val 20 &lt;. user ^. UserAge
--   </pre>
(<.) :: PersistField typ => SqlExpr (Value typ) -> SqlExpr (Value typ) -> SqlExpr (Value Bool)
infix 4 <.

-- | This operator translates to the SQL operator <tt>!=</tt>.
--   
--   Example:
--   
--   <pre>
--   where_ $ user ^. UserName !=. val <a>Bob</a>
--   </pre>
(!=.) :: PersistField typ => SqlExpr (Value typ) -> SqlExpr (Value typ) -> SqlExpr (Value Bool)
infix 4 !=.

-- | This operator translates to the SQL operator <tt>AND</tt>.
--   
--   Example:
--   
--   <pre>
--   where_ $
--           user ^. UserName ==. val <a>Matt</a>
--       &amp;&amp;. user ^. UserAge &gt;=. val 21
--   </pre>
(&&.) :: SqlExpr (Value Bool) -> SqlExpr (Value Bool) -> SqlExpr (Value Bool)
infixr 3 &&.

-- | This operator translates to the SQL operator <tt>AND</tt>.
--   
--   Example:
--   
--   <pre>
--   where_ $
--           user ^. UserName ==. val <a>Matt</a>
--       ||. user ^. UserName ==. val <a>John</a>
--   </pre>
(||.) :: SqlExpr (Value Bool) -> SqlExpr (Value Bool) -> SqlExpr (Value Bool)
infixr 2 ||.

-- | <tt>a <a>between</a> (b, c)</tt> translates to the SQL expression
--   <tt>a &gt;= b AND a &lt;= c</tt>. It does not use a SQL
--   <tt>BETWEEN</tt> operator.
--   
--   @since: 3.1.0
between :: PersistField a => SqlExpr (Value a) -> (SqlExpr (Value a), SqlExpr (Value a)) -> SqlExpr (Value Bool)

-- | This operator translates to the SQL operator <tt>+</tt>.
--   
--   This does not require or assume anything about the SQL values.
--   Interpreting what <tt>+.</tt> means for a given type is left to the
--   database engine.
--   
--   Example:
--   
--   <pre>
--   user ^. UserAge +. val 10
--   </pre>
(+.) :: PersistField a => SqlExpr (Value a) -> SqlExpr (Value a) -> SqlExpr (Value a)
infixl 6 +.

-- | This operator translates to the SQL operator <tt>-</tt>.
--   
--   This does not require or assume anything about the SQL values.
--   Interpreting what <tt>-.</tt> means for a given type is left to the
--   database engine.
--   
--   Example:
--   
--   <pre>
--   user ^. UserAge -. val 10
--   </pre>
(-.) :: PersistField a => SqlExpr (Value a) -> SqlExpr (Value a) -> SqlExpr (Value a)
infixl 6 -.

-- | This operator translates to the SQL operator <tt>/</tt>.
--   
--   This does not require or assume anything about the SQL values.
--   Interpreting what <tt>/.</tt> means for a given type is left to the
--   database engine.
--   
--   Example:
--   
--   <pre>
--   user ^. UserAge /. val 10
--   </pre>
(/.) :: PersistField a => SqlExpr (Value a) -> SqlExpr (Value a) -> SqlExpr (Value a)
infixl 7 /.

-- | This operator translates to the SQL operator <tt>*</tt>.
--   
--   This does not require or assume anything about the SQL values.
--   Interpreting what <tt>*.</tt> means for a given type is left to the
--   database engine.
--   
--   Example:
--   
--   <pre>
--   user ^. UserAge *. val 10
--   </pre>
(*.) :: PersistField a => SqlExpr (Value a) -> SqlExpr (Value a) -> SqlExpr (Value a)
infixl 7 *.
round_ :: (PersistField a, Num a, PersistField b, Num b) => SqlExpr (Value a) -> SqlExpr (Value b)
ceiling_ :: (PersistField a, Num a, PersistField b, Num b) => SqlExpr (Value a) -> SqlExpr (Value b)
floor_ :: (PersistField a, Num a, PersistField b, Num b) => SqlExpr (Value a) -> SqlExpr (Value b)
min_ :: PersistField a => SqlExpr (Value a) -> SqlExpr (Value (Maybe (Nullable a)))
max_ :: PersistField a => SqlExpr (Value a) -> SqlExpr (Value (Maybe (Nullable a)))
sum_ :: (PersistField a, PersistField b) => SqlExpr (Value a) -> SqlExpr (Value (Maybe b))
avg_ :: (PersistField a, PersistField b) => SqlExpr (Value a) -> SqlExpr (Value (Maybe b))

-- | Allow a number of one type to be used as one of another type via an
--   implicit cast. An explicit cast is not made, this function changes
--   only the types on the Haskell side.
--   
--   <i>Caveat</i>: Trying to use <tt>castNum</tt> from <tt>Double</tt> to
--   <tt>Int</tt> will not result in an integer, the original fractional
--   number will still be used! Use <a>round_</a>, <a>ceiling_</a> or
--   <a>floor_</a> instead.
--   
--   <i>Safety</i>: This operation is mostly safe due to the <a>Num</a>
--   constraint between the types and the fact that RDBMSs usually allow
--   numbers of different types to be used interchangeably. However, there
--   may still be issues with the query not being accepted by the RDBMS or
--   <tt>persistent</tt> not being able to parse it.
castNum :: (Num a, Num b) => SqlExpr (Value a) -> SqlExpr (Value b)

-- | Same as <a>castNum</a>, but for nullable values.
castNumM :: (Num a, Num b) => SqlExpr (Value (Maybe a)) -> SqlExpr (Value (Maybe b))

-- | <tt>COALESCE</tt> function. Evaluates the arguments in order and
--   returns the value of the first non-NULL SqlExpression, or NULL
--   (Nothing) otherwise. Some RDBMSs (such as SQLite) require at least two
--   arguments; please refer to the appropriate documentation.
coalesce :: (PersistField a, NullableFieldProjection a a') => [SqlExpr (Value (Maybe a))] -> SqlExpr (Value (Maybe a'))

-- | Like <tt>coalesce</tt>, but takes a non-nullable SqlExpression placed
--   at the end of the SqlExpression list, which guarantees a non-NULL
--   result.
coalesceDefault :: PersistField a => [SqlExpr (Value (Maybe a))] -> SqlExpr (Value a) -> SqlExpr (Value a)

-- | <tt>LOWER</tt> function.
lower_ :: SqlString s => SqlExpr (Value s) -> SqlExpr (Value s)

-- | <tt>UPPER</tt> function. @since 3.3.0
upper_ :: SqlString s => SqlExpr (Value s) -> SqlExpr (Value s)

-- | <tt>TRIM</tt> function. @since 3.3.0
trim_ :: SqlString s => SqlExpr (Value s) -> SqlExpr (Value s)

-- | <tt>LTRIM</tt> function. @since 3.3.0
ltrim_ :: SqlString s => SqlExpr (Value s) -> SqlExpr (Value s)

-- | <tt>RTRIM</tt> function. @since 3.3.0
rtrim_ :: SqlString s => SqlExpr (Value s) -> SqlExpr (Value s)

-- | <tt>LENGTH</tt> function. @since 3.3.0
length_ :: (SqlString s, Num a) => SqlExpr (Value s) -> SqlExpr (Value a)

-- | <tt>LEFT</tt> function. @since 3.3.0
left_ :: (SqlString s, Num a) => (SqlExpr (Value s), SqlExpr (Value a)) -> SqlExpr (Value s)

-- | <tt>RIGHT</tt> function. @since 3.3.0
right_ :: (SqlString s, Num a) => (SqlExpr (Value s), SqlExpr (Value a)) -> SqlExpr (Value s)

-- | <tt>LIKE</tt> operator.
like :: SqlString s => SqlExpr (Value s) -> SqlExpr (Value s) -> SqlExpr (Value Bool)
infixr 2 `like`

-- | <tt>ILIKE</tt> operator (case-insensitive <tt>LIKE</tt>).
--   
--   Supported by PostgreSQL only. Deprecated in version 3.6.0 in favor of
--   the version available from <a>Database.Esqueleto.PostgreSQL</a>.

-- | <i>Deprecated: Since 3.6.0: <a>ilike</a> is only supported on
--   Postgres. Please import it from 'Database.Esqueleto.PostgreSQL.</i>
ilike :: SqlString s => SqlExpr (Value s) -> SqlExpr (Value s) -> SqlExpr (Value Bool)
infixr 2 `ilike`

-- | The string <tt><a>%</a></tt>. May be useful while using <a>like</a>
--   and concatenation (<a>concat_</a> or <a>++.</a>, depending on your
--   database). Note that you always have to type the parenthesis, for
--   example:
--   
--   <pre>
--   name `<a>like</a>` (%) ++. <a>val</a> "John" ++. (%)
--   </pre>
(%) :: SqlString s => SqlExpr (Value s)

-- | The <tt>CONCAT</tt> function with a variable number of parameters.
--   Supported by MySQL and PostgreSQL. SQLite supports this in versions
--   after 3.44.0, and <tt>persistent-sqlite</tt> supports this in versions
--   <tt>2.13.3.0</tt> and after.
concat_ :: SqlString s => [SqlExpr (Value s)] -> SqlExpr (Value s)

-- | The <tt>||</tt> string concatenation operator (named after Haskell's
--   <a>++</a> in order to avoid naming clash with <a>||.</a>).
--   
--   Supported by SQLite and PostgreSQL.
--   
--   MySQL support requires setting the SQL mode to
--   <tt>PIPES_AS_CONCAT</tt> or <tt>ANSI</tt> - see <a>this StackOverflow
--   answer</a>.
(++.) :: SqlString s => SqlExpr (Value s) -> SqlExpr (Value s) -> SqlExpr (Value s)
infixr 5 ++.

-- | Cast a string type into <a>Text</a>. This function is very useful if
--   you want to use <tt>newtype</tt>s, or if you want to apply functions
--   such as <a>like</a> to strings of different types.
--   
--   <i>Safety:</i> This is a slightly unsafe function, especially if you
--   have defined your own instances of <a>SqlString</a>. Also, since
--   <a>Maybe</a> is an instance of <a>SqlString</a>, it's possible to turn
--   a nullable value into a non-nullable one. Avoid using this function if
--   possible.
castString :: (SqlString s, SqlString r) => SqlExpr (Value s) -> SqlExpr (Value r)

-- | Execute a subquery <tt>SELECT</tt> in an SqlExpression. Returns a list
--   of values.
subList_select :: PersistField a => SqlQuery (SqlExpr (Value a)) -> SqlExpr (ValueList a)

-- | Lift a list of constant value from Haskell-land to the query.
valList :: PersistField typ => [typ] -> SqlExpr (ValueList typ)

-- | Same as <a>just</a> but for <a>ValueList</a>. Most of the time you
--   won't need it, though, because you can use <a>just</a> from inside
--   <a>subList_select</a> or <a>Just</a> from inside <a>valList</a>.
justList :: SqlExpr (ValueList typ) -> SqlExpr (ValueList (Maybe typ))

-- | <tt>IN</tt> operator. For example if you want to select all
--   <tt>Person</tt>s by a list of IDs:
--   
--   <pre>
--   SELECT *
--   FROM Person
--   WHERE Person.id IN (?)
--   </pre>
--   
--   In <tt>esqueleto</tt>, we may write the same query above as:
--   
--   <pre>
--   select $
--   <a>from</a> $ \person -&gt; do
--   <a>where_</a> $ person <a>^.</a> PersonId `<tt>in_</tt>` <a>valList</a> personIds
--   return person
--   </pre>
--   
--   Where <tt>personIds</tt> is of type <tt>[Key Person]</tt>.
in_ :: PersistField typ => SqlExpr (Value typ) -> SqlExpr (ValueList typ) -> SqlExpr (Value Bool)

-- | <tt>NOT IN</tt> operator.
notIn :: PersistField typ => SqlExpr (Value typ) -> SqlExpr (ValueList typ) -> SqlExpr (Value Bool)

-- | <tt>EXISTS</tt> operator. For example:
--   
--   <pre>
--   select $
--   <a>from</a> $ \person -&gt; do
--   <a>where_</a> $ <a>exists</a> $
--            <a>from</a> $ \post -&gt; do
--            <a>where_</a> (post <a>^.</a> BlogPostAuthorId <a>==.</a> person <a>^.</a> PersonId)
--   return person
--   </pre>
exists :: SqlQuery () -> SqlExpr (Value Bool)

-- | <tt>NOT EXISTS</tt> operator.
notExists :: SqlQuery () -> SqlExpr (Value Bool)

-- | <tt>SET</tt> clause used on <tt>UPDATE</tt>s. Note that while it's not
--   a type error to use this function on a <tt>SELECT</tt>, it will most
--   certainly result in a runtime error.
set :: PersistEntity val => SqlExpr (Entity val) -> [SqlExpr (Entity val) -> SqlExpr Update] -> SqlQuery ()
(=.) :: (PersistEntity val, PersistField typ) => EntityField val typ -> SqlExpr (Value typ) -> SqlExpr (Entity val) -> SqlExpr Update
infixr 3 =.
(+=.) :: (PersistEntity val, PersistField a) => EntityField val a -> SqlExpr (Value a) -> SqlExpr (Entity val) -> SqlExpr Update
infixr 3 +=.
(-=.) :: (PersistEntity val, PersistField a) => EntityField val a -> SqlExpr (Value a) -> SqlExpr (Entity val) -> SqlExpr Update
infixr 3 -=.
(*=.) :: (PersistEntity val, PersistField a) => EntityField val a -> SqlExpr (Value a) -> SqlExpr (Entity val) -> SqlExpr Update
infixr 3 *=.
(/=.) :: (PersistEntity val, PersistField a) => EntityField val a -> SqlExpr (Value a) -> SqlExpr (Entity val) -> SqlExpr Update
infixr 3 /=.

-- | <tt>CASE</tt> statement. For example:
--   
--   <pre>
--   select $
--   return $
--   <a>case_</a>
--      [ <a>when_</a>
--          (<a>exists</a> $
--          <a>from</a> $ \p -&gt; do
--          <a>where_</a> (p <a>^.</a> PersonName <a>==.</a> <a>val</a> "Mike"))
--        <a>then_</a>
--          (<a>subSelect</a> $
--          <a>from</a> $ \v -&gt; do
--          let sub =
--                  <a>from</a> $ \c -&gt; do
--                  <a>where_</a> (c <a>^.</a> PersonName <a>==.</a> <a>val</a> "Mike")
--                  return (c <a>^.</a> PersonFavNum)
--          <a>where_</a> (<a>just</a> (v <a>^.</a> PersonFavNum) &gt;. <a>subSelect</a> sub)
--          return $ <a>count</a> (v <a>^.</a> PersonName) +. <a>val</a> (1 :: Int)) ]
--      (<a>else_</a> $ <a>val</a> (-1))
--   </pre>
--   
--   This query is a bit complicated, but basically it checks if a person
--   named <tt>"Mike"</tt> exists, and if that person does, run the
--   subquery to find out how many people have a ranking (by Fav Num)
--   higher than <tt>"Mike"</tt>.
--   
--   <b>NOTE:</b> There are a few things to be aware about this statement.
--   
--   <ul>
--   <li>This only implements the full CASE statement, it does not
--   implement the "simple" CASE statement.</li>
--   <li>At least one <a>when_</a> and <a>then_</a> is mandatory otherwise
--   it will emit an error.</li>
--   <li>The <a>else_</a> is also mandatory, unlike the SQL statement in
--   which if the <tt>ELSE</tt> is omitted it will return a <tt>NULL</tt>.
--   You can reproduce this via <a>nothing</a>.</li>
--   </ul>
case_ :: PersistField a => [(SqlExpr (Value Bool), SqlExpr (Value a))] -> SqlExpr (Value a) -> SqlExpr (Value a)

-- | Convert an entity's key into another entity's.
--   
--   This function is to be used when you change an entity's <tt>Id</tt> to
--   be that of another entity. For example:
--   
--   <pre>
--   Bar
--     barNum Int
--   Foo
--     bar BarId
--     fooNum Int
--     Primary bar
--   </pre>
--   
--   In this example, Bar is said to be the BaseEnt(ity), and Foo the
--   child. To model this in Esqueleto, declare:
--   
--   <pre>
--   instance ToBaseId Foo where
--     type BaseEnt Foo = Bar
--     toBaseIdWitness barId = FooKey barId
--   </pre>
--   
--   Now you're able to write queries such as:
--   
--   <pre>
--   <a>select</a> $
--   <a>from</a> $ (bar `<tt>InnerJoin</tt>` foo) -&gt; do
--   <a>on</a> (<a>toBaseId</a> (foo <a>^.</a> FooId) <a>==.</a> bar <a>^.</a> BarId)
--   return (bar, foo)
--   </pre>
--   
--   Note: this function may be unsafe to use in conditions not like the
--   one of the example above.
toBaseId :: ToBaseId ent => SqlExpr (Value (Key ent)) -> SqlExpr (Value (Key (BaseEnt ent)))

-- | The inverse of <a>toBaseId</a>. Note that this is somewhat less "safe"
--   than <a>toBaseId</a>. Calling <a>toBaseId</a> will usually mean that a
--   foreign key constraint is present that guarantees the presence of the
--   base ID. <a>fromBaseId</a> has no such guarantee. Consider the code
--   example given in <a>toBaseId</a>:
--   
--   <pre>
--   Bar
--     barNum Int
--   Foo
--     bar BarId
--     fooNum Int
--     Primary bar
--   </pre>
--   
--   <pre>
--   instance ToBaseId Foo where
--     type BaseEnt Foo = Bar
--     toBaseIdWitness barId = FooKey barId
--   </pre>
--   
--   The type of <a>toBaseId</a> for <tt>Foo</tt> would be:
--   
--   <pre>
--   toBaseId :: SqlExpr (Value FooId) -&gt; SqlExpr (Value BarId)
--   </pre>
--   
--   The foreign key constraint on <tt>Foo</tt> means that every
--   <tt>FooId</tt> points to a <tt>BarId</tt> in the database. However,
--   <a>fromBaseId</a> will not have this:
--   
--   <pre>
--   fromBaseId :: SqlExpr (Value BarId) -&gt; SqlExpr (Value FooId)
--   </pre>
fromBaseId :: ToBaseId ent => SqlExpr (Value (Key (BaseEnt ent))) -> SqlExpr (Value (Key ent))

-- | As <a>fromBaseId</a>, but works on <a>Maybe</a> keys.
fromBaseIdMaybe :: ToBaseId ent => SqlExpr (Value (Maybe (Key (BaseEnt ent)))) -> SqlExpr (Value (Maybe (Key ent)))

-- | Like <a>toBaseId</a>, but works on <a>Maybe</a> keys.
toBaseIdMaybe :: ToBaseId ent => SqlExpr (Value (Maybe (Key ent))) -> SqlExpr (Value (Maybe (Key (BaseEnt ent))))

-- | Execute a subquery <tt>SELECT</tt> in a <a>SqlExpr</a>. The query
--   passed to this function will only return a single result - it has a
--   <tt>LIMIT 1</tt> passed in to the query to make it safe, and the
--   return type is <a>Maybe</a> to indicate that the subquery might result
--   in 0 rows.
--   
--   If you find yourself writing <tt><a>joinV</a> . <a>subSelect</a></tt>,
--   then consider using <a>subSelectMaybe</a>.
--   
--   If you're performing a <a>countRows</a>, then you can use
--   <a>subSelectCount</a> which is safe.
--   
--   If you know that the subquery will always return exactly one row (eg a
--   foreign key constraint guarantees that you'll get exactly one row),
--   then consider <a>subSelectUnsafe</a>, along with a comment explaining
--   why it is safe.
subSelect :: (PersistField a, NullableFieldProjection a a') => SqlQuery (SqlExpr (Value a)) -> SqlExpr (Value (Maybe a'))

-- | Execute a subquery <tt>SELECT</tt> in a <a>SqlExpr</a>. This function
--   is a shorthand for the common <tt><a>joinV</a> . <a>subSelect</a></tt>
--   idiom, where you are calling <a>subSelect</a> on an expression that
--   would be <a>Maybe</a> already.
--   
--   As an example, you would use this function when calling <a>sum_</a> or
--   <a>max_</a>, which have <a>Maybe</a> in the result type (for a 0 row
--   query).
subSelectMaybe :: PersistField a => SqlQuery (SqlExpr (Value (Maybe a))) -> SqlExpr (Value (Maybe a))

-- | Performs a <tt>COUNT</tt> of the given query in a <tt>subSelect</tt>
--   manner. This is always guaranteed to return a result value, and is
--   completely safe.
subSelectCount :: (Num a, PersistField a) => SqlQuery ignored -> SqlExpr (Value a)

-- | Performs a sub-select using the given foreign key on the entity. This
--   is useful to extract values that are known to be present by the
--   database schema.
--   
--   As an example, consider the following persistent definition:
--   
--   <pre>
--   User
--     profile ProfileId
--   
--   Profile
--     name    Text
--   </pre>
--   
--   The following query will return the name of the user.
--   
--   <pre>
--   getUserWithName =
--       <a>select</a> $
--       <a>from</a> $ user -&gt;
--       <a>pure</a> (user, <a>subSelectForeign</a> user UserProfile (^. ProfileName)
--   </pre>
subSelectForeign :: (BackendCompatible SqlBackend (PersistEntityBackend val1), PersistEntity val1, PersistEntity val2, PersistField a) => SqlExpr (Entity val2) -> EntityField val2 (Key val1) -> (SqlExpr (Entity val1) -> SqlExpr (Value a)) -> SqlExpr (Value a)

-- | Execute a subquery <tt>SELECT</tt> in a <a>SqlExpr</a> that returns a
--   list. This is an alias for <a>subList_select</a> and is provided for
--   symmetry with the other safe subselect functions.
subSelectList :: PersistField a => SqlQuery (SqlExpr (Value a)) -> SqlExpr (ValueList a)

-- | Execute a subquery <tt>SELECT</tt> in a <a>SqlExpr</a>. This function
--   is unsafe, because it can throw runtime exceptions in two cases:
--   
--   <ol>
--   <li>If the query passed has 0 result rows, then it will return a
--   <tt>NULL</tt> value. The <tt>persistent</tt> parsing operations will
--   fail on an unexpected <tt>NULL</tt>.</li>
--   <li>If the query passed returns more than one row, then the SQL engine
--   will fail with an error like "More than one row returned by a subquery
--   used as an expression".</li>
--   </ol>
--   
--   This function is safe if you guarantee that exactly one row will be
--   returned, or if the result already has a <a>Maybe</a> type for some
--   reason.
--   
--   For variants with the safety encoded already, see <a>subSelect</a> and
--   <a>subSelectMaybe</a>. For the most common safe use of this, see
--   <a>subSelectCount</a>.
subSelectUnsafe :: PersistField a => SqlQuery (SqlExpr (Value a)) -> SqlExpr (Value a)

-- | Class that enables one to use <a>toBaseId</a> to convert an entity's
--   key on a query into another (cf. <a>toBaseId</a>).
class ToBaseId ent where {
    
    -- | e.g. <tt>type BaseEnt MyBase = MyChild</tt>
    type BaseEnt ent;
}

-- | Convert from the key of the BaseEnt(ity) to the key of the child
--   entity. This function is not actually called, but that it typechecks
--   proves this operation is safe.
toBaseIdWitness :: ToBaseId ent => Key (BaseEnt ent) -> Key ent

-- | Syntax sugar for <a>case_</a>.
when_ :: expr (Value Bool) -> () -> expr a -> (expr (Value Bool), expr a)

-- | Syntax sugar for <a>case_</a>.
then_ :: ()

-- | Syntax sugar for <a>case_</a>.
else_ :: expr a -> expr a

-- | <tt>FROM</tt> clause: bring entities into scope.
--   
--   Note that this function will be replaced by the one in
--   <a>Database.Esqueleto.Experimental</a> in version 4.0.0.0 of the
--   library. The <tt>Experimental</tt> module has a dramatically improved
--   means for introducing tables and entities that provides more power and
--   less potential for runtime errors.
--   
--   This function internally uses two type classes in order to provide
--   some flexibility of how you may call it. Internally we refer to these
--   type classes as the two different magics.
--   
--   The innermost magic allows you to use <tt>from</tt> with the following
--   types:
--   
--   <ul>
--   <li><tt>expr (Entity val)</tt>, which brings a single entity into
--   scope.</li>
--   <li><tt>expr (Maybe (Entity val))</tt>, which brings a single entity
--   that may be <tt>NULL</tt> into scope. Used for <tt>OUTER
--   JOIN</tt>s.</li>
--   <li>A <tt>JOIN</tt> of any other two types allowed by the innermost
--   magic, where a <tt>JOIN</tt> may be an <a>InnerJoin</a>, a
--   <a>CrossJoin</a>, a <a>LeftOuterJoin</a>, a <a>RightOuterJoin</a>, or
--   a <a>FullOuterJoin</a>. The <tt>JOINs</tt> have left fixity.</li>
--   </ul>
--   
--   The outermost magic allows you to use <tt>from</tt> on any tuples of
--   types supported by innermost magic (and also tuples of tuples, and so
--   on), up to 8-tuples.
--   
--   Note that using <tt>from</tt> for the same entity twice does work and
--   corresponds to a self-join. You don't even need to use two different
--   calls to <tt>from</tt>, you may use a <tt>JOIN</tt> or a tuple.
--   
--   The following are valid examples of uses of <tt>from</tt> (the types
--   of the arguments of the lambda are inside square brackets):
--   
--   <pre>
--   <a>from</a> $ \person -&gt; ...
--   <a>from</a> $ \(person, blogPost) -&gt; ...
--   <a>from</a> $ \(p `<a>LeftOuterJoin</a>` mb) -&gt; ...
--   <a>from</a> $ \(p1 `<a>InnerJoin</a>` f `<a>InnerJoin</a>` p2) -&gt; ...
--   <a>from</a> $ \((p1 `<a>InnerJoin</a>` f) `<a>InnerJoin</a>` p2) -&gt; ...
--   </pre>
--   
--   The types of the arguments to the lambdas above are, respectively:
--   
--   <pre>
--   person
--     :: ( Esqueleto query expr backend
--        , PersistEntity Person
--        , PersistEntityBackend Person ~ backend
--        ) =&gt; expr (Entity Person)
--   (person, blogPost)
--     :: (...) =&gt; (expr (Entity Person), expr (Entity BlogPost))
--   (p `<a>LeftOuterJoin</a>` mb)
--     :: (...) =&gt; InnerJoin (expr (Entity Person)) (expr (Maybe (Entity BlogPost)))
--   (p1 `<a>InnerJoin</a>` f `<a>InnerJoin</a>` p2)
--     :: (...) =&gt; InnerJoin
--                   (InnerJoin (expr (Entity Person))
--                              (expr (Entity Follow)))
--                   (expr (Entity Person))
--   (p1 `<a>InnerJoin</a>` (f `<a>InnerJoin</a>` p2)) ::
--     :: (...) =&gt; InnerJoin
--                   (expr (Entity Person))
--                   (InnerJoin (expr (Entity Follow))
--                              (expr (Entity Person)))
--   </pre>
--   
--   Note that some backends may not support all kinds of <tt>JOIN</tt>s.
from :: From a => (a -> SqlQuery b) -> SqlQuery b

-- | A single value (as opposed to a whole entity). You may use
--   <tt>(<a>^.</a>)</tt> or <tt>(<a>?.</a>)</tt> to get a <a>Value</a>
--   from an <a>Entity</a>.
newtype Value a
Value :: a -> Value a
[unValue] :: Value a -> a

-- | A list of single values. There's a limited set of functions able to
--   work with this data type (such as <a>subList_select</a>,
--   <a>valList</a>, <a>in_</a> and <a>exists</a>).
newtype ValueList a
ValueList :: a -> ValueList a

-- | Phantom type used by <a>orderBy</a>, <a>asc</a> and <a>desc</a>.
data OrderBy

-- | Phantom type used by <a>distinctOn</a> and <a>don</a>.
data DistinctOn

-- | Different kinds of locking clauses supported by <a>locking</a>.
--   
--   Note that each RDBMS has different locking support. The constructors
--   of this datatype specify only the <i>syntax</i> of the locking
--   mechanism, not its <i>semantics</i>. For example, even though both
--   MySQL and PostgreSQL support <a>ForUpdate</a>, there are no guarantees
--   that they will behave the same.
data LockingKind

-- | <tt>FOR UPDATE</tt> syntax. Supported by MySQL, Oracle and PostgreSQL.

-- | <i>Deprecated: The constructors for <a>LockingKind</a> are deprecated
--   in v3.6.0.0. Instead, please refer to the smart constructors
--   <a>forUpdate</a> and <a>forUpdateSkipLocked</a>.</i>
ForUpdate :: LockingKind

-- | <tt>FOR UPDATE SKIP LOCKED</tt> syntax. Supported by MySQL, Oracle and
--   PostgreSQL.

-- | <i>Deprecated: The constructors for <a>LockingKind</a> are deprecated
--   in v3.6.0.0. Instead, please refer to the smart constructors
--   <a>forUpdate</a> and <a>forUpdateSkipLocked</a>.</i>
ForUpdateSkipLocked :: LockingKind

-- | <tt>FOR SHARE</tt> syntax. Supported by PostgreSQL.

-- | <i>Deprecated: The constructors for <a>LockingKind</a> are deprecated
--   in v3.6.0.0. Instead, please refer to the smart constructor
--   <tt>forShare</tt> exported from Database.Esqueleto.PostgreSQL.</i>
ForShare :: LockingKind

-- | <tt>LOCK IN SHARE MODE</tt> syntax. Supported by MySQL.

-- | <i>Deprecated: The constructors for <a>LockingKind</a> are deprecated
--   in v3.6.0.0. Instead, please refer to the smart constructors
--   <tt>lockInShareMode</tt> exported from Database.Esqueleto.MySQL.</i>
LockInShareMode :: LockingKind

-- | <tt>FOR UPDATE</tt> syntax.
--   
--   Usage:
--   
--   <pre>
--   <a>locking</a> <a>forUpdate</a>
--   </pre>
forUpdate :: LockingKind

-- | <tt>FOR UPDATE SKIP LOCKED</tt> syntax.
--   
--   <pre>
--   <a>locking</a> <a>forUpdateSkipLocked</a>
--   </pre>
forUpdateSkipLocked :: LockingKind

-- | Lockable entity
--   
--   Example use:
--   
--   <pre>
--   select $ do
--       (p :&amp; bp) &lt;- from $
--           table <tt>Person
--           <tt>innerJoin</tt> table </tt>BlogPost
--               <a>on</a> do
--                   (p :&amp; bp) -&gt; p ^. PersonId ==. b ^. BlogPostAuthorId
--       forUpdateOf (p :&amp; b) skipLocked
--       return p
--   </pre>
class LockableEntity a
flattenLockableEntity :: LockableEntity a => a -> NonEmpty LockableSqlExpr

-- | Phantom class of data types that are treated as strings by the RDBMS.
--   It has no methods because it's only used to avoid type errors such as
--   trying to concatenate integers.
--   
--   If you have a custom data type or <tt>newtype</tt>, feel free to make
--   it an instance of this class.
class PersistField a => SqlString a

-- | Data type that represents an <tt>INNER JOIN</tt> (see
--   <a>LeftOuterJoin</a> for an example).
data InnerJoin a b
InnerJoin :: a -> b -> InnerJoin a b
infixl 2 `InnerJoin`
infixl 2 `InnerJoin`

-- | Data type that represents a <tt>CROSS JOIN</tt> (see
--   <a>LeftOuterJoin</a> for an example).
data CrossJoin a b
CrossJoin :: a -> b -> CrossJoin a b
infixl 2 `CrossJoin`
infixl 2 `CrossJoin`

-- | Data type that represents a <tt>LEFT OUTER JOIN</tt>. For example,
--   
--   <pre>
--   select $
--   <a>from</a> $ \(person `<tt>LeftOuterJoin</tt>` pet) -&gt;
--     ...
--   </pre>
--   
--   is translated into
--   
--   <pre>
--   SELECT ...
--   FROM Person LEFT OUTER JOIN Pet
--   ...
--   </pre>
--   
--   See also: <a>from</a>.
data LeftOuterJoin a b
LeftOuterJoin :: a -> b -> LeftOuterJoin a b
infixl 2 `LeftOuterJoin`
infixl 2 `LeftOuterJoin`

-- | Data type that represents a <tt>RIGHT OUTER JOIN</tt> (see
--   <a>LeftOuterJoin</a> for an example).
data RightOuterJoin a b
RightOuterJoin :: a -> b -> RightOuterJoin a b
infixl 2 `RightOuterJoin`
infixl 2 `RightOuterJoin`

-- | Data type that represents a <tt>FULL OUTER JOIN</tt> (see
--   <a>LeftOuterJoin</a> for an example).
data FullOuterJoin a b
FullOuterJoin :: a -> b -> FullOuterJoin a b
infixl 2 `FullOuterJoin`
infixl 2 `FullOuterJoin`

-- | (Internal) A kind of <tt>JOIN</tt>.
data JoinKind

-- | <pre>
--   INNER JOIN
--   </pre>
InnerJoinKind :: JoinKind

-- | <pre>
--   CROSS JOIN
--   </pre>
CrossJoinKind :: JoinKind

-- | <pre>
--   LEFT OUTER JOIN
--   </pre>
LeftOuterJoinKind :: JoinKind

-- | <pre>
--   RIGHT OUTER JOIN
--   </pre>
RightOuterJoinKind :: JoinKind

-- | <pre>
--   FULL OUTER JOIN
--   </pre>
FullOuterJoinKind :: JoinKind

-- | Exception thrown whenever <a>on</a> is used to create an <tt>ON</tt>
--   clause but no matching <tt>JOIN</tt> is found.
data OnClauseWithoutMatchingJoinException
OnClauseWithoutMatchingJoinException :: String -> OnClauseWithoutMatchingJoinException

-- | SQL backend for <tt>esqueleto</tt> using <a>SqlPersistT</a>.
data SqlQuery a

-- | An expression on the SQL backend.
--   
--   Raw expression: Contains a <a>SqlExprMeta</a> and a function for
--   building the expr. It recieves a parameter telling it whether it is in
--   a parenthesized context, and takes information about the SQL
--   connection (mainly for escaping names) and returns both an string
--   (<a>Builder</a>) and a list of values to be interpolated by the SQL
--   backend.
data SqlExpr a

-- | Constraint synonym for <tt>persistent</tt> entities whose backend is
--   <a>SqlBackend</a>.
type SqlEntity ent = (PersistEntity ent, PersistEntityBackend ent ~ SqlBackend)

-- | Execute an <tt>esqueleto</tt> <tt>SELECT</tt> query inside
--   <tt>persistent</tt>'s <a>SqlPersistT</a> monad and return a list of
--   rows.
--   
--   We've seen that <a>from</a> has some magic about which kinds of things
--   you may bring into scope. This <a>select</a> function also has some
--   magic for which kinds of things you may bring back to Haskell-land by
--   using <tt>SqlQuery</tt>'s <tt>return</tt>:
--   
--   <ul>
--   <li>You may return a <tt>SqlExpr (<a>Entity</a> v)</tt> for an entity
--   <tt>v</tt> (i.e., like the <tt>*</tt> in SQL), which is then returned
--   to Haskell-land as just <tt>Entity v</tt>.</li>
--   <li>You may return a <tt>SqlExpr (Maybe (Entity v))</tt> for an entity
--   <tt>v</tt> that may be <tt>NULL</tt>, which is then returned to
--   Haskell-land as <tt>Maybe (Entity v)</tt>. Used for <tt>OUTER
--   JOIN</tt>s.</li>
--   <li>You may return a <tt>SqlExpr (<a>Value</a> t)</tt> for a value
--   <tt>t</tt> (i.e., a single column), where <tt>t</tt> is any instance
--   of <a>PersistField</a>, which is then returned to Haskell-land as
--   <tt>Value t</tt>. You may use <tt>Value</tt> to return projections of
--   an <tt>Entity</tt> (see <tt>(<a>^.</a>)</tt> and <tt>(<a>?.</a>)</tt>)
--   or to return any other value calculated on the query (e.g.,
--   <a>countRows</a> or <a>subSelect</a>).</li>
--   </ul>
--   
--   The <tt>SqlSelect a r</tt> class has functional dependencies that
--   allow type information to flow both from <tt>a</tt> to <tt>r</tt> and
--   vice-versa. This means that you'll almost never have to give any type
--   signatures for <tt>esqueleto</tt> queries. For example, the query
--   <tt><a>select</a> $ from $ \p -&gt; return p</tt> alone is ambiguous,
--   but in the context of
--   
--   <pre>
--   do ps &lt;- <a>select</a> $
--            <a>from</a> $ \p -&gt;
--            return p
--      liftIO $ mapM_ (putStrLn . personName . entityVal) ps
--   </pre>
--   
--   we are able to infer from that single <tt>personName . entityVal</tt>
--   function composition that the <tt>p</tt> inside the query is of type
--   <tt>SqlExpr (Entity Person)</tt>.
select :: forall a r (m :: Type -> Type) backend. (SqlSelect a r, MonadIO m, SqlBackendCanRead backend) => SqlQuery a -> ReaderT backend m [r]

-- | Execute an <tt>esqueleto</tt> <tt>SELECT</tt> query inside
--   <tt>persistent</tt>'s <a>SqlPersistT</a> monad and return the first
--   entry wrapped in a <tt>Maybe</tt>. @since 3.5.1.0
--   
--   <h3><b>Example usage</b></h3>
--   
--   <pre>
--   firstPerson :: MonadIO m =&gt; SqlPersistT m (Maybe (Entity Person))
--   firstPerson =
--    <a>selectOne</a> $ do
--        person &lt;- <a>from</a> $ <tt>table</tt> @Person
--        return person
--   </pre>
--   
--   The above query is equivalent to a <a>select</a> combined with
--   <a>limit</a> but you would still have to transform the results from a
--   list:
--   
--   <pre>
--   firstPerson :: MonadIO m =&gt; SqlPersistT m [Entity Person]
--   firstPerson =
--    <a>select</a> $ do
--        person &lt;- <a>from</a> $ <tt>table</tt> @Person
--        <a>limit</a> 1
--        return person
--   </pre>
selectOne :: forall a r (m :: Type -> Type) backend. (SqlSelect a r, MonadIO m, SqlBackendCanRead backend) => SqlQuery a -> ReaderT backend m (Maybe r)

-- | Execute an <tt>esqueleto</tt> <tt>SELECT</tt> query inside
--   <tt>persistent</tt>'s <a>SqlPersistT</a> monad and return a
--   <a>Source</a> of rows.
selectSource :: forall a r backend (m :: Type -> Type). (SqlSelect a r, BackendCompatible SqlBackend backend, IsPersistBackend backend, PersistQueryRead backend, PersistStoreRead backend, PersistUniqueRead backend, MonadResource m) => SqlQuery a -> ConduitT () r (ReaderT backend m) ()

-- | Execute an <tt>esqueleto</tt> <tt>DELETE</tt> query inside
--   <tt>persistent</tt>'s <a>SqlPersistT</a> monad. Note that currently
--   there are no type checks for statements that should not appear on a
--   <tt>DELETE</tt> query.
--   
--   Example of usage:
--   
--   <pre>
--   <a>delete</a> $
--   <a>from</a> $ \appointment -&gt;
--   <a>where_</a> (appointment <a>^.</a> AppointmentDate <a>&lt;.</a> <a>val</a> now)
--   </pre>
--   
--   Unlike <a>select</a>, there is a useful way of using <a>delete</a>
--   that will lead to type ambiguities. If you want to delete all rows
--   (i.e., no <a>where_</a> clause), you'll have to use a type signature:
--   
--   <pre>
--   <a>delete</a> $
--   <a>from</a> $ \(appointment :: <a>SqlExpr</a> (<a>Entity</a> Appointment)) -&gt;
--   return ()
--   </pre>
--   
--   <h4><a>Database.Esqueleto.Experimental</a>:</h4>
--   
--   <pre>
--   delete $ do
--     userFeature &lt;- from $ table @UserFeature
--     where_ ((userFeature ^. UserFeatureFeature) <a>notIn</a> valList allKnownFeatureFlags)
--   </pre>
delete :: forall (m :: Type -> Type) backend. (MonadIO m, SqlBackendCanWrite backend) => SqlQuery () -> ReaderT backend m ()

-- | Same as <a>delete</a>, but returns the number of rows affected.
deleteCount :: forall (m :: Type -> Type) backend. (MonadIO m, SqlBackendCanWrite backend) => SqlQuery () -> ReaderT backend m Int64

-- | Execute an <tt>esqueleto</tt> <tt>UPDATE</tt> query inside
--   <tt>persistent</tt>'s <a>SqlPersistT</a> monad. Note that currently
--   there are no type checks for statements that should not appear on a
--   <tt>UPDATE</tt> query.
--   
--   Example of usage:
--   
--   <pre>
--   <a>update</a> $ \p -&gt; do
--   <a>set</a> p [ PersonAge <a>=.</a> <a>just</a> (<a>val</a> thisYear) -. p <a>^.</a> PersonBorn ]
--   <a>where_</a> $ isNothing (p <a>^.</a> PersonAge)
--   </pre>
update :: forall (m :: Type -> Type) val backend. (MonadIO m, PersistEntity val, BackendCompatible SqlBackend (PersistEntityBackend val), SqlBackendCanWrite backend) => (SqlExpr (Entity val) -> SqlQuery ()) -> ReaderT backend m ()

-- | Same as <a>update</a>, but returns the number of rows affected.
updateCount :: forall (m :: Type -> Type) val backend. (MonadIO m, PersistEntity val, BackendCompatible SqlBackend (PersistEntityBackend val), SqlBackendCanWrite backend) => (SqlExpr (Entity val) -> SqlQuery ()) -> ReaderT backend m Int64

-- | Insert a <a>PersistField</a> for every selected value.
insertSelect :: forall (m :: Type -> Type) a backend. (MonadIO m, PersistEntity a, SqlBackendCanWrite backend) => SqlQuery (SqlExpr (Insertion a)) -> ReaderT backend m ()

-- | Insert a <a>PersistField</a> for every selected value, return the
--   count afterward
insertSelectCount :: forall (m :: Type -> Type) a backend. (MonadIO m, PersistEntity a, SqlBackendCanWrite backend) => SqlQuery (SqlExpr (Insertion a)) -> ReaderT backend m Int64

-- | Apply a <a>PersistField</a> constructor to <tt>SqlExpr Value</tt>
--   arguments.
(<#) :: (a -> b) -> SqlExpr (Value a) -> SqlExpr (Insertion b)

-- | Apply extra <tt>SqlExpr Value</tt> arguments to a <a>PersistField</a>
--   constructor
(<&>) :: SqlExpr (Insertion (a -> b)) -> SqlExpr (Value a) -> SqlExpr (Insertion b)

-- | Renders a <a>SqlQuery</a> into a <a>Text</a> value along with the list
--   of <a>PersistValue</a>s that would be supplied to the database for
--   <tt>?</tt> placeholders.
--   
--   You must ensure that the <a>Mode</a> you pass to this function
--   corresponds with the actual <a>SqlQuery</a>. If you pass a query that
--   uses incompatible features (like an <tt>INSERT</tt> statement with a
--   <tt>SELECT</tt> mode) then you'll get a weird result.
renderQueryToText :: forall a r backend (m :: Type -> Type). (SqlSelect a r, BackendCompatible SqlBackend backend, Monad m) => Mode -> SqlQuery a -> ReaderT backend m (Text, [PersistValue])

-- | Renders a <a>SqlQuery</a> into a <a>Text</a> value along with the list
--   of <a>PersistValue</a>s that would be supplied to the database for
--   <tt>?</tt> placeholders.
renderQuerySelect :: forall a r backend (m :: Type -> Type). (SqlSelect a r, BackendCompatible SqlBackend backend, Monad m) => SqlQuery a -> ReaderT backend m (Text, [PersistValue])

-- | Renders a <a>SqlQuery</a> into a <a>Text</a> value along with the list
--   of <a>PersistValue</a>s that would be supplied to the database for
--   <tt>?</tt> placeholders.
renderQueryUpdate :: forall a r backend (m :: Type -> Type). (SqlSelect a r, BackendCompatible SqlBackend backend, Monad m) => SqlQuery a -> ReaderT backend m (Text, [PersistValue])

-- | Renders a <a>SqlQuery</a> into a <a>Text</a> value along with the list
--   of <a>PersistValue</a>s that would be supplied to the database for
--   <tt>?</tt> placeholders.
renderQueryDelete :: forall a r backend (m :: Type -> Type). (SqlSelect a r, BackendCompatible SqlBackend backend, Monad m) => SqlQuery a -> ReaderT backend m (Text, [PersistValue])

-- | Renders a <a>SqlQuery</a> into a <a>Text</a> value along with the list
--   of <a>PersistValue</a>s that would be supplied to the database for
--   <tt>?</tt> placeholders.
renderQueryInsertInto :: forall a r backend (m :: Type -> Type). (SqlSelect a r, BackendCompatible SqlBackend backend, Monad m) => SqlQuery a -> ReaderT backend m (Text, [PersistValue])

-- | (Internal) Class that implements the tuple <a>from</a> magic (see
--   <a>fromStart</a>).
class From a

-- | <tt>valkey i = <a>val</a> . <a>toSqlKey</a></tt>
--   (<a>https://github.com/prowdsponsor/esqueleto/issues/9</a>).
valkey :: (ToBackendKey SqlBackend entity, PersistField (Key entity)) => Int64 -> SqlExpr (Value (Key entity))

-- | <tt>valJ</tt> is like <tt>val</tt> but for something that is already a
--   <tt>Value</tt>. The use case it was written for was, given a
--   <tt>Value</tt> lift the <tt>Key</tt> for that <tt>Value</tt> into the
--   query expression in a type safe way. However, the implementation is
--   more generic than that so we call it <tt>valJ</tt>.
--   
--   Its important to note that the input entity and the output entity are
--   constrained to be the same by the type signature on the function
--   (<a>https://github.com/prowdsponsor/esqueleto/pull/69</a>).
valJ :: PersistField (Key entity) => Value (Key entity) -> SqlExpr (Value (Key entity))

-- | Avoid N+1 queries and join entities into a map structure.
--   
--   This function is useful to call on the result of a single
--   <tt>JOIN</tt>. For example, suppose you have this query:
--   
--   <pre>
--   getFoosAndNestedBarsFromParent
--       :: ParentId
--       -&gt; SqlPersistT IO [(Entity Foo, Maybe (Entity Bar))]
--   getFoosAndNestedBarsFromParent parentId =
--       <a>select</a> $ do
--           (foo :&amp; bar) &lt;- from $
--               table <tt>Foo
--               <a>`LeftOuterJoin`</a>
--               table </tt>Bar
--                   <a>`on`</a> do
--                       \(foo :&amp; bar) -&gt;
--                           foo ^. FooId ==. bar ?. BarFooId
--           where_ $
--               foo ^. FooParentId ==. val parentId
--           pure (foo, bar)
--   </pre>
--   
--   This is a natural result type for SQL - a list of tuples. However,
--   it's not what we usually want in Haskell - each <tt>Foo</tt> in the
--   list will be represented multiple times, once for each <tt>Bar</tt>.
--   
--   We can write <tt><a>fmap</a> <a>associateJoin</a></tt> and it will
--   translate it into a <tt>Map</tt> that is keyed on the <a>Key</a> of
--   the left <a>Entity</a>, and the value is a tuple of the entity's value
--   as well as the list of each coresponding entity.
--   
--   <pre>
--   getFoosAndNestedBarsFromParentHaskellese
--       :: ParentId
--       -&gt; SqlPersistT (Map (Key Foo) (Foo, [Maybe (Entity Bar)]))
--   getFoosAndNestedBarsFromParentHaskellese parentId =
--       <a>fmap</a> <a>associateJoin</a> $ getFoosdAndNestedBarsFromParent parentId
--   </pre>
--   
--   What if you have multiple joins?
--   
--   Let's use <a>associateJoin</a> with a *two* join query.
--   
--   <pre>
--   userPostComments
--       :: SqlQuery (SqlExpr (Entity User, Entity Post, Entity Comment))
--   userPostsComment = do
--       (u :&amp; p :&amp; c) &lt;- from $
--           table <tt>User
--           <a>`InnerJoin`</a>
--           table </tt>Post
--               <a>on</a> do
--                   \(u :&amp; p) -&gt;
--                       u ^. UserId ==. p ^. PostUserId
--           <a>`InnerJoin`</a>
--           table @Comment
--               <a>`on`</a> do
--                   \(_ :&amp; p :&amp; c) -&gt;
--                       p ^. PostId ==. c ^. CommentPostId
--       pure (u, p, c)
--   </pre>
--   
--   This query returns a User, with all of the users Posts, and then all
--   of the Comments on that post.
--   
--   First, we *nest* the tuple.
--   
--   <pre>
--   nest :: (a, b, c) -&gt; (a, (b, c))
--   nest (a, b, c) = (a, (b, c))
--   </pre>
--   
--   This makes the return of the query conform to the input expected from
--   <a>associateJoin</a>.
--   
--   <pre>
--   nestedUserPostComments
--       :: SqlPersistT IO [(Entity User, (Entity Post, Entity Comment))]
--   nestedUserPostComments =
--       fmap nest $ select userPostsComments
--   </pre>
--   
--   Now, we can call <a>associateJoin</a> on it.
--   
--   <pre>
--   associateUsers
--       :: [(Entity User, (Entity Post, Entity Comment))]
--       -&gt; Map UserId (User, [(Entity Post, Entity Comment)])
--   associateUsers =
--       associateJoin
--   </pre>
--   
--   Next, we'll use the <a>Functor</a> instances for <tt>Map</tt> and
--   tuple to call <a>associateJoin</a> on the <tt>[(Entity Post, Entity
--   Comment)]</tt>.
--   
--   <pre>
--   associatePostsAndComments
--       :: Map UserId (User, [(Entity Post, Entity Comment)])
--       -&gt; Map UserId (User, Map PostId (Post, [Entity Comment]))
--   associatePostsAndComments =
--       fmap (fmap associateJoin)
--   </pre>
--   
--   For more reading on this topic, see <a>this Foxhound Systems blog
--   post</a>.
associateJoin :: forall e1 e0. Ord (Key e0) => [(Entity e0, e1)] -> Map (Key e0) (e0, [e1])

-- | Synonym for <a>delete</a> that does not clash with
--   <tt>esqueleto</tt>'s <a>delete</a>.
deleteKey :: forall backend val (m :: Type -> Type). (PersistStore backend, BaseBackend backend ~ PersistEntityBackend val, MonadIO m, PersistEntity val) => Key val -> ReaderT backend m ()

-- | Persistent serialized Haskell records to the database. A Database
--   <a>Entity</a> (A row in SQL, a document in MongoDB, etc) corresponds
--   to a <a>Key</a> plus a Haskell record.
--   
--   For every Haskell record type stored in the database there is a
--   corresponding <a>PersistEntity</a> 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 <a>PersistEntity</a>, with each query returning
--   different types of Haskell records.
--   
--   Some advanced type system capabilities are used to make this process
--   type-safe. Persistent users usually don't need to understand the class
--   associated data and functions.
class (PersistField Key record, ToJSON Key record, FromJSON Key record, Show Key record, Read Key record, Eq Key record, Ord Key record) => PersistEntity record where {
    
    -- | Persistent allows multiple different backends (databases).
    type PersistEntityBackend record;
    
    -- | By default, a backend will automatically generate the key Instead you
    --   can specify a Primary key made up of unique values.
    data Key record;
    
    -- | An <a>EntityField</a> is parameterised by the Haskell record it
    --   belongs to and the additional type of that field.
    --   
    --   As of <tt>persistent-2.11.0.0</tt>, it's possible to use the
    --   <tt>OverloadedLabels</tt> language extension to refer to
    --   <a>EntityField</a> values polymorphically. See the documentation on
    --   <a>SymbolToField</a> for more information.
    data EntityField record :: Type -> Type;
    
    -- | Unique keys besides the <a>Key</a>.
    data Unique record;
}

-- | A lower-level key operation.
keyToValues :: PersistEntity record => Key record -> [PersistValue]

-- | A lower-level key operation.
keyFromValues :: PersistEntity record => [PersistValue] -> Either Text (Key record)

-- | A meta-operation to retrieve the <a>Key</a> <a>EntityField</a>.
persistIdField :: PersistEntity record => EntityField record (Key record)

-- | Retrieve the <a>EntityDef</a> meta-data for the record.
entityDef :: PersistEntity record => proxy record -> EntityDef

-- | Return meta-data for a given <a>EntityField</a>.
persistFieldDef :: PersistEntity record => EntityField record typ -> FieldDef

-- | A meta-operation to get the database fields of a record.
toPersistFields :: PersistEntity record => record -> [PersistValue]

-- | A lower-level operation to convert from database values to a Haskell
--   record.
fromPersistValues :: PersistEntity record => [PersistValue] -> Either Text record

-- | This function allows you to build an <tt><a>Entity</a> a</tt> by
--   specifying an action that returns a value for the field in the
--   callback function. Let's look at an example.
--   
--   <pre>
--   parseFromEnvironmentVariables :: IO (Entity User)
--   parseFromEnvironmentVariables =
--       tabulateEntityA $ \userField -&gt;
--           case userField of
--               UserName -&gt;
--                   getEnv <a>USER_NAME</a>
--               UserAge -&gt; do
--                   ageVar &lt;- getEnv <a>USER_AGE</a>
--                   case readMaybe ageVar of
--                       Just age -&gt;
--                           pure age
--                       Nothing -&gt;
--                           error $ "Failed to parse Age from: " &lt;&gt; ageVar
--               UserAddressId -&gt; do
--                   addressVar &lt;- getEnv <a>USER_ADDRESS_ID</a>
--                   pure $ AddressKey addressVar
--   </pre>
tabulateEntityA :: (PersistEntity record, Applicative f) => (forall a. () => EntityField record a -> f a) -> f (Entity record)

-- | Like <a>tabulateEntityA</a>, but works with any <a>Apply</a> f. This
--   works because all entities have at least one field, and so we can
--   tabulate things into semigroup-like shapes instead.
tabulateEntityApply :: (PersistEntity record, Apply f) => (forall a. () => EntityField record a -> f a) -> f (Entity record)

-- | A meta operation to retrieve all the <a>Unique</a> keys.
persistUniqueKeys :: PersistEntity record => record -> [Unique record]

-- | A lower level operation.
persistUniqueToFieldNames :: PersistEntity record => Unique record -> NonEmpty (FieldNameHS, FieldNameDB)

-- | A lower level operation.
persistUniqueToValues :: PersistEntity record => Unique record -> [PersistValue]

-- | Use a <a>PersistField</a> as a lens.
fieldLens :: PersistEntity record => EntityField record field -> forall (f :: Type -> Type). Functor f => (field -> f field) -> Entity record -> f (Entity record)

-- | Extract a <tt><a>Key</a> record</tt> from a <tt>record</tt> value.
--   Currently, this is only defined for entities using the
--   <tt>Primary</tt> syntax for natural/composite keys. In a future
--   version of <tt>persistent</tt> which incorporates the ID directly into
--   the entity, this will always be Just.
keyFromRecordM :: PersistEntity record => Maybe (record -> Key record)

-- | By default, a backend will automatically generate the key Instead you
--   can specify a Primary key made up of unique values.
data family Key record
class (Show BackendKey backend, Read BackendKey backend, Eq BackendKey backend, Ord BackendKey backend, PersistStoreRead backend, PersistField BackendKey backend, ToJSON BackendKey backend, FromJSON BackendKey backend) => PersistStoreWrite backend

-- | Create a new record in the database, returning an automatically
--   created key (in SQL an auto-increment id).
--   
--   <h3><b>Example usage</b></h3>
--   
--   Using <a>schema-1</a> and <a>dataset-1</a>, let's insert a new user
--   <tt>John</tt>.
--   
--   <pre>
--   insertJohn :: MonadIO m =&gt; ReaderT SqlBackend m (Key User)
--   insertJohn = insert $ User "John" 30
--   </pre>
--   
--   <pre>
--   johnId &lt;- insertJohn
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will produce this:
--   
--   <pre>
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |40   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   |3    |John  |30   |
--   +-----+------+-----+
--   </pre>
insert :: forall record (m :: Type -> Type). (PersistStoreWrite backend, MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => record -> ReaderT backend m (Key record)

-- | Same as <a>insert</a>, but doesn't return a <tt>Key</tt>.
--   
--   <h3><b>Example usage</b></h3>
--   
--   with <a>schema-1</a> and <a>dataset-1</a>,
--   
--   <pre>
--   insertJohn :: MonadIO m =&gt; ReaderT SqlBackend m (Key User)
--   insertJohn = insert_ $ User "John" 30
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will produce this:
--   
--   <pre>
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |40   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   |3    |John  |30   |
--   +-----+------+-----+
--   </pre>
insert_ :: forall record (m :: Type -> Type). (PersistStoreWrite backend, MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => record -> ReaderT backend m ()

-- | Create multiple records in the database and return their <a>Key</a>s.
--   
--   If you don't need the inserted <a>Key</a>s, use <a>insertMany_</a>.
--   
--   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
--   <tt>mapM insert</tt>.
--   
--   <h3><b>Example usage</b></h3>
--   
--   with <a>schema-1</a> and <a>dataset-1</a>,
--   
--   <pre>
--   insertUsers :: MonadIO m =&gt; ReaderT SqlBackend m [Key User]
--   insertUsers = insertMany [User "John" 30, User "Nick" 32, User "Jane" 20]
--   </pre>
--   
--   <pre>
--   userIds &lt;- insertUsers
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will produce this:
--   
--   <pre>
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |40   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   |3    |John  |30   |
--   +-----+------+-----+
--   |4    |Nick  |32   |
--   +-----+------+-----+
--   |5    |Jane  |20   |
--   +-----+------+-----+
--   </pre>
insertMany :: forall record (m :: Type -> Type). (PersistStoreWrite backend, MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => [record] -> ReaderT backend m [Key record]

-- | Same as <a>insertMany</a>, but doesn't return any <a>Key</a>s.
--   
--   The MongoDB, PostgreSQL, SQLite and MySQL backends insert all records
--   in one database query.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>,
--   
--   <pre>
--   insertUsers_ :: MonadIO m =&gt; ReaderT SqlBackend m ()
--   insertUsers_ = insertMany_ [User "John" 30, User "Nick" 32, User "Jane" 20]
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will produce this:
--   
--   <pre>
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |40   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   |3    |John  |30   |
--   +-----+------+-----+
--   |4    |Nick  |32   |
--   +-----+------+-----+
--   |5    |Jane  |20   |
--   +-----+------+-----+
--   </pre>
insertMany_ :: forall record (m :: Type -> Type). (PersistStoreWrite backend, MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => [record] -> ReaderT backend m ()

-- | Same as <a>insertMany_</a>, but takes an <a>Entity</a> 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.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>,
--   
--   <pre>
--   insertUserEntityMany :: MonadIO m =&gt; ReaderT SqlBackend m ()
--   insertUserEntityMany = insertEntityMany [SnakeEntity, EvaEntity]
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will produce this:
--   
--   <pre>
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |40   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   |3    |Snake |38   |
--   +-----+------+-----+
--   |4    |Eva   |38   |
--   +-----+------+-----+
--   </pre>
insertEntityMany :: forall record (m :: Type -> Type). (PersistStoreWrite backend, MonadIO m, PersistRecordBackend record backend) => [Entity record] -> ReaderT backend m ()

-- | Create a new record in the database using the given key.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>,
--   
--   <pre>
--   insertAliceKey :: MonadIO m =&gt; Key User -&gt; ReaderT SqlBackend m ()
--   insertAliceKey key = insertKey key $ User "Alice" 20
--   </pre>
--   
--   <pre>
--   insertAliceKey $ UserKey {unUserKey = SqlBackendKey {unSqlBackendKey = 3}}
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will produce this:
--   
--   <pre>
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |40   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   |3    |Alice |20   |
--   +-----+------+-----+
--   </pre>
insertKey :: forall record (m :: Type -> Type). (PersistStoreWrite backend, MonadIO m, PersistRecordBackend record backend) => Key record -> record -> ReaderT backend m ()

-- | Put the record in the database with the given key. Unlike
--   <a>replace</a>, if a record with the given key does not exist then a
--   new record will be inserted.
--   
--   <h3><b>Example usage</b></h3>
--   
--   We try to explain <tt>upsertBy</tt> using <a>schema-1</a> and
--   <a>dataset-1</a>.
--   
--   First, we insert Philip to <a>dataset-1</a>.
--   
--   <pre>
--   insertPhilip :: MonadIO m =&gt; ReaderT SqlBackend m (Key User)
--   insertPhilip = insert $ User "Philip" 42
--   </pre>
--   
--   <pre>
--   philipId &lt;- insertPhilip
--   </pre>
--   
--   This query will produce:
--   
--   <pre>
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |40   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   |3    |Philip|42   |
--   +-----+------+-----+
--   </pre>
--   
--   <pre>
--   repsertHaskell :: MonadIO m =&gt; Key record -&gt; ReaderT SqlBackend m ()
--   repsertHaskell id = repsert id $ User "Haskell" 81
--   </pre>
--   
--   <pre>
--   repsertHaskell philipId
--   </pre>
--   
--   This query will replace Philip's record with Haskell's one:
--   
--   <pre>
--   +-----+-----------------+--------+
--   |id   |name             |age     |
--   +-----+-----------------+--------+
--   |1    |SPJ              |40      |
--   +-----+-----------------+--------+
--   |2    |Simon            |41      |
--   +-----+-----------------+--------+
--   |3    |Philip -&gt; Haskell|42 -&gt; 81|
--   +-----+-----------------+--------+
--   </pre>
--   
--   <a>repsert</a> inserts the given record if the key doesn't exist.
--   
--   <pre>
--   repsertXToUnknown :: MonadIO m =&gt; ReaderT SqlBackend m ()
--   repsertXToUnknown = repsert unknownId $ User "X" 999
--   </pre>
--   
--   For example, applying the above query to <a>dataset-1</a> will produce
--   this:
--   
--   <pre>
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |40   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   |3    |X     |999  |
--   +-----+------+-----+
--   </pre>
repsert :: forall record (m :: Type -> Type). (PersistStoreWrite backend, MonadIO m, PersistRecordBackend record backend) => Key record -> record -> ReaderT backend m ()

-- | Put many entities into the database.
--   
--   Batch version of <a>repsert</a> for SQL backends.
--   
--   Useful when migrating data from one entity to another and want to
--   preserve ids.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>,
--   
--   <pre>
--   repsertManyUsers :: MonadIO m =&gt;ReaderT SqlBackend m ()
--   repsertManyusers = repsertMany [(simonId, User "Philip" 20), (unknownId999, User "Mr. X" 999)]
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will produce this:
--   
--   <pre>
--   +-----+----------------+---------+
--   |id   |name            |age      |
--   +-----+----------------+---------+
--   |1    |SPJ             |40       |
--   +-----+----------------+---------+
--   |2    |Simon -&gt; Philip |41 -&gt; 20 |
--   +-----+----------------+---------+
--   |999  |Mr. X           |999      |
--   +-----+----------------+---------+
--   </pre>
repsertMany :: forall record (m :: Type -> Type). (PersistStoreWrite backend, 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
--   <a>insertKey</a> or <a>repsert</a> in these cases.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1 schama-1</a> and <a>dataset-1</a>,
--   
--   <pre>
--   replaceSpj :: MonadIO m =&gt; User -&gt; ReaderT SqlBackend m ()
--   replaceSpj record = replace spjId record
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will produce this:
--   
--   <pre>
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |Mike  |45   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   </pre>
replace :: forall record (m :: Type -> Type). (PersistStoreWrite backend, MonadIO m, PersistRecordBackend record backend) => Key record -> record -> ReaderT backend m ()

-- | Update individual fields on a specific record, and retrieve the
--   updated value from the database.
--   
--   Note that this function will throw an exception if the given key is
--   not found in the database.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>,
--   
--   <pre>
--   updateGetSpj :: MonadIO m =&gt; [Update User] -&gt; ReaderT SqlBackend m User
--   updateGetSpj updates = updateGet spjId updates
--   </pre>
--   
--   <pre>
--   spj &lt;- updateGetSpj [UserAge +=. 100]
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will produce this:
--   
--   <pre>
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |140  |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   </pre>
updateGet :: forall record (m :: Type -> Type). (PersistStoreWrite backend, MonadIO m, PersistRecordBackend record backend) => Key record -> [Update record] -> ReaderT backend m record
data PersistFilter
Eq :: PersistFilter
Ne :: PersistFilter
Gt :: PersistFilter
Lt :: PersistFilter
Ge :: PersistFilter
Le :: PersistFilter
In :: PersistFilter
NotIn :: PersistFilter
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

-- | Get a record by identifier, if available.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>,
--   
--   <pre>
--   getSpj :: MonadIO m =&gt; ReaderT SqlBackend m (Maybe User)
--   getSpj = get spjId
--   </pre>
--   
--   <pre>
--   mspj &lt;- getSpj
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will get this:
--   
--   <pre>
--   +------+-----+
--   | name | age |
--   +------+-----+
--   | SPJ  |  40 |
--   +------+-----+
--   </pre>
get :: forall record (m :: Type -> Type). (PersistStoreRead backend, MonadIO m, PersistRecordBackend record backend) => Key record -> ReaderT backend m (Maybe record)

-- | Get many records by their respective identifiers, if available.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>:
--   
--   <pre>
--   getUsers :: MonadIO m =&gt; ReaderT SqlBackend m (Map (Key User) User)
--   getUsers = getMany allkeys
--   </pre>
--   
--   <pre>
--   musers &lt;- getUsers
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will get these
--   records:
--   
--   <pre>
--   +----+-------+-----+
--   | id | name  | age |
--   +----+-------+-----+
--   |  1 | SPJ   |  40 |
--   +----+-------+-----+
--   |  2 | Simon |  41 |
--   +----+-------+-----+
--   </pre>
getMany :: forall record (m :: Type -> Type). (PersistStoreRead backend, MonadIO m, PersistRecordBackend record backend) => [Key record] -> ReaderT backend m (Map (Key record) record)

-- | Some functions in this module (<a>insertUnique</a>, <a>insertBy</a>,
--   and <a>replaceUnique</a>) first query the unique indexes to check for
--   conflicts. You could instead optimistically attempt to perform the
--   operation (e.g. <a>replace</a> instead of <a>replaceUnique</a>).
--   However,
--   
--   <ul>
--   <li>there is some fragility to trying to catch the correct exception
--   and determing the column of failure;</li>
--   <li>an exception will automatically abort the current SQL
--   transaction.</li>
--   </ul>
class (PersistUniqueRead backend, PersistStoreWrite backend) => PersistUniqueWrite backend

-- | Delete a specific record by unique key. Does nothing if no record
--   matches.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>,
--   
--   <pre>
--   deleteBySpjName :: MonadIO m =&gt; ReaderT SqlBackend m ()
--   deleteBySpjName = deleteBy (UniqueUserName "SPJ")
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will produce this:
--   
--   <pre>
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   </pre>
deleteBy :: forall record (m :: Type -> Type). (PersistUniqueWrite backend, MonadIO m, PersistRecordBackend record backend) => Unique record -> ReaderT backend m ()

-- | Like <a>insert</a>, but returns <a>Nothing</a> when the record
--   couldn't be inserted because of a uniqueness constraint.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>, we try to insert the
--   following two records:
--   
--   <pre>
--   linusId &lt;- insertUnique $ User "Linus" 48
--   spjId   &lt;- insertUnique $ User "SPJ" 90
--   </pre>
--   
--   <pre>
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |40   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   |3    |Linus |48   |
--   +-----+------+-----+
--   </pre>
--   
--   Linus's record was inserted to <a>dataset-1</a>, while SPJ wasn't
--   because SPJ already exists in <a>dataset-1</a>.
insertUnique :: forall record (m :: Type -> Type). (PersistUniqueWrite backend, MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => record -> ReaderT backend m (Maybe (Key record))

-- | Same as <a>insertUnique</a> but doesn't return a <tt>Key</tt>.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>, we try to insert the
--   following two records:
--   
--   <pre>
--   linusId &lt;- insertUnique_ $ User "Linus" 48
--   spjId   &lt;- insertUnique_ $ User "SPJ" 90
--   </pre>
--   
--   <pre>
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |40   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   |3    |Linus |48   |
--   +-----+------+-----+
--   </pre>
--   
--   Linus's record was inserted to <a>dataset-1</a>, while SPJ wasn't
--   because SPJ already exists in <a>dataset-1</a>.
insertUnique_ :: forall record (m :: Type -> Type). (PersistUniqueWrite backend, MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => record -> ReaderT backend m (Maybe ())

-- | Update based on a uniqueness constraint or insert:
--   
--   <ul>
--   <li>insert the new record if it does not exist;</li>
--   <li>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.</li>
--   </ul>
--   
--   <h3><b>Example usage</b></h3>
--   
--   First, we try to explain <a>upsert</a> using <a>schema-1</a> and
--   <a>dataset-1</a>.
--   
--   <pre>
--   upsertSpj :: MonadIO m =&gt; [Update User] -&gt; ReaderT SqlBackend m (Maybe (Entity User))
--   upsertSpj updates = upsert (User "SPJ" 999) updates
--   </pre>
--   
--   <pre>
--   mSpjEnt &lt;- upsertSpj [UserAge +=. 15]
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will produce this:
--   
--   <pre>
--   +-----+-----+--------+
--   |id   |name |age     |
--   +-----+-----+--------+
--   |1    |SPJ  |40 -&gt; 55|
--   +-----+-----+--------+
--   |2    |Simon|41      |
--   +-----+-----+--------+
--   </pre>
--   
--   <pre>
--   upsertX :: MonadIO m =&gt; [Update User] -&gt; ReaderT SqlBackend m (Maybe (Entity User))
--   upsertX updates = upsert (User "X" 999) updates
--   </pre>
--   
--   <pre>
--   mXEnt &lt;- upsertX [UserAge +=. 15]
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will produce this:
--   
--   <pre>
--   +-----+-----+--------+
--   |id   |name |age     |
--   +-----+-----+--------+
--   |1    |SPJ  |40      |
--   +-----+-----+--------+
--   |2    |Simon|41      |
--   +-----+-----+--------+
--   |3    |X    |999     |
--   +-----+-----+--------+
--   </pre>
--   
--   Next, what if the schema has two uniqueness constraints? Let's check
--   it out using <a>schema-2</a>:
--   
--   <pre>
--   mSpjEnt &lt;- upsertSpj [UserAge +=. 15]
--   </pre>
--   
--   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
--   <a>upsertBy</a> to select the unique key we want.
upsert :: forall record (m :: Type -> Type). (PersistUniqueWrite backend, MonadIO m, PersistRecordBackend record backend, OnlyOneUniqueKey record, SafeToInsert record) => record -> [Update record] -> ReaderT backend m (Entity record)

-- | Update based on a given uniqueness constraint or insert:
--   
--   <ul>
--   <li>insert the new record if it does not exist;</li>
--   <li>update the existing record that matches the given uniqueness
--   constraint.</li>
--   </ul>
--   
--   <h3><b>Example usage</b></h3>
--   
--   We try to explain <a>upsertBy</a> using <a>schema-2</a> and
--   <a>dataset-1</a>.
--   
--   <pre>
--   upsertBySpjName :: MonadIO m =&gt; User -&gt; [Update User] -&gt; ReaderT SqlBackend m (Entity User)
--   upsertBySpjName record updates = upsertBy (UniqueUserName "SPJ") record updates
--   </pre>
--   
--   <pre>
--   mSpjEnt &lt;- upsertBySpjName (Person "X" 999) [PersonAge += .15]
--   </pre>
--   
--   The above query will alter <a>dataset-1</a> to:
--   
--   <pre>
--   +-----+-----+--------+
--   |id   |name |age     |
--   +-----+-----+--------+
--   |1    |SPJ  |40 -&gt; 55|
--   +-----+-----+--------+
--   |2    |Simon|41      |
--   +-----+-----+--------+
--   </pre>
--   
--   <pre>
--   upsertBySimonAge :: MonadIO m =&gt; User -&gt; [Update User] -&gt; ReaderT SqlBackend m (Entity User)
--   upsertBySimonAge record updates = upsertBy (UniqueUserName "SPJ") record updates
--   </pre>
--   
--   <pre>
--   mPhilipEnt &lt;- upsertBySimonAge (User "X" 999) [UserName =. "Philip"]
--   </pre>
--   
--   The above query will alter <a>dataset-1</a> to:
--   
--   <pre>
--   +----+-----------------+-----+
--   | id |      name       | age |
--   +----+-----------------+-----+
--   |  1 | SPJ             |  40 |
--   +----+-----------------+-----+
--   |  2 | Simon -&gt; Philip |  41 |
--   +----+-----------------+-----+
--   </pre>
--   
--   <pre>
--   upsertByUnknownName :: MonadIO m =&gt; User -&gt; [Update User] -&gt; ReaderT SqlBackend m (Entity User)
--   upsertByUnknownName record updates = upsertBy (UniqueUserName "Unknown") record updates
--   </pre>
--   
--   <pre>
--   mXEnt &lt;- upsertByUnknownName (User "X" 999) [UserAge +=. 15]
--   </pre>
--   
--   This query will alter <a>dataset-1</a> to:
--   
--   <pre>
--   +-----+-----+-----+
--   |id   |name |age  |
--   +-----+-----+-----+
--   |1    |SPJ  |40   |
--   +-----+-----+-----+
--   |2    |Simon|41   |
--   +-----+-----+-----+
--   |3    |X    |999  |
--   +-----+-----+-----+
--   </pre>
upsertBy :: forall record (m :: Type -> Type). (PersistUniqueWrite backend, MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => Unique record -> record -> [Update record] -> ReaderT backend m (Entity record)

-- | Put many records into db
--   
--   <ul>
--   <li>insert new records that do not exist (or violate any unique
--   constraints)</li>
--   <li>replace existing records (matching any unique constraint)</li>
--   </ul>
putMany :: forall record (m :: Type -> Type). (PersistUniqueWrite backend, MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => [record] -> ReaderT backend m ()

-- | Insert a value, checking for conflicts with any unique constraints. If
--   a duplicate exists in the database, it is returned as <a>Left</a>.
--   Otherwise, the new 'Key is returned as <a>Right</a>.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-2</a> and <a>dataset-1</a>, we have following lines of
--   code:
--   
--   <pre>
--   l1 &lt;- insertBy $ User "SPJ" 20
--   l2 &lt;- insertBy $ User "XXX" 41
--   l3 &lt;- insertBy $ User "SPJ" 40
--   r1 &lt;- insertBy $ User "XXX" 100
--   </pre>
--   
--   First three lines return <a>Left</a> because there're duplicates in
--   given record's uniqueness constraints. While the last line returns a
--   new key as <a>Right</a>.
insertBy :: forall record backend (m :: Type -> Type). (MonadIO m, PersistUniqueWrite backend, PersistRecordBackend record backend, AtLeastOneUniqueKey record, SafeToInsert record) => record -> ReaderT backend m (Either (Entity record) (Key record))

-- | Given a list of old entity definitions and a new <a>EntityDef</a> in
--   <tt>val</tt>, this creates a <a>Migration</a> to update the old list
--   of definitions with the new one.
migrate :: [EntityDef] -> EntityDef -> Migration

-- | Report a single error in a <a>Migration</a>.
reportError :: Text -> Migration

-- | Unique keys besides the <a>Key</a>.
data family Unique record

-- | A single column (see <tt>rawSql</tt>). Any <tt>PersistField</tt> may
--   be used here, including <a>PersistValue</a> (which does not do any
--   processing).
newtype Single a
Single :: a -> Single a
[unSingle] :: Single a -> a
data Column
Column :: !FieldNameDB -> !Bool -> !SqlType -> !Maybe Text -> !Maybe Text -> !Maybe ConstraintNameDB -> !Maybe Integer -> !Maybe ColumnReference -> Column
[cName] :: Column -> !FieldNameDB
[cNull] :: Column -> !Bool
[cSqlType] :: Column -> !SqlType
[cDefault] :: Column -> !Maybe Text
[cGenerated] :: Column -> !Maybe Text
[cDefaultConstraintName] :: Column -> !Maybe ConstraintNameDB
[cMaxLen] :: Column -> !Maybe Integer
[cReference] :: Column -> !Maybe ColumnReference

-- | Execute a raw SQL statement and return its results as a list. If you
--   do not expect a return value, use of <a>rawExecute</a> is recommended.
--   
--   If you're using <a>Entity</a><tt>s</tt> (which is quite likely), then
--   you <i>must</i> use entity selection placeholders (double question
--   mark, <tt>??</tt>). These <tt>??</tt> placeholders are then replaced
--   for the names of the columns that we need for your entities. You'll
--   receive an error if you don't use the placeholders. Please see the
--   <a>Entity</a><tt>s</tt> documentation for more details.
--   
--   You may put value placeholders (question marks, <tt>?</tt>) in your
--   SQL query. These placeholders are then replaced by the values you pass
--   on the second parameter, already correctly escaped. You may want to
--   use <a>toPersistValue</a> to help you constructing the placeholder
--   values.
--   
--   Since you're giving a raw SQL statement, you don't get any guarantees
--   regarding safety. If <a>rawSql</a> is not able to parse the results of
--   your query back, then an exception is raised. However, most common
--   problems are mitigated by using the entity selection placeholder
--   <tt>??</tt>, and you shouldn't see any error at all if you're not
--   using <a>Single</a>.
--   
--   Some example of <a>rawSql</a> based on this schema:
--   
--   <pre>
--   share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
--   Person
--       name String
--       age Int Maybe
--       deriving Show
--   BlogPost
--       title String
--       authorId PersonId
--       deriving Show
--   |]
--   </pre>
--   
--   Examples based on the above schema:
--   
--   <pre>
--   getPerson :: MonadIO m =&gt; ReaderT SqlBackend m [Entity Person]
--   getPerson = rawSql "select ?? from person where name=?" [PersistText "john"]
--   
--   getAge :: MonadIO m =&gt; ReaderT SqlBackend m [Single Int]
--   getAge = rawSql "select person.age from person where name=?" [PersistText "john"]
--   
--   getAgeName :: MonadIO m =&gt; ReaderT SqlBackend m [(Single Int, Single Text)]
--   getAgeName = rawSql "select person.age, person.name from person where name=?" [PersistText "john"]
--   
--   getPersonBlog :: MonadIO m =&gt; ReaderT SqlBackend m [(Entity Person, Entity BlogPost)]
--   getPersonBlog = rawSql "select ??,?? from person,blog_post where person.id = blog_post.author_id" []
--   </pre>
--   
--   Minimal working program for PostgreSQL backend based on the above
--   concepts:
--   
--   <pre>
--   {-# LANGUAGE EmptyDataDecls             #-}
--   {-# LANGUAGE FlexibleContexts           #-}
--   {-# LANGUAGE GADTs                      #-}
--   {-# LANGUAGE GeneralizedNewtypeDeriving #-}
--   {-# LANGUAGE MultiParamTypeClasses      #-}
--   {-# LANGUAGE OverloadedStrings          #-}
--   {-# LANGUAGE QuasiQuotes                #-}
--   {-# LANGUAGE TemplateHaskell            #-}
--   {-# LANGUAGE TypeFamilies               #-}
--   
--   import           Control.Monad.IO.Class  (liftIO)
--   import           Control.Monad.Logger    (runStderrLoggingT)
--   import           Database.Persist
--   import           Control.Monad.Reader
--   import           Data.Text
--   import           Database.Persist.Sql
--   import           Database.Persist.Postgresql
--   import           Database.Persist.TH
--   
--   share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
--   Person
--       name String
--       age Int Maybe
--       deriving Show
--   |]
--   
--   conn = "host=localhost dbname=new_db user=postgres password=postgres port=5432"
--   
--   getPerson :: MonadIO m =&gt; ReaderT SqlBackend m [Entity Person]
--   getPerson = rawSql "select ?? from person where name=?" [PersistText "sibi"]
--   
--   liftSqlPersistMPool y x = liftIO (runSqlPersistMPool y x)
--   
--   main :: IO ()
--   main = runStderrLoggingT $ withPostgresqlPool conn 10 $ liftSqlPersistMPool $ do
--            runMigration migrateAll
--            xs &lt;- getPerson
--            liftIO (print xs)
--   </pre>
rawSql :: forall a (m :: Type -> Type) backend. (RawSql a, MonadIO m, BackendCompatible SqlBackend backend) => Text -> [PersistValue] -> ReaderT backend m [a]

-- | Represents a value containing all the configuration options for a
--   specific backend. This abstraction makes it easier to write code that
--   can easily swap backends.
class PersistConfig c where {
    type PersistConfigBackend c :: Type -> Type -> Type -> Type;
    type PersistConfigPool c;
}

-- | Load the config settings from a <a>Value</a>, most likely taken from a
--   YAML config file.
loadConfig :: PersistConfig c => Value -> Parser c

-- | Modify the config settings based on environment variables.
applyEnv :: PersistConfig c => c -> IO c

-- | Create a new connection pool based on the given config settings.
createPoolConfig :: PersistConfig c => c -> IO (PersistConfigPool c)

-- | Run a database action by taking a connection from the pool.
runPool :: (PersistConfig c, MonadUnliftIO m) => c -> PersistConfigBackend c m a -> PersistConfigPool c -> m a
type family PersistConfigBackend c :: Type -> Type -> Type -> Type
type family PersistConfigPool c

-- | An <a>ConstraintNameHS</a> represents the Haskell-side name that
--   <tt>persistent</tt> will use for a constraint.
newtype ConstraintNameHS
ConstraintNameHS :: Text -> ConstraintNameHS
[unConstraintNameHS] :: ConstraintNameHS -> Text

-- | A <a>ConstraintNameDB</a> represents the datastore-side name that
--   <tt>persistent</tt> will use for a constraint.
newtype ConstraintNameDB
ConstraintNameDB :: Text -> ConstraintNameDB
[unConstraintNameDB] :: ConstraintNameDB -> Text

-- | An <a>EntityNameDB</a> represents the datastore-side name that
--   <tt>persistent</tt> will use for an entity.
newtype EntityNameDB
EntityNameDB :: Text -> EntityNameDB
[unEntityNameDB] :: EntityNameDB -> Text

-- | An <a>EntityNameHS</a> represents the Haskell-side name that
--   <tt>persistent</tt> will use for an entity.
newtype EntityNameHS
EntityNameHS :: Text -> EntityNameHS
[unEntityNameHS] :: EntityNameHS -> Text

-- | A <a>FieldNameHS</a> represents the Haskell-side name that
--   <tt>persistent</tt> will use for a field.
newtype FieldNameHS
FieldNameHS :: Text -> FieldNameHS
[unFieldNameHS] :: FieldNameHS -> Text

-- | A <a>FieldNameDB</a> represents the datastore-side name that
--   <tt>persistent</tt> will use for a field.
newtype FieldNameDB
FieldNameDB :: Text -> FieldNameDB
[unFieldNameDB] :: FieldNameDB -> Text

-- | Convenience operations for working with '-NameDB' types.
class DatabaseName a
escapeWith :: DatabaseName a => (Text -> str) -> a -> str

-- | A type that determines how a backend should handle the literal.
data LiteralType

-- | The accompanying value will be escaped before inserting into the
--   database. This is the correct default choice to use.
Escaped :: LiteralType

-- | The accompanying value will not be escaped when inserting into the
--   database. This is potentially dangerous - use this with care.
Unescaped :: LiteralType

-- | The <a>DbSpecific</a> constructor corresponds to the legacy
--   <a>PersistDbSpecific</a> 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.
DbSpecific :: LiteralType

-- | A raw value which can be stored in any backend and can be marshalled
--   to and from a <tt>PersistField</tt>.
data PersistValue
PersistText :: Text -> PersistValue
PersistByteString :: ByteString -> PersistValue
PersistInt64 :: Int64 -> PersistValue
PersistDouble :: Double -> PersistValue
PersistRational :: Rational -> PersistValue
PersistBool :: Bool -> PersistValue
PersistDay :: Day -> PersistValue
PersistTimeOfDay :: TimeOfDay -> PersistValue
PersistUTCTime :: UTCTime -> PersistValue
PersistNull :: PersistValue
PersistList :: [PersistValue] -> PersistValue
PersistMap :: [(Text, PersistValue)] -> PersistValue

-- | Intended especially for MongoDB backend
PersistObjectId :: ByteString -> PersistValue

-- | Intended especially for PostgreSQL backend for text arrays
PersistArray :: [PersistValue] -> PersistValue

-- | This constructor is used to specify some raw literal value for the
--   backend. The <a>LiteralType</a> value specifies how the value should
--   be escaped. This can be used to make special, custom types avaialable
--   in the back end.
PersistLiteral_ :: LiteralType -> ByteString -> PersistValue

-- | This pattern synonym used to be a data constructor on
--   <a>PersistValue</a>, but was changed into a catch-all pattern synonym
--   to allow backwards compatiblity with database types. See the
--   documentation on <a>PersistDbSpecific</a> for more details.
pattern PersistLiteral :: ByteString -> PersistValue

-- | This pattern synonym used to be a data constructor on
--   <a>PersistValue</a>, but was changed into a catch-all pattern synonym
--   to allow backwards compatiblity with database types. See the
--   documentation on <a>PersistDbSpecific</a> for more details.
pattern PersistLiteralEscaped :: ByteString -> PersistValue

-- | This pattern synonym used to be a data constructor for the
--   <a>PersistValue</a> 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 <a>PersistLiteral_</a> directly.
--   
--   If you use this, it will overlap a patern match on the
--   'PersistLiteral_, <a>PersistLiteral</a>, and
--   <a>PersistLiteralEscaped</a> patterns. If you need to disambiguate
--   between these constructors, pattern match on <a>PersistLiteral_</a>
--   directly.
pattern PersistDbSpecific :: ByteString -> PersistValue
fromPersistValueText :: PersistValue -> Either Text Text

-- | Please refer to the documentation for the database in question for a
--   full overview of the semantics of the varying isolation levels
data IsolationLevel
ReadUncommitted :: IsolationLevel
ReadCommitted :: IsolationLevel
RepeatableRead :: IsolationLevel
Serializable :: IsolationLevel

-- | A <a>FieldDef</a> represents the inormation that <tt>persistent</tt>
--   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.
data FieldDef
FieldDef :: !FieldNameHS -> !FieldNameDB -> !FieldType -> !SqlType -> ![FieldAttr] -> !Bool -> !ReferenceDef -> !FieldCascade -> !Maybe Text -> !Maybe Text -> !Bool -> FieldDef

-- | The 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
--   <a>FieldDef</a> that contains a <tt><a>FieldNameHS</a> "name"</tt> for
--   a type <tt>User</tt> will have a record field <tt>userName</tt>.
[fieldHaskell] :: FieldDef -> !FieldNameHS

-- | The name of the field in the database. For SQL databases, this
--   corresponds to the column name.
[fieldDB] :: FieldDef -> !FieldNameDB

-- | The type of the field in Haskell.
[fieldType] :: FieldDef -> !FieldType

-- | The type of the field in a SQL database.
[fieldSqlType] :: FieldDef -> !SqlType

-- | User annotations for a field. These are provided with the <tt>!</tt>
--   operator.
[fieldAttrs] :: FieldDef -> ![FieldAttr]

-- | If this is <a>True</a>, then the Haskell datatype will have a strict
--   record field. The default value for this is <a>True</a>.
[fieldStrict] :: FieldDef -> !Bool
[fieldReference] :: FieldDef -> !ReferenceDef

-- | Defines how operations on the field cascade on to the referenced
--   tables. This doesn't have any meaning if the <a>fieldReference</a> is
--   set to <a>NoReference</a> or <a>SelfReference</a>. The cascade option
--   here should be the same as the one obtained in the
--   <a>fieldReference</a>.
[fieldCascade] :: FieldDef -> !FieldCascade

-- | Optional comments for a <tt>Field</tt>.
[fieldComments] :: FieldDef -> !Maybe Text

-- | Whether or not the field is a <tt>GENERATED</tt> column, and
--   additionally the expression to use for generation.
[fieldGenerated] :: FieldDef -> !Maybe Text

-- | <a>True</a> if the field is an implicit ID column. <a>False</a>
--   otherwise.
[fieldIsImplicitIdColumn] :: FieldDef -> !Bool
data PersistUpdate
Assign :: PersistUpdate
Add :: PersistUpdate
Subtract :: PersistUpdate
Multiply :: PersistUpdate
Divide :: PersistUpdate
BackendSpecificUpdate :: Text -> PersistUpdate
type family BackendSpecificUpdate backend record
data UpdateException
KeyNotFound :: String -> UpdateException
UpsertError :: String -> UpdateException

-- | 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.
data SqlType
SqlString :: SqlType
SqlInt32 :: SqlType
SqlInt64 :: SqlType
SqlReal :: SqlType
SqlNumeric :: Word32 -> Word32 -> SqlType
SqlBool :: SqlType
SqlDay :: SqlType
SqlTime :: SqlType

-- | Always uses UTC timezone
SqlDayTime :: SqlType
SqlBlob :: SqlType

-- | a backend-specific name
SqlOther :: Text -> SqlType
data PersistException

-- | Generic Exception
PersistError :: Text -> PersistException
PersistMarshalError :: Text -> PersistException
PersistInvalidField :: Text -> PersistException
PersistForeignConstraintUnmet :: Text -> PersistException
PersistMongoDBError :: Text -> PersistException
PersistMongoDBUnsupported :: Text -> PersistException

-- | An action that might happen on a deletion or update on a foreign key
--   change.
data CascadeAction
Cascade :: CascadeAction
Restrict :: CascadeAction
SetNull :: CascadeAction
SetDefault :: CascadeAction

-- | 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 <a>Nothing</a> in either of the field values means that
--   the user has not specified a <a>CascadeAction</a>. An unspecified
--   <a>CascadeAction</a> is defaulted to <a>Restrict</a> when doing
--   migrations.
data FieldCascade
FieldCascade :: !Maybe CascadeAction -> !Maybe CascadeAction -> FieldCascade
[fcOnUpdate] :: FieldCascade -> !Maybe CascadeAction
[fcOnDelete] :: FieldCascade -> !Maybe CascadeAction
data ForeignDef
ForeignDef :: !EntityNameHS -> !EntityNameDB -> !ConstraintNameHS -> !ConstraintNameDB -> !FieldCascade -> ![(ForeignFieldDef, ForeignFieldDef)] -> ![Attr] -> Bool -> Bool -> ForeignDef
[foreignRefTableHaskell] :: ForeignDef -> !EntityNameHS
[foreignRefTableDBName] :: ForeignDef -> !EntityNameDB
[foreignConstraintNameHaskell] :: ForeignDef -> !ConstraintNameHS
[foreignConstraintNameDBName] :: ForeignDef -> !ConstraintNameDB

-- | Determine how the field will cascade on updates and deletions.
[foreignFieldCascade] :: ForeignDef -> !FieldCascade
[foreignFields] :: ForeignDef -> ![(ForeignFieldDef, ForeignFieldDef)]
[foreignAttrs] :: ForeignDef -> ![Attr]
[foreignNullable] :: ForeignDef -> Bool

-- | Determines if the reference is towards a Primary Key or not.
[foreignToPrimary] :: ForeignDef -> Bool

-- | Used instead of FieldDef to generate a smaller amount of code
type ForeignFieldDef = (FieldNameHS, FieldNameDB)
data CompositeDef
CompositeDef :: !NonEmpty FieldDef -> ![Attr] -> CompositeDef
[compositeFields] :: CompositeDef -> !NonEmpty FieldDef
[compositeAttrs] :: CompositeDef -> ![Attr]

-- | Type for storing the Uniqueness constraint in the Schema. Assume you
--   have the following schema with a uniqueness constraint:
--   
--   <pre>
--   Person
--     name String
--     age Int
--     UniqueAge age
--   </pre>
--   
--   This will be represented as:
--   
--   <pre>
--   UniqueDef
--       { uniqueHaskell = ConstraintNameHS (packPTH <a>UniqueAge</a>)
--       , uniqueDBName = ConstraintNameDB (packPTH "unique_age")
--       , uniqueFields = [(FieldNameHS (packPTH "age"), FieldNameDB (packPTH "age"))]
--       , uniqueAttrs = []
--       }
--   </pre>
data UniqueDef
UniqueDef :: !ConstraintNameHS -> !ConstraintNameDB -> !NonEmpty (FieldNameHS, FieldNameDB) -> ![Attr] -> UniqueDef
[uniqueHaskell] :: UniqueDef -> !ConstraintNameHS
[uniqueDBName] :: UniqueDef -> !ConstraintNameDB
[uniqueFields] :: UniqueDef -> !NonEmpty (FieldNameHS, FieldNameDB)
[uniqueAttrs] :: UniqueDef -> ![Attr]

-- | An EmbedFieldDef is the same as a FieldDef But it is only used for
--   embeddedFields so it only has data needed for embedding
data EmbedFieldDef
EmbedFieldDef :: FieldNameDB -> Maybe (Either SelfEmbed EntityNameHS) -> EmbedFieldDef
[emFieldDB] :: EmbedFieldDef -> FieldNameDB
[emFieldEmbed] :: EmbedFieldDef -> Maybe (Either SelfEmbed EntityNameHS)

-- | An EmbedEntityDef is the same as an EntityDef But it is only used for
--   fieldReference so it only has data needed for embedding
data EmbedEntityDef
EmbedEntityDef :: EntityNameHS -> [EmbedFieldDef] -> EmbedEntityDef
[embeddedHaskell] :: EmbedEntityDef -> EntityNameHS
[embeddedFields] :: EmbedEntityDef -> [EmbedFieldDef]

-- | There are 3 kinds of references 1) composite (to fields that exist in
--   the record) 2) single field 3) embedded
data ReferenceDef
NoReference :: ReferenceDef

-- | A 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
ForeignRef :: !EntityNameHS -> ReferenceDef
EmbedRef :: EntityNameHS -> ReferenceDef

-- | A SelfReference stops an immediate cycle which causes non-termination
--   at compile-time (issue #311).
SelfReference :: ReferenceDef

-- | A <a>FieldType</a> describes a field parsed from the QuasiQuoter and
--   is used to determine the Haskell type in the generated code.
--   
--   <tt>name Text</tt> parses into <tt>FTTypeCon Nothing <a>Text</a></tt>
--   
--   <tt>name T.Text</tt> parses into <tt>FTTypeCon (Just <a>T</a>
--   <a>Text</a>)</tt>
--   
--   <tt>name (Jsonb User)</tt> parses into:
--   
--   <pre>
--   FTApp (FTTypeCon Nothing <a>Jsonb</a>) (FTTypeCon Nothing <a>User</a>)
--   </pre>
data FieldType

-- | Optional module and name.
FTTypeCon :: Maybe Text -> Text -> FieldType
FTLit :: FieldTypeLit -> FieldType
FTTypePromoted :: Text -> FieldType
FTApp :: FieldType -> FieldType -> FieldType
FTList :: FieldType -> FieldType

-- | 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 <a>FieldAttr</a> is extensible through its constructor
--   <a>FieldAttrOther</a>.
data FieldAttr

-- | The <a>Maybe</a> keyword goes after the type. This indicates that the
--   column is nullable, and the generated Haskell code will have a
--   <tt><a>Maybe</a></tt> type for it.
--   
--   Example:
--   
--   <pre>
--   User
--       name Text Maybe
--   </pre>
FieldAttrMaybe :: FieldAttr

-- | This indicates that the column is nullable, but should not have a
--   <a>Maybe</a> type. For this to work out, you need to ensure that the
--   <tt>PersistField</tt> instance for the type in question can support a
--   <a>PersistNull</a> value.
--   
--   <pre>
--   data What = NoWhat | Hello Text
--   
--   instance PersistField What where
--       fromPersistValue PersistNull =
--           pure NoWhat
--       fromPersistValue pv =
--           Hello <a>$</a> fromPersistValue pv
--   
--   instance PersistFieldSql What where
--       sqlType _ = SqlString
--   
--   User
--       what What nullable
--   </pre>
FieldAttrNullable :: FieldAttr

-- | This 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.
--   
--   <pre>
--   User
--       oldName Text MigrationOnly
--       newName Text
--   </pre>
FieldAttrMigrationOnly :: FieldAttr

-- | A <tt>SafeToRemove</tt> attribute is not present on the Haskell
--   datatype, and the backend migrations should attempt to drop the column
--   without triggering any unsafe migration warnings.
--   
--   Useful after you've used <tt>MigrationOnly</tt> to remove a column
--   from the database in phases.
--   
--   <pre>
--   User
--       oldName Text SafeToRemove
--       newName Text
--   </pre>
FieldAttrSafeToRemove :: FieldAttr

-- | This attribute indicates that we should not create a foreign key
--   reference from a column. By default, <tt>persistent</tt> will try and
--   create a foreign key reference for a column if it can determine that
--   the type of the column is a <tt><tt>Key</tt> entity</tt> or an
--   <tt>EntityId</tt> and the <tt>Entity</tt>'s name was present in
--   <tt>mkPersist</tt>.
--   
--   This is useful if you want to use the explicit foreign key syntax.
--   
--   <pre>
--   Post
--       title    Text
--   
--   Comment
--       postId   PostId      noreference
--       Foreign Post fk_comment_post postId
--   </pre>
FieldAttrNoreference :: FieldAttr

-- | This is set to specify precisely the database table the column refers
--   to.
--   
--   <pre>
--   Post
--       title    Text
--   
--   Comment
--       postId   PostId references="post"
--   </pre>
--   
--   You should not need this - <tt>persistent</tt> should be capable of
--   correctly determining the target table's name. If you do need this,
--   please file an issue describing why.
FieldAttrReference :: Text -> FieldAttr

-- | Specify a name for the constraint on the foreign key reference for
--   this table.
--   
--   <pre>
--   Post
--       title    Text
--   
--   Comment
--       postId   PostId constraint="my_cool_constraint_name"
--   </pre>
FieldAttrConstraint :: Text -> FieldAttr

-- | Specify the default value for a column.
--   
--   <pre>
--   User
--       createdAt    UTCTime     default="NOW()"
--   </pre>
--   
--   Note that a <tt>default=</tt> attribute does not mean you can omit the
--   value while inserting.
FieldAttrDefault :: Text -> FieldAttr

-- | Specify a custom SQL type for the column. Generally, you should define
--   a custom datatype with a custom <tt>PersistFieldSql</tt> instance
--   instead of using this.
--   
--   <pre>
--   User
--       uuid     Text    sqltype=<a>UUID</a>
--   </pre>
FieldAttrSqltype :: Text -> FieldAttr

-- | Set a maximum length for a column. Useful for VARCHAR and indexes.
--   
--   <pre>
--   User
--       name     Text    maxlen=200
--   
--       UniqueName name
--   </pre>
FieldAttrMaxlen :: Integer -> FieldAttr

-- | Specify the database name of the column.
--   
--   <pre>
--   User
--       blarghle     Int     sql="b_l_a_r_g_h_l_e"
--   </pre>
--   
--   Useful for performing phased migrations, where one column is renamed
--   to another column over time.
FieldAttrSql :: Text -> FieldAttr

-- | A grab bag of random attributes that were unrecognized by the parser.
FieldAttrOther :: Text -> FieldAttr
type Attr = Text
type ExtraLine = [Text]

-- | The definition for the entity's primary key ID.
data EntityIdDef

-- | The entity has a single key column, and it is a surrogate key - that
--   is, you can't go from <tt>rec -&gt; Key rec</tt>.
EntityIdField :: !FieldDef -> EntityIdDef

-- | The entity has a natural key. This means you can write <tt>rec -&gt;
--   Key rec</tt> because all the key fields are present on the datatype.
--   
--   A natural key can have one or more columns.
EntityIdNaturalKey :: !CompositeDef -> EntityIdDef

-- | An <a>EntityDef</a> represents the information that
--   <tt>persistent</tt> knows about an Entity. It uses this information to
--   generate the Haskell datatype, the SQL migrations, and other relevant
--   conversions.
data EntityDef

-- | The reason why a field is <tt>nullable</tt> is very important. A field
--   that is nullable because of a <tt>Maybe</tt> tag will have its type
--   changed from <tt>A</tt> to <tt>Maybe A</tt>. OTOH, a field that is
--   nullable because of a <tt>nullable</tt> tag will remain with the same
--   type.
data WhyNullable
ByMaybeAttr :: WhyNullable
ByNullableAttr :: WhyNullable
data IsNullable
Nullable :: !WhyNullable -> IsNullable
NotNullable :: IsNullable

-- | A <a>Checkmark</a> 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.
--   
--   <i>NOTE:</i> You need to mark any <tt>Checkmark</tt> fields as
--   <tt>nullable</tt> (see the following example).
--   
--   For example, suppose there's a <tt>Location</tt> entity that
--   represents where a user has lived:
--   
--   <pre>
--   Location
--       user    UserId
--       name    Text
--       current Checkmark nullable
--   
--       UniqueLocation user current
--   </pre>
--   
--   The <tt>UniqueLocation</tt> constraint allows any number of
--   <a>Inactive</a> <tt>Location</tt>s to be <tt>current</tt>. However,
--   there may be at most one <tt>current</tt> <tt>Location</tt> per user
--   (i.e., either zero or one per user).
--   
--   This data type works because of the way that SQL treats
--   <tt>NULL</tt>able fields within uniqueness constraints. The SQL
--   standard says that <tt>NULL</tt> values should be considered
--   different, so we represent <a>Inactive</a> as SQL <tt>NULL</tt>, thus
--   allowing any number of <a>Inactive</a> records. On the other hand, we
--   represent <a>Active</a> as <tt>TRUE</tt>, so the uniqueness constraint
--   will disallow more than one <a>Active</a> record.
--   
--   <i>Note:</i> There may be DBMSs that do not respect the SQL standard's
--   treatment of <tt>NULL</tt> values on uniqueness constraints, please
--   check if this data type works before relying on it.
--   
--   The SQL <tt>BOOLEAN</tt> type is used because it's the smallest data
--   type available. Note that we never use <tt>FALSE</tt>, just
--   <tt>TRUE</tt> and <tt>NULL</tt>. Provides the same behavior <tt>Maybe
--   ()</tt> would if <tt>()</tt> was a valid <tt>PersistField</tt>.
data Checkmark

-- | When used on a uniqueness constraint, there may be at most one
--   <a>Active</a> record.
Active :: Checkmark

-- | When used on a uniqueness constraint, there may be any number of
--   <a>Inactive</a> records.
Inactive :: Checkmark
fieldAttrsContainsNullable :: [FieldAttr] -> IsNullable

-- | Return the <tt>[<a>FieldDef</a>]</tt> for the entity keys.
entitiesPrimary :: EntityDef -> NonEmpty FieldDef
entityPrimary :: EntityDef -> Maybe CompositeDef

-- | Returns a <a>NonEmpty</a> list of <a>FieldDef</a> that correspond with
--   the key columns for an <a>EntityDef</a>.
keyAndEntityFields :: EntityDef -> NonEmpty FieldDef

-- | Returns a <a>NonEmpty</a> list of <a>FieldDef</a> that correspond with
--   the key columns for an <a>EntityDef</a> including those fields that
--   are marked as <tt>MigrationOnly</tt> (and therefore only present in
--   the database) or <tt>SafeToRemove</tt> (and a migration will drop the
--   column if it exists in the database).
--   
--   For fields on the Haskell type use <a>keyAndEntityFieldsDatabase</a>
keyAndEntityFieldsDatabase :: EntityDef -> NonEmpty FieldDef

-- | Parse raw field attributes into structured form. Any unrecognized
--   attributes will be preserved, identically as they are encountered, as
--   <a>FieldAttrOther</a> values.
parseFieldAttrs :: [Text] -> [FieldAttr]
isFieldNotGenerated :: FieldDef -> Bool

-- | Returns <a>True</a> if the <a>FieldDef</a> does not have a
--   <tt>MigrationOnly</tt> or <tt>SafeToRemove</tt> flag from the
--   QuasiQuoter.
isHaskellField :: FieldDef -> Bool

-- | A <a>FieldCascade</a> that does nothing.
noCascade :: FieldCascade

-- | Renders a <a>FieldCascade</a> value such that it can be used in SQL
--   migrations.
renderFieldCascade :: FieldCascade -> Text

-- | Render a <a>CascadeAction</a> to <a>Text</a> such that it can be used
--   in a SQL command.
renderCascadeAction :: CascadeAction -> Text

-- | A <a>Statement</a> is a representation of a database query that has
--   been prepared and stored on the server side.
data Statement
Statement :: IO () -> IO () -> ([PersistValue] -> IO Int64) -> (forall (m :: Type -> Type). MonadIO m => [PersistValue] -> Acquire (ConduitM () [PersistValue] m ())) -> Statement
[stmtFinalize] :: Statement -> IO ()
[stmtReset] :: Statement -> IO ()
[stmtExecute] :: Statement -> [PersistValue] -> IO Int64
[stmtQuery] :: Statement -> forall (m :: Type -> Type). MonadIO m => [PersistValue] -> Acquire (ConduitM () [PersistValue] m ())
data InsertSqlResult
ISRSingle :: Text -> InsertSqlResult
ISRInsertGet :: Text -> Text -> InsertSqlResult
ISRManyKeys :: Text -> [PersistValue] -> InsertSqlResult
type LogFunc = Loc -> LogSource -> LogLevel -> LogStr -> IO ()

-- | Replace the <a>FieldDef</a> <a>FieldAttr</a> with the new list.
setFieldAttrs :: [FieldAttr] -> FieldDef -> FieldDef

-- | Modify the list of field attributes.
overFieldAttrs :: ([FieldAttr] -> [FieldAttr]) -> FieldDef -> FieldDef

-- | Add an attribute to the list of field attributes.
addFieldAttr :: FieldAttr -> FieldDef -> FieldDef

-- | Check if the field definition is nullable
isFieldNullable :: FieldDef -> IsNullable

-- | Check if the field is `Maybe a`
isFieldMaybe :: FieldDef -> Bool

-- | Retrieve the list of <a>UniqueDef</a> from an <a>EntityDef</a>. This
--   does not include a <tt>Primary</tt> key, if one is defined. A future
--   version of <tt>persistent</tt> will include a <tt>Primary</tt> key
--   among the <tt>Unique</tt> constructors for the <tt>Entity</tt>.
getEntityUniquesNoPrimaryKey :: EntityDef -> [UniqueDef]

-- | Retrieve the list of <a>UniqueDef</a> from an <a>EntityDef</a>. 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
--   <a>getEntityUniquesNoPrimaryKey</a>.
getEntityUniques :: EntityDef -> [UniqueDef]

-- | Retrieve the Haskell name of the given entity.
getEntityHaskellName :: EntityDef -> EntityNameHS

-- | Return the database name for the given entity.
getEntityDBName :: EntityDef -> EntityNameDB
getEntityExtra :: EntityDef -> Map Text [[Text]]

setEntityDBName :: EntityNameDB -> EntityDef -> EntityDef
getEntityComments :: EntityDef -> Maybe Text

getEntityForeignDefs :: EntityDef -> [ForeignDef]

-- | Retrieve the list of <a>FieldDef</a> that makes up the fields of the
--   entity.
--   
--   This does not return the fields for an <tt>Id</tt> column or an
--   implicit <tt>id</tt>. It will return the key columns if you used the
--   <tt>Primary</tt> syntax for defining the primary key.
--   
--   This does not return fields that are marked <tt>SafeToRemove</tt> or
--   <tt>MigrationOnly</tt> - so it only returns fields that are
--   represented in the Haskell type. If you need those fields, use
--   <a>getEntityFieldsDatabase</a>.
getEntityFields :: EntityDef -> [FieldDef]

-- | This returns all of the <a>FieldDef</a> defined for the
--   <a>EntityDef</a>, including those fields that are marked as
--   <tt>MigrationOnly</tt> (and therefore only present in the database) or
--   <tt>SafeToRemove</tt> (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
--   <a>getEntityFields</a>.
getEntityFieldsDatabase :: EntityDef -> [FieldDef]

isEntitySum :: EntityDef -> Bool

getEntityId :: EntityDef -> EntityIdDef

getEntityIdField :: EntityDef -> Maybe FieldDef

-- | Set an <a>entityId</a> to be the given <a>FieldDef</a>.
setEntityId :: FieldDef -> EntityDef -> EntityDef

setEntityIdDef :: EntityIdDef -> EntityDef -> EntityDef

getEntityKeyFields :: EntityDef -> NonEmpty FieldDef

-- | Perform a mapping function over all of the entity fields, as
--   determined by <a>getEntityFieldsDatabase</a>.
overEntityFields :: ([FieldDef] -> [FieldDef]) -> EntityDef -> EntityDef

-- | Gets the <tt>Source</tt> of the definition of the entity.
--   
--   Note that as of this writing the span covers the entire file or
--   quasiquote where the item is defined due to parsing limitations. This
--   may be changed in a future release to be more accurate.
getEntitySpan :: EntityDef -> Maybe SourceSpan

-- | Prior to <tt>persistent-2.11.0</tt>, we provided an instance of
--   <a>PersistField</a> for the <a>Natural</a> type. This was in error,
--   because <a>Natural</a> represents an infinite value, and databases
--   don't have reasonable types for this.
--   
--   The instance for <a>Natural</a> used the <a>Int64</a> 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 <a>Word</a> series of types
--   from <a>Data.Word</a>. These have a bounded size, are guaranteed to be
--   non-negative, and are quite efficient for the database to store.
newtype OverflowNatural
OverflowNatural :: Natural -> OverflowNatural
[unOverflowNatural] :: OverflowNatural -> Natural

-- | This class teaches Persistent how to take a custom type and marshal it
--   to and from a <a>PersistValue</a>, allowing it to be stored in a
--   database.
--   
--   <h4><b>Examples</b></h4>
--   
--   <h5>Simple Newtype</h5>
--   
--   You can use <tt>newtype</tt> to add more type safety/readability to a
--   basis type like <a>ByteString</a>. In these cases, just derive
--   <a>PersistField</a> and <tt>PersistFieldSql</tt>:
--   
--   <pre>
--   {-# LANGUAGE GeneralizedNewtypeDeriving #-}
--   
--   newtype HashedPassword = HashedPassword <a>ByteString</a>
--     deriving (Eq, Show, <a>PersistField</a>, PersistFieldSql)
--   </pre>
--   
--   <h5>Smart Constructor Newtype</h5>
--   
--   In this example, we create a <a>PersistField</a> instance for a
--   newtype following the "Smart Constructor" pattern.
--   
--   <pre>
--   {-# LANGUAGE GeneralizedNewtypeDeriving #-}
--   import qualified <a>Data.Text</a> as T
--   import qualified <a>Data.Char</a> as C
--   
--   -- | An American Social Security Number
--   newtype SSN = SSN <a>Text</a>
--    deriving (Eq, Show, PersistFieldSql)
--   
--   mkSSN :: <a>Text</a> -&gt; <a>Either</a> <a>Text</a> SSN
--   mkSSN t = if (T.length t == 9) &amp;&amp; (T.all C.isDigit t)
--    then <a>Right</a> $ SSN t
--    else <a>Left</a> $ "Invalid SSN: " &lt;&gt; t
--   
--   instance <a>PersistField</a> SSN where
--     <a>toPersistValue</a> (SSN t) = <a>PersistText</a> t
--     <a>fromPersistValue</a> (<a>PersistText</a> t) = mkSSN t
--     -- Handle cases where the database does not give us PersistText
--     <a>fromPersistValue</a> x = <a>Left</a> $ "File.hs: When trying to deserialize an SSN: expected PersistText, received: " &lt;&gt; T.pack (show x)
--   </pre>
--   
--   Tips:
--   
--   <ul>
--   <li>This file contain dozens of <a>PersistField</a> instances you can
--   look at for examples.</li>
--   <li>Typically custom <a>PersistField</a> instances will only accept a
--   single <a>PersistValue</a> constructor in
--   <a>fromPersistValue</a>.</li>
--   <li>Internal <a>PersistField</a> instances accept a wide variety of
--   <a>PersistValue</a>s to accomodate e.g. storing booleans as integers,
--   booleans or strings.</li>
--   <li>If you're making a custom instance and using a SQL database,
--   you'll also need <tt>PersistFieldSql</tt> to specify the type of the
--   database column.</li>
--   </ul>
class PersistField a
toPersistValue :: PersistField a => a -> PersistValue
fromPersistValue :: PersistField a => PersistValue -> Either Text a

-- | A type class which is used to witness that a type is safe to insert
--   into the database without providing a primary key.
--   
--   The <tt>TemplateHaskell</tt> function <tt>mkPersist</tt> 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 <tt>Primary</tt> natural key, then this works fine. But
--   if the entity has an <tt>Id</tt> column with no <tt>default=</tt>,
--   then this does a <a>TypeError</a> and forces the user to use
--   <tt>insertKey</tt>.
class SafeToInsert a

-- | This type class is used with the <tt>OverloadedLabels</tt> extension
--   to provide a more convenient means of using the <a>EntityField</a>
--   type. <a>EntityField</a> definitions are prefixed with the type name
--   to avoid ambiguity, but this ambiguity can result in verbose code.
--   
--   If you have a table <tt>User</tt> with a <tt>name Text</tt> field,
--   then the corresponding <a>EntityField</a> is <tt>UserName</tt>. With
--   this, we can write <tt>#name :: <a>EntityField</a> User Text</tt>.
--   
--   What's more fun is that the type is more general: it's actually <tt>
--   #name :: (<a>SymbolToField</a> "name" rec typ) =&gt; EntityField rec
--   typ </tt>
--   
--   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.
class SymbolToField (sym :: Symbol) rec typ | sym rec -> typ
symbolToField :: SymbolToField sym rec typ => EntityField rec typ

-- | Datatype that represents an entity, with both its <a>Key</a> and its
--   Haskell record representation.
--   
--   When using a SQL-based backend (such as SQLite or PostgreSQL), an
--   <a>Entity</a> may take any number of columns depending on how many
--   fields it has. In order to reconstruct your entity on the Haskell
--   side, <tt>persistent</tt> needs all of your entity columns and in the
--   right order. Note that you don't need to worry about this when using
--   <tt>persistent</tt>'s API since everything is handled correctly behind
--   the scenes.
--   
--   However, if you want to issue a raw SQL command that returns an
--   <a>Entity</a>, then you have to be careful with the column order.
--   While you could use <tt>SELECT Entity.* WHERE ...</tt> 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 <tt>persistent</tt>
--   expects (for example, if you add a new field in the middle of you
--   entity definition and then use the migration code --
--   <tt>persistent</tt> 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 <a>rawSql</a> (from the
--   <a>Database.Persist.Sql</a> module) with its /entity selection
--   placeholder/ (a double question mark <tt>??</tt>). Using
--   <tt>rawSql</tt> the query above must be written as <tt>SELECT ?? WHERE
--   ..</tt>. Then <tt>rawSql</tt> will replace <tt>??</tt> with the list
--   of all columns that we need from your entity in the right order. If
--   your query returns two entities (i.e. <tt>(Entity backend a, Entity
--   backend b)</tt>), then you must you use <tt>SELECT ??, ?? WHERE
--   ...</tt>, and so on.
data Entity record
Entity :: Key record -> record -> Entity record
[entityKey] :: Entity record -> Key record
[entityVal] :: Entity record -> record

-- | Value to filter with. Highly dependant on the type of filter used.
data FilterValue typ
[FilterValue] :: forall typ. typ -> FilterValue typ
[FilterValues] :: forall typ. [typ] -> FilterValue typ
[UnsafeValue] :: forall a typ. PersistField a => a -> FilterValue typ

-- | Persistent allows multiple different backends (databases).
type family PersistEntityBackend record

-- | An <a>EntityField</a> is parameterised by the Haskell record it
--   belongs to and the additional type of that field.
--   
--   As of <tt>persistent-2.11.0.0</tt>, it's possible to use the
--   <tt>OverloadedLabels</tt> language extension to refer to
--   <a>EntityField</a> values polymorphically. See the documentation on
--   <a>SymbolToField</a> for more information.
data family EntityField record :: Type -> Type

-- | Construct an <tt><a>Entity</a> record</tt> by providing a value for
--   each of the record's fields.
--   
--   These constructions are equivalent:
--   
--   <pre>
--   entityMattConstructor, entityMattTabulate :: Entity User
--   entityMattConstructor =
--       Entity
--           { entityKey = toSqlKey 123
--           , entityVal =
--               User
--                   { userName = <a>Matt</a>
--                   , userAge = 33
--                   }
--           }
--   
--   entityMattTabulate =
--       tabulateEntity $ \case
--           UserId -&gt;
--               toSqlKey 123
--           UserName -&gt;
--               <a>Matt</a>
--           UserAge -&gt;
--               33
--   </pre>
--   
--   This is a specialization of <a>tabulateEntityA</a>, which allows you
--   to construct an <a>Entity</a> by providing an <a>Applicative</a>
--   action for each field instead of a regular function.
tabulateEntity :: PersistEntity record => (forall a. () => EntityField record a -> a) -> Entity record

-- | Get list of values corresponding to given entity.
entityValues :: PersistEntity record => Entity record -> [PersistValue]

-- | Predefined <tt>toJSON</tt>. The resulting JSON looks like <tt>{"key":
--   1, "value": {"name": ...}}</tt>.
--   
--   The typical usage is:
--   
--   <pre>
--   instance ToJSON (Entity User) where
--       toJSON = keyValueEntityToJSON
--   </pre>
keyValueEntityToJSON :: (PersistEntity record, ToJSON record) => Entity record -> Value

-- | Predefined <tt>parseJSON</tt>. The input JSON looks like <tt>{"key":
--   1, "value": {"name": ...}}</tt>.
--   
--   The typical usage is:
--   
--   <pre>
--   instance FromJSON (Entity User) where
--       parseJSON = keyValueEntityFromJSON
--   </pre>
keyValueEntityFromJSON :: (PersistEntity record, FromJSON record) => Value -> Parser (Entity record)

-- | Predefined <tt>toJSON</tt>. The resulting JSON looks like <tt>{"id":
--   1, "name": ...}</tt>.
--   
--   The typical usage is:
--   
--   <pre>
--   instance ToJSON (Entity User) where
--       toJSON = entityIdToJSON
--   </pre>
entityIdToJSON :: (PersistEntity record, ToJSON record) => Entity record -> Value

-- | Predefined <tt>parseJSON</tt>. The input JSON looks like <tt>{"id": 1,
--   "name": ...}</tt>.
--   
--   The typical usage is:
--   
--   <pre>
--   instance FromJSON (Entity User) where
--       parseJSON = entityIdFromJSON
--   </pre>
entityIdFromJSON :: (PersistEntity record, FromJSON record) => Value -> Parser (Entity record)

-- | Convenience function for getting a free <a>PersistField</a> instance
--   from a type with JSON instances.
--   
--   Example usage in combination with <a>fromPersistValueJSON</a>:
--   
--   <pre>
--   instance PersistField MyData where
--     fromPersistValue = fromPersistValueJSON
--     toPersistValue = toPersistValueJSON
--   </pre>
toPersistValueJSON :: ToJSON a => a -> PersistValue

-- | Convenience function for getting a free <a>PersistField</a> 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 <a>toPersistValueJSON</a>:
--   
--   <pre>
--   instance PersistField MyData where
--     fromPersistValue = fromPersistValueJSON
--     toPersistValue = toPersistValueJSON
--   </pre>
fromPersistValueJSON :: FromJSON a => PersistValue -> Either Text a
class PersistCore backend where {
    data BackendKey backend;
}
data family BackendKey backend

-- | <a>ToBackendKey</a> converts a <a>PersistEntity</a> <a>Key</a> into a
--   <a>BackendKey</a> This can be used by each backend to convert between
--   a <a>Key</a> and a plain Haskell type. For Sql, that is done with
--   <tt>toSqlKey</tt> and <tt>fromSqlKey</tt>.
--   
--   By default, a <a>PersistEntity</a> uses the default <a>BackendKey</a>
--   for its Key and is an instance of ToBackendKey
--   
--   A <a>Key</a> that instead uses a custom type will not be an instance
--   of <a>ToBackendKey</a>.
class (PersistEntity record, PersistEntityBackend record ~ backend, PersistCore backend) => ToBackendKey backend record
toBackendKey :: ToBackendKey backend record => Key record -> BackendKey backend
fromBackendKey :: ToBackendKey backend record => BackendKey backend -> Key record

-- | A convenient alias for common type signatures
type PersistRecordBackend record backend = (PersistEntity record, PersistEntityBackend record ~ BaseBackend backend)

-- | This class witnesses that two backend are compatible, and that you can
--   convert from the <tt>sub</tt> backend into the <tt>sup</tt> backend.
--   This is similar to the <a>HasPersistBackend</a> and
--   <a>IsPersistBackend</a> classes, but where you don't want to fix the
--   type associated with the <a>PersistEntityBackend</a> of a record.
--   
--   Generally speaking, where you might have:
--   
--   <pre>
--   foo ::
--     ( <a>PersistEntity</a> record
--     , <a>PersistEntityBackend</a> record ~ <a>BaseBackend</a> backend
--     , <tt>IsSqlBackend</tt> backend
--     )
--   </pre>
--   
--   this can be replaced with:
--   
--   <pre>
--   foo ::
--     ( <a>PersistEntity</a> record,
--     , <a>PersistEntityBackend</a> record ~ backend
--     , <a>BackendCompatible</a> <tt>SqlBackend</tt> backend
--     )
--   </pre>
--   
--   This works for <tt>SqlReadBackend</tt> because of the <tt>instance
--   <a>BackendCompatible</a> <tt>SqlBackend</tt>
--   <tt>SqlReadBackend</tt></tt>, without needing to go through the
--   <a>BaseBackend</a> type family.
--   
--   Likewise, functions that are currently hardcoded to use
--   <tt>SqlBackend</tt> can be generalized:
--   
--   <pre>
--   -- before:
--   asdf :: <a>ReaderT</a> <tt>SqlBackend</tt> m ()
--   asdf = pure ()
--   
--   -- after:
--   asdf' :: <a>BackendCompatible</a> SqlBackend backend =&gt; ReaderT backend m ()
--   asdf' = <a>withCompatibleBackend</a> asdf
--   </pre>
class BackendCompatible sup sub
projectBackend :: BackendCompatible sup sub => sub -> sup

-- | Class which witnesses that <tt>backend</tt> is essentially the same as
--   <tt>BaseBackend backend</tt>. That is, they're isomorphic and
--   <tt>backend</tt> is just some wrapper over <tt>BaseBackend
--   backend</tt>.
class HasPersistBackend backend => IsPersistBackend backend

-- | Class which allows the plucking of a <tt>BaseBackend backend</tt> from
--   some larger type. For example, <tt> instance HasPersistBackend
--   (SqlReadBackend, Int) where type BaseBackend (SqlReadBackend, Int) =
--   SqlBackend persistBackend = unSqlReadBackend . fst </tt>
class HasPersistBackend backend where {
    type BaseBackend backend;
}
persistBackend :: HasPersistBackend backend => backend -> BaseBackend backend
type family BaseBackend backend

-- | Run a query against a larger backend by plucking out <tt>BaseBackend
--   backend</tt>
--   
--   This is a helper for reusing existing queries when expanding the
--   backend type.
withBaseBackend :: forall backend (m :: Type -> Type) a. HasPersistBackend backend => ReaderT (BaseBackend backend) m a -> ReaderT backend m a

-- | Run a query against a compatible backend, by projecting the backend
--   
--   This is a helper for using queries which run against a specific
--   backend type that your backend is compatible with.
withCompatibleBackend :: forall sup sub (m :: Type -> Type) a. BackendCompatible sup sub => ReaderT sup m a -> ReaderT sub m a
liftPersist :: (MonadIO m, MonadReader backend m) => ReaderT backend IO b -> m b

-- | Same as <a>get</a>, but for a non-null (not Maybe) foreign key. Unsafe
--   unless your database is enforcing that the foreign key is valid.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>,
--   
--   <pre>
--   getJustSpj :: MonadIO m =&gt; ReaderT SqlBackend m User
--   getJustSpj = getJust spjId
--   </pre>
--   
--   <pre>
--   spj &lt;- getJust spjId
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will get this
--   record:
--   
--   <pre>
--   +----+------+-----+
--   | id | name | age |
--   +----+------+-----+
--   |  1 | SPJ  |  40 |
--   +----+------+-----+
--   </pre>
--   
--   <pre>
--   getJustUnknown :: MonadIO m =&gt; ReaderT SqlBackend m User
--   getJustUnknown = getJust unknownId
--   </pre>
--   
--   mrx &lt;- getJustUnknown
--   
--   This just throws an error.
getJust :: forall record backend (m :: Type -> Type). (PersistStoreRead backend, PersistRecordBackend record backend, MonadIO m) => Key record -> ReaderT backend m record

-- | Same as <a>getJust</a>, but returns an <a>Entity</a> instead of just
--   the record.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>,
--   
--   <pre>
--   getJustEntitySpj :: MonadIO m =&gt; ReaderT SqlBackend m (Entity User)
--   getJustEntitySpj = getJustEntity spjId
--   </pre>
--   
--   <pre>
--   spjEnt &lt;- getJustEntitySpj
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will get this
--   entity:
--   
--   <pre>
--   +----+------+-----+
--   | id | name | age |
--   +----+------+-----+
--   |  1 | SPJ  |  40 |
--   +----+------+-----+
--   </pre>
getJustEntity :: forall record backend (m :: Type -> Type). (PersistEntityBackend record ~ BaseBackend backend, MonadIO m, PersistEntity record, PersistStoreRead backend) => Key record -> ReaderT backend m (Entity record)

-- | Curry this to make a convenience function that loads an associated
--   model.
--   
--   <pre>
--   foreign = belongsTo foreignId
--   </pre>
belongsTo :: forall ent1 ent2 backend (m :: Type -> Type). (PersistStoreRead backend, PersistEntity ent1, PersistRecordBackend ent2 backend, MonadIO m) => (ent1 -> Maybe (Key ent2)) -> ent1 -> ReaderT backend m (Maybe ent2)

-- | Same as <a>belongsTo</a>, but uses <tt>getJust</tt> and therefore is
--   similarly unsafe.
belongsToJust :: forall ent1 ent2 backend (m :: Type -> Type). (PersistStoreRead backend, PersistEntity ent1, PersistRecordBackend ent2 backend, MonadIO m) => (ent1 -> Key ent2) -> ent1 -> ReaderT backend m ent2

-- | Like <tt>insert</tt>, but returns the complete <tt>Entity</tt>.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>,
--   
--   <pre>
--   insertHaskellEntity :: MonadIO m =&gt; ReaderT SqlBackend m (Entity User)
--   insertHaskellEntity = insertEntity $ User "Haskell" 81
--   </pre>
--   
--   <pre>
--   haskellEnt &lt;- insertHaskellEntity
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will produce this:
--   
--   <pre>
--   +----+---------+-----+
--   | id |  name   | age |
--   +----+---------+-----+
--   |  1 | SPJ     |  40 |
--   +----+---------+-----+
--   |  2 | Simon   |  41 |
--   +----+---------+-----+
--   |  3 | Haskell |  81 |
--   +----+---------+-----+
--   </pre>
insertEntity :: forall e backend (m :: Type -> Type). (PersistStoreWrite backend, PersistRecordBackend e backend, SafeToInsert e, MonadIO m, HasCallStack) => e -> ReaderT backend m (Entity e)

-- | Like <tt>get</tt>, but returns the complete <tt>Entity</tt>.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>,
--   
--   <pre>
--   getSpjEntity :: MonadIO m =&gt; ReaderT SqlBackend m (Maybe (Entity User))
--   getSpjEntity = getEntity spjId
--   </pre>
--   
--   <pre>
--   mSpjEnt &lt;- getSpjEntity
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will get this
--   entity:
--   
--   <pre>
--   +----+------+-----+
--   | id | name | age |
--   +----+------+-----+
--   |  1 | SPJ  |  40 |
--   +----+------+-----+
--   </pre>
getEntity :: forall e backend (m :: Type -> Type). (PersistStoreRead backend, PersistRecordBackend e backend, MonadIO m) => Key e -> ReaderT backend m (Maybe (Entity e))

-- | Like <a>insertEntity</a> but just returns the record instead of
--   <a>Entity</a>.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>,
--   
--   <pre>
--   insertDaveRecord :: MonadIO m =&gt; ReaderT SqlBackend m User
--   insertDaveRecord = insertRecord $ User "Dave" 50
--   </pre>
--   
--   <pre>
--   dave &lt;- insertDaveRecord
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will produce this:
--   
--   <pre>
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |40   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   |3    |Dave  |50   |
--   +-----+------+-----+
--   </pre>
insertRecord :: forall record backend (m :: Type -> Type). (PersistEntityBackend record ~ BaseBackend backend, PersistEntity record, MonadIO m, PersistStoreWrite backend, SafeToInsert record, HasCallStack) => record -> ReaderT backend m record

-- | A <a>SqlBackend</a> represents a handle or connection to a database.
--   It contains functions and values that allow databases to have more
--   optimized implementations, as well as references that benefit
--   performance and sharing.
--   
--   Instead of using the <a>SqlBackend</a> constructor directly, use the
--   <a>mkSqlBackend</a> function.
--   
--   A <a>SqlBackend</a> is *not* thread-safe. You should not assume that a
--   <a>SqlBackend</a> can be shared among threads and run concurrent
--   queries. This *will* result in problems. Instead, you should create a
--   <tt><tt>Pool</tt> <a>SqlBackend</a></tt>, known as a
--   <tt>ConnectionPool</tt>, and pass that around in multi-threaded
--   applications.
--   
--   To run actions in the <tt>persistent</tt> library, you should use the
--   <tt>runSqlConn</tt> function. If you're using a multithreaded
--   application, use the <tt>runSqlPool</tt> function.
data SqlBackend

-- | 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 <tt>TypeError</tt> instances for records that
--   have 0 unique keys.
class PersistEntity record => AtLeastOneUniqueKey record
requireUniquesP :: AtLeastOneUniqueKey record => record -> NonEmpty (Unique record)

-- | This is an error message. It is used when an entity has multiple
--   unique keys, and the function expects a single unique key.
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 writing instances of
--   <a>OnlyOneUniqueKey</a> for an entity that has no unique keys.
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 class is used to ensure that <a>upsert</a> is only called on
--   records that have a single <a>Unique</a> key. The quasiquoter
--   automatically generates working instances for appropriate records, and
--   generates <tt>TypeError</tt> instances for records that have 0 or
--   multiple unique keys.
class PersistEntity record => OnlyOneUniqueKey record
onlyUniqueP :: OnlyOneUniqueKey record => record -> Unique record

-- | Queries against <a>Unique</a> keys (other than the id <a>Key</a>).
--   
--   Please read the general Persistent documentation to learn how to
--   create <a>Unique</a> keys.
--   
--   Using this with an Entity without a Unique key leads to undefined
--   behavior. A few of these functions require a <i>single</i>
--   <a>Unique</a>, so using an Entity with multiple <a>Unique</a>s is also
--   undefined. In these cases persistent's goal is to throw an exception
--   as soon as possible, but persistent is still transitioning to that.
--   
--   SQL backends automatically create uniqueness constraints, but for
--   MongoDB you must manually place a unique index on a field to have a
--   uniqueness constraint.
class PersistStoreRead backend => PersistUniqueRead backend

-- | Get a record by unique key, if available. Returns also the identifier.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>:
--   
--   <pre>
--   getBySpjName :: MonadIO m  =&gt; ReaderT SqlBackend m (Maybe (Entity User))
--   getBySpjName = getBy $ UniqueUserName "SPJ"
--   </pre>
--   
--   <pre>
--   mSpjEnt &lt;- getBySpjName
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will get this
--   entity:
--   
--   <pre>
--   +----+------+-----+
--   | id | name | age |
--   +----+------+-----+
--   |  1 | SPJ  |  40 |
--   +----+------+-----+
--   </pre>
getBy :: forall record (m :: Type -> Type). (PersistUniqueRead backend, MonadIO m, PersistRecordBackend record backend) => Unique record -> ReaderT backend m (Maybe (Entity record))

-- | Returns True if a record with this unique key exists, otherwise False.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>:
--   
--   <pre>
--   existsBySpjName :: MonadIO m  =&gt; ReaderT SqlBackend m Bool
--   existsBySpjName = existsBy $ UniqueUserName "SPJ"
--   </pre>
--   
--   <pre>
--   spjEntExists &lt;- existsBySpjName
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will return the
--   value True.
existsBy :: forall record (m :: Type -> Type). (PersistUniqueRead backend, MonadIO m, PersistRecordBackend record backend) => Unique record -> ReaderT backend m Bool

-- | Given a proxy for a <a>PersistEntity</a> record, this returns the sole
--   <a>UniqueDef</a> for that entity.
onlyOneUniqueDef :: (OnlyOneUniqueKey record, Monad proxy) => proxy record -> UniqueDef

-- | Like <a>insertEntity</a>, but returns <a>Nothing</a> when the record
--   couldn't be inserted because of a uniqueness constraint.
--   
--   <h3><b>Example usage</b></h3>
--   
--   We use <a>schema-2</a> and <a>dataset-1</a> here.
--   
--   <pre>
--   insertUniqueSpjEntity :: MonadIO m =&gt; ReaderT SqlBackend m (Maybe (Entity User))
--   insertUniqueSpjEntity = insertUniqueEntity $ User "SPJ" 50
--   </pre>
--   
--   <pre>
--   mSpjEnt &lt;- insertUniqueSpjEntity
--   </pre>
--   
--   The above query results <a>Nothing</a> as SPJ already exists.
--   
--   <pre>
--   insertUniqueAlexaEntity :: MonadIO m =&gt; ReaderT SqlBackend m (Maybe (Entity User))
--   insertUniqueAlexaEntity = insertUniqueEntity $ User "Alexa" 3
--   </pre>
--   
--   <pre>
--   mAlexaEnt &lt;- insertUniqueSpjEntity
--   </pre>
--   
--   Because there's no such unique keywords of the given record, the above
--   query when applied on <a>dataset-1</a>, will produce this:
--   
--   <pre>
--   +----+-------+-----+
--   | id | name  | age |
--   +----+-------+-----+
--   |  1 | SPJ   |  40 |
--   +----+-------+-----+
--   |  2 | Simon |  41 |
--   +----+-------+-----+
--   |  3 | Alexa |   3 |
--   +----+-------+-----+
--   </pre>
insertUniqueEntity :: forall record backend (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend, PersistUniqueWrite backend, SafeToInsert record) => record -> ReaderT backend m (Maybe (Entity record))

-- | Return the single unique key for a record.
--   
--   <h3><b>Example usage</b></h3>
--   
--   We use shcema-1 and <a>dataset-1</a> here.
--   
--   <pre>
--   onlySimonConst :: MonadIO m =&gt; ReaderT SqlBackend m (Unique User)
--   onlySimonConst = onlyUnique $ User "Simon" 999
--   </pre>
--   
--   <pre>
--   mSimonConst &lt;- onlySimonConst
--   </pre>
--   
--   <tt>mSimonConst</tt> would be Simon's uniqueness constraint. Note that
--   <tt>onlyUnique</tt> doesn't work if there're more than two
--   constraints. It will fail with a type error instead.
onlyUnique :: forall record backend (m :: Type -> Type). (MonadIO m, PersistUniqueWrite backend, PersistRecordBackend record backend, OnlyOneUniqueKey record) => record -> ReaderT backend m (Unique record)

-- | A modification of <a>getBy</a>, which takes the <a>PersistEntity</a>
--   itself instead of a <a>Unique</a> record. Returns a record matching
--   <i>one</i> of the unique keys. This function makes the most sense on
--   entities with a single <a>Unique</a> constructor.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>,
--   
--   getBySpjValue :: MonadIO m =&gt; ReaderT SqlBackend m (Maybe (Entity
--   User)) getBySpjValue = getByValue $ User <a>SPJ</a> 999
--   
--   <pre>
--   mSpjEnt &lt;- getBySpjValue
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will get this
--   record:
--   
--   <pre>
--   +----+------+-----+
--   | id | name | age |
--   +----+------+-----+
--   |  1 | SPJ  |  40 |
--   +----+------+-----+
--   </pre>
getByValue :: forall record (m :: Type -> Type) backend. (MonadIO m, PersistUniqueRead backend, PersistRecordBackend record backend, AtLeastOneUniqueKey record) => record -> ReaderT backend m (Maybe (Entity record))

-- | Attempt to replace the record of the given key with the given new
--   record. First query the unique fields to make sure the replacement
--   maintains uniqueness constraints.
--   
--   Return <a>Nothing</a> if the replacement was made. If uniqueness is
--   violated, return a <a>Just</a> with the <a>Unique</a> violation
replaceUnique :: forall record backend (m :: Type -> Type). (MonadIO m, Eq (Unique record), PersistRecordBackend record backend, PersistUniqueWrite backend) => Key record -> record -> ReaderT backend m (Maybe (Unique record))

-- | Check whether there are any conflicts for unique keys with this entity
--   and existing entities in the database.
--   
--   Returns <a>Nothing</a> if the entity would be unique, and could thus
--   safely be inserted. on a conflict returns the conflicting key
--   
--   <h3><b>Example usage</b></h3>
--   
--   We use <a>schema-1</a> and <a>dataset-1</a> here.
--   
--   This would be <a>Nothing</a>:
--   
--   <pre>
--   mAlanConst &lt;- checkUnique $ User "Alan" 70
--   </pre>
--   
--   While this would be <a>Just</a> because SPJ already exists:
--   
--   <pre>
--   mSpjConst &lt;- checkUnique $ User "SPJ" 60
--   </pre>
checkUnique :: forall record backend (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend, PersistUniqueRead backend) => record -> ReaderT backend m (Maybe (Unique record))

-- | Check whether there are any conflicts for unique keys with this entity
--   and existing entities in the database.
--   
--   Returns <a>Nothing</a> if the entity would stay unique, and could thus
--   safely be updated. on a conflict returns the conflicting key
--   
--   This is similar to <a>checkUnique</a>, except it's useful for updating
--   - when the particular entity already exists, it would normally
--   conflict with itself. This variant ignores those conflicts
--   
--   <h3><b>Example usage</b></h3>
--   
--   We use <a>schema-1</a> and <a>dataset-1</a> here.
--   
--   This would be <a>Nothing</a>:
--   
--   <pre>
--   mAlanConst &lt;- checkUnique $ User "Alan" 70
--   </pre>
--   
--   While this would be <a>Just</a> because SPJ already exists:
--   
--   <pre>
--   mSpjConst &lt;- checkUnique $ User "SPJ" 60
--   </pre>
checkUniqueUpdateable :: forall record backend (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend, PersistUniqueRead backend) => Entity record -> ReaderT backend m (Maybe (Unique record))

-- | Backends supporting conditional write operations
class (PersistQueryRead backend, PersistStoreWrite backend) => PersistQueryWrite backend

-- | Update individual fields on any record matching the given criterion.
updateWhere :: forall (m :: Type -> Type) record. (PersistQueryWrite backend, MonadIO m, PersistRecordBackend record backend) => [Filter record] -> [Update record] -> ReaderT backend m ()

-- | Delete all records matching the given criterion.
deleteWhere :: forall (m :: Type -> Type) record. (PersistQueryWrite backend, MonadIO m, PersistRecordBackend record backend) => [Filter record] -> ReaderT backend m ()

-- | Backends supporting conditional read operations.
class (PersistCore backend, PersistStoreRead backend) => PersistQueryRead backend

-- | Get all records matching the given criterion in the specified order.
--   Returns also the identifiers.
--   
--   NOTE: This function returns an <a>Acquire</a> and a <a>ConduitM</a>,
--   which implies that it streams from the database. It does not. Please
--   use <a>selectList</a> to simplify the code. If you want streaming
--   behavior, consider <tt>persistent-pagination</tt> which efficiently
--   chunks a query into ranges, or investigate a backend-specific
--   streaming solution.
selectSourceRes :: forall record (m1 :: Type -> Type) (m2 :: Type -> Type). (PersistQueryRead backend, PersistRecordBackend record backend, MonadIO m1, MonadIO m2) => [Filter record] -> [SelectOpt record] -> ReaderT backend m1 (Acquire (ConduitM () (Entity record) m2 ()))

-- | Get just the first record for the criterion.
selectFirst :: forall (m :: Type -> Type) record. (PersistQueryRead backend, MonadIO m, PersistRecordBackend record backend) => [Filter record] -> [SelectOpt record] -> ReaderT backend m (Maybe (Entity record))

-- | Get the <a>Key</a>s of all records matching the given criterion.
selectKeysRes :: forall (m1 :: Type -> Type) (m2 :: Type -> Type) record. (PersistQueryRead backend, MonadIO m1, MonadIO m2, PersistRecordBackend record backend) => [Filter record] -> [SelectOpt record] -> ReaderT backend m1 (Acquire (ConduitM () (Key record) m2 ()))

-- | Get the <a>Key</a>s of all records matching the given criterion.
--   
--   For an example, see <a>selectList</a>.
selectKeys :: forall record backend (m :: Type -> Type). (PersistQueryRead backend, MonadResource m, PersistRecordBackend record backend, MonadReader backend m) => [Filter record] -> [SelectOpt record] -> ConduitM () (Key record) m ()

-- | 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.
type PersistStore a = PersistStoreWrite a

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

-- | A backend which is a wrapper around <tt>SqlBackend</tt>.
type IsSqlBackend backend = (IsPersistBackend backend, BaseBackend backend ~ SqlBackend)

-- | Like <tt>SqlPersistT</tt> but compatible with any SQL backend which
--   can handle read and write queries.
type SqlWriteT (m :: Type -> Type) a = forall backend. SqlBackendCanWrite backend => ReaderT backend m a

-- | Like <tt>SqlPersistT</tt> but compatible with any SQL backend which
--   can handle read queries.
type SqlReadT (m :: Type -> Type) a = forall backend. SqlBackendCanRead backend => ReaderT backend m a

-- | A constraint synonym which witnesses that a backend is SQL and can run
--   read and write queries.
type SqlBackendCanWrite backend = (SqlBackendCanRead backend, PersistQueryWrite backend, PersistStoreWrite backend, PersistUniqueWrite backend)

-- | A constraint synonym which witnesses that a backend is SQL and can run
--   read queries.
type SqlBackendCanRead backend = (BackendCompatible SqlBackend backend, PersistQueryRead backend, PersistStoreRead backend, PersistUniqueRead backend)

-- | An SQL backend which can handle read or write queries
--   
--   The constructor was exposed in 2.10.0
newtype SqlWriteBackend
SqlWriteBackend :: SqlBackend -> SqlWriteBackend
[unSqlWriteBackend] :: SqlWriteBackend -> SqlBackend

-- | An SQL backend which can only handle read queries
--   
--   The constructor was exposed in 2.10.0.
newtype SqlReadBackend
SqlReadBackend :: SqlBackend -> SqlReadBackend
[unSqlReadBackend] :: SqlReadBackend -> SqlBackend

-- | Useful for running a write query against an untagged backend with
--   unknown capabilities.
writeToUnknown :: forall (m :: Type -> Type) a. Monad m => ReaderT SqlWriteBackend m a -> ReaderT SqlBackend m a

-- | Useful for running a read query against a backend with read and write
--   capabilities.
readToWrite :: forall (m :: Type -> Type) a. Monad m => ReaderT SqlReadBackend m a -> ReaderT SqlWriteBackend m a

-- | Useful for running a read query against a backend with unknown
--   capabilities.
readToUnknown :: forall (m :: Type -> Type) a. Monad m => ReaderT SqlReadBackend m a -> ReaderT SqlBackend m a

-- | Values to configure a pool of database connections. See
--   <a>Data.Pool</a> for details.
data ConnectionPoolConfig
ConnectionPoolConfig :: Int -> NominalDiffTime -> Int -> ConnectionPoolConfig

-- | How many stripes to divide the pool into. See <a>Data.Pool</a> for
--   details. Default: 1.
[connectionPoolConfigStripes] :: ConnectionPoolConfig -> Int

-- | How long connections can remain idle before being disposed of, in
--   seconds. Default: 600
[connectionPoolConfigIdleTimeout] :: ConnectionPoolConfig -> NominalDiffTime

-- | How many connections should be held in the connection pool. Default:
--   10
[connectionPoolConfigSize] :: ConnectionPoolConfig -> Int
type ConnectionPool = Pool SqlBackend
type SqlPersistM = SqlPersistT NoLoggingT ResourceT IO
type SqlPersistT = ReaderT SqlBackend
data PersistentSqlException
StatementAlreadyFinalized :: Text -> PersistentSqlException
Couldn'tGetSQLConnection :: PersistentSqlException

-- | This value specifies how a field references another table.
data ColumnReference
ColumnReference :: !EntityNameDB -> !ConstraintNameDB -> !FieldCascade -> ColumnReference

-- | The table name that the
[crTableName] :: ColumnReference -> !EntityNameDB

-- | The name of the foreign key constraint.
[crConstraintName] :: ColumnReference -> !ConstraintNameDB

-- | Whether or not updates/deletions to the referenced table cascade to
--   this table.
[crFieldCascade] :: ColumnReference -> !FieldCascade

-- | Initializes a ConnectionPoolConfig with default values. See the
--   documentation of <a>ConnectionPoolConfig</a> for each field's default
--   value.
defaultConnectionPoolConfig :: ConnectionPoolConfig

-- | Record of functions to override the default behavior in
--   <a>mkColumns</a>. It is recommended you initialize this with
--   <a>emptyBackendSpecificOverrides</a> and override the default values,
--   so that as new fields are added, your code still compiles.
--   
--   For added safety, use the <tt>getBackendSpecific*</tt> and
--   <tt>setBackendSpecific*</tt> functions, as a breaking change to the
--   record field labels won't be reflected in a major version bump of the
--   library.
data BackendSpecificOverrides

-- | If the override is defined, then this returns a function that accepts
--   an entity name and field name and provides the <a>ConstraintNameDB</a>
--   for the foreign key constraint.
--   
--   An abstract accessor for the <a>BackendSpecificOverrides</a>
getBackendSpecificForeignKeyName :: BackendSpecificOverrides -> Maybe (EntityNameDB -> FieldNameDB -> ConstraintNameDB)

-- | Set the backend's foreign key generation function to this value.
setBackendSpecificForeignKeyName :: (EntityNameDB -> FieldNameDB -> ConstraintNameDB) -> BackendSpecificOverrides -> BackendSpecificOverrides

-- | Creates an empty <a>BackendSpecificOverrides</a> (i.e. use the default
--   behavior; no overrides)
emptyBackendSpecificOverrides :: BackendSpecificOverrides
defaultAttribute :: [FieldAttr] -> Maybe Text

-- | Create the list of columns for the given entity.
mkColumns :: [EntityDef] -> EntityDef -> BackendSpecificOverrides -> ([Column], [UniqueDef], [ForeignDef])

-- | A more general way to convert instances of <a>ToJSON</a> type class to
--   strict text <a>Text</a>.
toJsonText :: ToJSON j => j -> Text

-- | Tells Persistent what database column type should be used to store a
--   Haskell type.
--   
--   <h4><b>Examples</b></h4>
--   
--   <h5>Simple Boolean Alternative</h5>
--   
--   <pre>
--   data Switch = On | Off
--     deriving (Show, Eq)
--   
--   instance <a>PersistField</a> Switch where
--     <a>toPersistValue</a> s = case s of
--       On -&gt; <a>PersistBool</a> True
--       Off -&gt; <a>PersistBool</a> False
--     <a>fromPersistValue</a> (<a>PersistBool</a> b) = if b then <a>Right</a> On else <a>Right</a> Off
--     <a>fromPersistValue</a> x = Left $ "File.hs: When trying to deserialize a Switch: expected PersistBool, received: " &lt;&gt; T.pack (show x)
--   
--   instance <a>PersistFieldSql</a> Switch where
--     <a>sqlType</a> _ = <a>SqlBool</a>
--   </pre>
--   
--   <h5>Non-Standard Database Types</h5>
--   
--   If your database supports non-standard types, such as Postgres'
--   <tt>uuid</tt>, you can use <a>SqlOther</a> to use them:
--   
--   <pre>
--   import qualified Data.UUID as UUID
--   instance <a>PersistField</a> UUID where
--     <a>toPersistValue</a> = <tt>PersistLiteralEncoded</tt> . toASCIIBytes
--     <a>fromPersistValue</a> (<tt>PersistLiteralEncoded</tt> uuid) =
--       case fromASCIIBytes uuid of
--         <a>Nothing</a> -&gt; <a>Left</a> $ "Model/CustomTypes.hs: Failed to deserialize a UUID; received: " &lt;&gt; T.pack (show uuid)
--         <a>Just</a> uuid' -&gt; <a>Right</a> uuid'
--     <a>fromPersistValue</a> x = Left $ "File.hs: When trying to deserialize a UUID: expected PersistLiteralEncoded, received: "-- &gt;  &lt;&gt; T.pack (show x)
--   
--   instance <a>PersistFieldSql</a> UUID where
--     <a>sqlType</a> _ = <a>SqlOther</a> "uuid"
--   </pre>
--   
--   <h5>User Created Database Types</h5>
--   
--   Similarly, some databases support creating custom types, e.g.
--   Postgres' <a>DOMAIN</a> and <a>ENUM</a> features. You can use
--   <a>SqlOther</a> to specify a custom type:
--   
--   <pre>
--   CREATE DOMAIN ssn AS text
--         CHECK ( value ~ '^[0-9]{9}$');
--   </pre>
--   
--   <pre>
--   instance <tt>PersistFieldSQL</tt> SSN where
--     <a>sqlType</a> _ = <a>SqlOther</a> "ssn"
--   </pre>
--   
--   <pre>
--   CREATE TYPE rainbow_color AS ENUM ('red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet');
--   </pre>
--   
--   <pre>
--   instance <tt>PersistFieldSQL</tt> RainbowColor where
--     <a>sqlType</a> _ = <a>SqlOther</a> "rainbow_color"
--   </pre>
class PersistField a => PersistFieldSql a
sqlType :: PersistFieldSql a => Proxy a -> SqlType

-- | This newtype wrapper is useful when selecting an entity out of the
--   database and you want to provide a prefix to the table being selected.
--   
--   Consider this raw SQL query:
--   
--   <pre>
--   SELECT ??
--   FROM my_long_table_name AS mltn
--   INNER JOIN other_table AS ot
--      ON mltn.some_col = ot.other_col
--   WHERE ...
--   </pre>
--   
--   We don't want to refer to <tt>my_long_table_name</tt> every time, so
--   we create an alias. If we want to select it, we have to tell the raw
--   SQL quasi-quoter that we expect the entity to be prefixed with some
--   other name.
--   
--   We can give the above query a type with this, like:
--   
--   <pre>
--   getStuff :: <a>SqlPersistM</a> [<a>EntityWithPrefix</a> "mltn" MyLongTableName]
--   getStuff = rawSql queryText []
--   </pre>
--   
--   The <a>EntityWithPrefix</a> bit is a boilerplate newtype wrapper, so
--   you can remove it with <a>unPrefix</a>, like this:
--   
--   <pre>
--   getStuff :: <a>SqlPersistM</a> [<a>Entity</a> MyLongTableName]
--   getStuff = <a>unPrefix</a> @"mltn" <a>&lt;$&gt;</a> <tt>rawSql</tt> queryText []
--   </pre>
--   
--   The <tt> symbol is a "type application" and requires the
--   </tt>TypeApplications@ language extension.
newtype EntityWithPrefix (prefix :: Symbol) record
EntityWithPrefix :: Entity record -> EntityWithPrefix (prefix :: Symbol) record
[unEntityWithPrefix] :: EntityWithPrefix (prefix :: Symbol) record -> Entity record

-- | Class for data types that may be retrived from a <tt>rawSql</tt>
--   query.
class RawSql a

-- | Number of columns that this data type needs and the list of
--   substitutions for <tt>SELECT</tt> placeholders <tt>??</tt>.
rawSqlCols :: RawSql a => (Text -> Text) -> a -> (Int, [Text])

-- | A string telling the user why the column count is what it is.
rawSqlColCountReason :: RawSql a => a -> String

-- | Transform a row of the result into the data type.
rawSqlProcessRow :: RawSql a => [PersistValue] -> Either Text a

-- | A helper function to tell GHC what the <a>EntityWithPrefix</a> prefix
--   should be. This allows you to use a type application to specify the
--   prefix, instead of specifying the etype on the result.
--   
--   As an example, here's code that uses this:
--   
--   <pre>
--   myQuery :: <a>SqlPersistM</a> [<a>Entity</a> Person]
--   myQuery = fmap (unPrefix @"p") <a>$</a> rawSql query []
--     where
--       query = "SELECT ?? FROM person AS p"
--   </pre>
unPrefix :: forall (prefix :: Symbol) record. EntityWithPrefix prefix record -> Entity record
rawQuery :: forall (m :: Type -> Type) env. (MonadResource m, MonadReader env m, BackendCompatible SqlBackend env) => Text -> [PersistValue] -> ConduitM () [PersistValue] m ()
rawQueryRes :: forall (m1 :: Type -> Type) (m2 :: Type -> Type) env. (MonadIO m1, MonadIO m2, BackendCompatible SqlBackend env) => Text -> [PersistValue] -> ReaderT env m1 (Acquire (ConduitM () [PersistValue] m2 ()))

-- | Execute a raw SQL statement
rawExecute :: forall (m :: Type -> Type) backend. (MonadIO m, BackendCompatible SqlBackend backend) => Text -> [PersistValue] -> ReaderT backend m ()

-- | Execute a raw SQL statement and return the number of rows it has
--   modified.
rawExecuteCount :: forall (m :: Type -> Type) backend. (MonadIO m, BackendCompatible SqlBackend backend) => Text -> [PersistValue] -> ReaderT backend m Int64
getStmtConn :: SqlBackend -> Text -> IO Statement

-- | Get a connection from the pool, run the given action, and then return
--   the connection to the pool.
--   
--   This function performs the given action in a transaction. If an
--   exception occurs during the action, then the transaction is rolled
--   back.
--   
--   Note: This function previously timed out after 2 seconds, but this
--   behavior was buggy and caused more problems than it solved. Since
--   version 2.1.2, it performs no timeout checks.
runSqlPool :: forall backend m a. (MonadUnliftIO m, BackendCompatible SqlBackend backend) => ReaderT backend m a -> Pool backend -> m a

-- | Like <a>runSqlPool</a>, but supports specifying an isolation level.
runSqlPoolWithIsolation :: forall backend m a. (MonadUnliftIO m, BackendCompatible SqlBackend backend) => ReaderT backend m a -> Pool backend -> IsolationLevel -> m a

-- | Like <a>runSqlPool</a>, but does not surround the action in a
--   transaction. This action might leave your database in a weird state.
runSqlPoolNoTransaction :: forall backend m a. (MonadUnliftIO m, BackendCompatible SqlBackend backend) => ReaderT backend m a -> Pool backend -> Maybe IsolationLevel -> m a

-- | This function is how <a>runSqlPool</a> and
--   <a>runSqlPoolNoTransaction</a> are defined. In addition to the action
--   to be performed and the <a>Pool</a> of conections to use, we give you
--   the opportunity to provide three actions - initialize, afterwards, and
--   onException.
runSqlPoolWithHooks :: forall backend m a before after onException. (MonadUnliftIO m, BackendCompatible SqlBackend backend) => ReaderT backend m a -> Pool backend -> Maybe IsolationLevel -> (backend -> m before) -> (backend -> m after) -> (backend -> SomeException -> m onException) -> m a

-- | This function is how <a>runSqlPoolWithHooks</a> is defined.
--   
--   It's currently the most general function for using a SQL pool.
runSqlPoolWithExtensibleHooks :: forall backend m a. (MonadUnliftIO m, BackendCompatible SqlBackend backend) => ReaderT backend m a -> Pool backend -> Maybe IsolationLevel -> SqlPoolHooks m backend -> m a

-- | Starts a new transaction on the connection. When the acquired
--   connection is released the transaction is committed and the connection
--   returned to the pool.
--   
--   Upon an exception the transaction is rolled back and the connection
--   destroyed.
--   
--   This is equivalent to <a>runSqlConn</a> but does not incur the
--   <a>MonadUnliftIO</a> constraint, meaning it can be used within, for
--   example, a <tt>Conduit</tt> pipeline.
acquireSqlConn :: (MonadReader backend m, BackendCompatible SqlBackend backend) => m (Acquire backend)

-- | Like <a>acquireSqlConn</a>, but lets you specify an explicit isolation
--   level.
acquireSqlConnWithIsolation :: (MonadReader backend m, BackendCompatible SqlBackend backend) => IsolationLevel -> m (Acquire backend)
runSqlConn :: forall backend m a. (MonadUnliftIO m, BackendCompatible SqlBackend backend) => ReaderT backend m a -> backend -> m a

-- | Like <a>runSqlConn</a>, but supports specifying an isolation level.
runSqlConnWithIsolation :: forall backend m a. (MonadUnliftIO m, BackendCompatible SqlBackend backend) => ReaderT backend m a -> backend -> IsolationLevel -> m a
runSqlPersistM :: BackendCompatible SqlBackend backend => ReaderT backend (NoLoggingT (ResourceT IO)) a -> backend -> IO a
runSqlPersistMPool :: BackendCompatible SqlBackend backend => ReaderT backend (NoLoggingT (ResourceT IO)) a -> Pool backend -> IO a
liftSqlPersistMPool :: forall backend m a. (MonadIO m, BackendCompatible SqlBackend backend) => ReaderT backend (NoLoggingT (ResourceT IO)) a -> Pool backend -> m a
withSqlPool :: forall backend m a. (MonadLoggerIO m, MonadUnliftIO m, BackendCompatible SqlBackend backend) => (LogFunc -> IO backend) -> Int -> (Pool backend -> m a) -> m a

-- | Creates a pool of connections to a SQL database which can be used by
--   the <tt>Pool backend -&gt; m a</tt> function. After the function
--   completes, the connections are destroyed.
withSqlPoolWithConfig :: forall backend m a. (MonadLoggerIO m, MonadUnliftIO m, BackendCompatible SqlBackend backend) => (LogFunc -> IO backend) -> ConnectionPoolConfig -> (Pool backend -> m a) -> m a
createSqlPool :: forall backend m. (MonadLoggerIO m, MonadUnliftIO m, BackendCompatible SqlBackend backend) => (LogFunc -> IO backend) -> Int -> m (Pool backend)

-- | Creates a pool of connections to a SQL database.
createSqlPoolWithConfig :: (MonadLoggerIO m, MonadUnliftIO m, BackendCompatible SqlBackend backend) => (LogFunc -> IO backend) -> ConnectionPoolConfig -> m (Pool backend)

-- | Create a connection and run sql queries within it. This function
--   automatically closes the connection on it's completion.
--   
--   <h3><b>Example usage</b></h3>
--   
--   <pre>
--   {-# LANGUAGE GADTs #-}
--   {-# LANGUAGE ScopedTypeVariables #-}
--   {-# LANGUAGE OverloadedStrings #-}
--   {-# LANGUAGE MultiParamTypeClasses #-}
--   {-# LANGUAGE TypeFamilies#-}
--   {-# LANGUAGE TemplateHaskell#-}
--   {-# LANGUAGE QuasiQuotes#-}
--   {-# LANGUAGE GeneralizedNewtypeDeriving #-}
--   
--   import Control.Monad.IO.Class  (liftIO)
--   import Control.Monad.Logger
--   import Conduit
--   import Database.Persist
--   import Database.Sqlite
--   import Database.Persist.Sqlite
--   import Database.Persist.TH
--   
--   share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
--   Person
--     name String
--     age Int Maybe
--     deriving Show
--   |]
--   
--   openConnection :: LogFunc -&gt; IO SqlBackend
--   openConnection logfn = do
--    conn &lt;- open "/home/sibi/test.db"
--    wrapConnection conn logfn
--   
--   main :: IO ()
--   main = do
--     runNoLoggingT $ runResourceT $ withSqlConn openConnection (\backend -&gt;
--                                         flip runSqlConn backend $ do
--                                           runMigration migrateAll
--                                           insert_ $ Person "John doe" $ Just 35
--                                           insert_ $ Person "Divya" $ Just 36
--                                           (pers :: [Entity Person]) &lt;- selectList [] []
--                                           liftIO $ print pers
--                                           return ()
--                                        )
--   </pre>
--   
--   On executing it, you get this output:
--   
--   <pre>
--   Migrating: CREATE TABLE "person"("id" INTEGER PRIMARY KEY,"name" VARCHAR NOT NULL,"age" INTEGER NULL)
--   [Entity {entityKey = PersonKey {unPersonKey = SqlBackendKey {unSqlBackendKey = 1}}, entityVal = Person {personName = "John doe", personAge = Just 35}},Entity {entityKey = PersonKey {unPersonKey = SqlBackendKey {unSqlBackendKey = 2}}, entityVal = Person {personName = "Hema", personAge = Just 36}}]
--   </pre>
withSqlConn :: forall backend m a. (MonadUnliftIO m, MonadLoggerIO m, BackendCompatible SqlBackend backend) => (LogFunc -> IO backend) -> (backend -> m a) -> m a
close' :: BackendCompatible SqlBackend backend => backend -> IO ()
withRawQuery :: forall (m :: Type -> Type) a. MonadIO m => Text -> [PersistValue] -> ConduitM [PersistValue] Void IO a -> ReaderT SqlBackend m a
toSqlKey :: ToBackendKey SqlBackend record => Int64 -> Key record
fromSqlKey :: ToBackendKey SqlBackend record => Key record -> Int64

-- | get the SQL string for the table that a PersistEntity represents
--   Useful for raw SQL queries
--   
--   Your backend may provide a more convenient tableName function which
--   does not operate in a Monad
getTableName :: forall record (m :: Type -> Type) backend. (PersistEntity record, BackendCompatible SqlBackend backend, Monad m) => record -> ReaderT backend m Text

-- | useful for a backend to implement tableName by adding escaping
tableDBName :: PersistEntity record => record -> EntityNameDB

-- | get the SQL string for the field that an EntityField represents Useful
--   for raw SQL queries
--   
--   Your backend may provide a more convenient fieldName function which
--   does not operate in a Monad
getFieldName :: forall record typ (m :: Type -> Type) backend. (PersistEntity record, PersistEntityBackend record ~ SqlBackend, BackendCompatible SqlBackend backend, Monad m) => EntityField record typ -> ReaderT backend m Text

-- | useful for a backend to implement fieldName by adding escaping
fieldDBName :: PersistEntity record => EntityField record typ -> FieldNameDB

-- | Used when determining how to prefix a column name in a <tt>WHERE</tt>
--   clause.
data FilterTablePrefix

-- | Prefix the column with the table name. This is useful if the column
--   name might be ambiguous.
PrefixTableName :: FilterTablePrefix

-- | Prefix the column name with the <tt>EXCLUDED</tt> keyword. This is
--   used with the Postgresql backend when doing <tt>ON CONFLICT DO
--   UPDATE</tt> clauses - see the documentation on <tt>upsertWhere</tt>
--   and <tt>upsertManyWhere</tt>.
PrefixExcluded :: FilterTablePrefix

-- | Render a <tt>[<a>Filter</a> record]</tt> into a <a>Text</a> value
--   suitable for inclusion into a SQL query.
filterClause :: PersistEntity val => Maybe FilterTablePrefix -> SqlBackend -> [Filter val] -> Text

-- | Render a <tt>[<a>Filter</a> record]</tt> into a <a>Text</a> value
--   suitable for inclusion into a SQL query, as well as the
--   <tt>[<a>PersistValue</a>]</tt> to properly fill in the <tt>?</tt>
--   place holders.
filterClauseWithVals :: PersistEntity val => Maybe FilterTablePrefix -> SqlBackend -> [Filter val] -> (Text, [PersistValue])

-- | Render a <tt>[<a>SelectOpt</a> record]</tt> made up *only* of
--   <a>Asc</a> and <a>Desc</a> constructors into a <a>Text</a> value
--   suitable for inclusion into a SQL query.
orderClause :: PersistEntity val => Maybe FilterTablePrefix -> SqlBackend -> [SelectOpt val] -> Text

-- | Generates sql for limit and offset for postgres, sqlite and mysql.
decorateSQLWithLimitOffset :: Text -> (Int, Int) -> Text -> Text

-- | An exception indicating that Persistent refused to run some unsafe
--   migrations. Contains a list of pairs where the Bool tracks whether the
--   migration was unsafe (True means unsafe), and the Sql is the sql
--   statement for the migration.
newtype PersistUnsafeMigrationException
PersistUnsafeMigrationException :: [(Bool, Sql)] -> PersistUnsafeMigrationException

-- | A <a>Migration</a> is a four level monad stack consisting of:
--   
--   <ul>
--   <li><tt><a>WriterT</a> [<a>Text</a>]</tt> representing a log of errors
--   in the migrations.</li>
--   <li><tt><a>WriterT</a> <a>CautiousMigration</a></tt> representing a
--   list of migrations to run, along with whether or not they are
--   safe.</li>
--   <li><tt><a>ReaderT</a> <a>SqlBackend</a></tt>, aka the
--   <a>SqlPersistT</a> transformer for database interop.</li>
--   <li><tt><a>IO</a></tt> for arbitrary IO.</li>
--   </ul>
type Migration = WriterT [Text] WriterT CautiousMigration ReaderT SqlBackend IO ()

-- | A list of SQL operations, marked with a safety flag. If the
--   <a>Bool</a> is <a>True</a>, then the operation is *unsafe* - it might
--   be destructive, or otherwise not idempotent. If the <a>Bool</a> is
--   <a>False</a>, then the operation is *safe*, and can be run repeatedly
--   without issues.
type CautiousMigration = [(Bool, Sql)]
type Sql = Text

-- | Given a <a>Migration</a>, this parses it and returns either a list of
--   errors associated with the migration or a list of migrations to do.
parseMigration :: forall (m :: Type -> Type). (HasCallStack, MonadIO m) => Migration -> ReaderT SqlBackend m (Either [Text] CautiousMigration)

-- | Like <a>parseMigration</a>, but instead of returning the value in an
--   <a>Either</a> value, it calls <a>error</a> on the error values.
parseMigration' :: forall (m :: Type -> Type). (HasCallStack, MonadIO m) => Migration -> ReaderT SqlBackend m CautiousMigration

-- | Prints a migration.
printMigration :: forall (m :: Type -> Type). (HasCallStack, MonadIO m) => Migration -> ReaderT SqlBackend m ()

-- | Convert a <a>Migration</a> to a list of <a>Text</a> values
--   corresponding to their <a>Sql</a> statements.
showMigration :: forall (m :: Type -> Type). (HasCallStack, MonadIO m) => Migration -> ReaderT SqlBackend m [Text]

-- | Return all of the <a>Sql</a> values associated with the given
--   migration. Calls <a>error</a> if there's a parse error on any
--   migration.
getMigration :: forall (m :: Type -> Type). (MonadIO m, HasCallStack) => Migration -> ReaderT SqlBackend m [Sql]

-- | Runs a migration. If the migration fails to parse or if any of the
--   migrations are unsafe, then this throws a
--   <a>PersistUnsafeMigrationException</a>.
runMigration :: forall (m :: Type -> Type). MonadIO m => Migration -> ReaderT SqlBackend m ()

-- | Same as <a>runMigration</a>, but does not report the individual
--   migrations on stderr. Instead it returns a list of the executed SQL
--   commands.
--   
--   This is a safer/more robust alternative to <a>runMigrationSilent</a>,
--   but may be less silent for some persistent implementations, most
--   notably persistent-postgresql
runMigrationQuiet :: forall (m :: Type -> Type). MonadIO m => Migration -> ReaderT SqlBackend m [Text]

-- | Same as <a>runMigration</a>, but returns a list of the SQL commands
--   executed instead of printing them to stderr.
--   
--   This function silences the migration by remapping <a>stderr</a>. As a
--   result, it is not thread-safe and can clobber output from other parts
--   of the program. This implementation method was chosen to also silence
--   postgresql migration output on stderr, but is not recommended!
runMigrationSilent :: forall (m :: Type -> Type). MonadUnliftIO m => Migration -> ReaderT SqlBackend m [Text]

-- | Like <a>runMigration</a>, but this will perform the unsafe database
--   migrations instead of erroring out.
runMigrationUnsafe :: forall (m :: Type -> Type). MonadIO m => Migration -> ReaderT SqlBackend m ()

-- | Same as <a>runMigrationUnsafe</a>, but returns a list of the SQL
--   commands executed instead of printing them to stderr.
runMigrationUnsafeQuiet :: forall (m :: Type -> Type). (HasCallStack, MonadIO m) => Migration -> ReaderT SqlBackend m [Text]

-- | Report multiple errors in a <a>Migration</a>.
reportErrors :: [Text] -> Migration

-- | Add a migration to the migration plan.
addMigration :: Bool -> Sql -> Migration

-- | Add a <a>CautiousMigration</a> (aka a <tt>[(<a>Bool</a>,
--   <a>Text</a>)]</tt>) to the migration plan.
addMigrations :: CautiousMigration -> Migration

-- | Run an action against the database during a migration. Can be useful
--   for eg creating Postgres extensions:
--   
--   <pre>
--   runSqlCommand $ <a>rawExecute</a> "CREATE EXTENSION IF NOT EXISTS "uuid-ossp";" []
--   </pre>
runSqlCommand :: SqlPersistT IO () -> Migration

-- | Commit the current transaction and begin a new one. This is used when
--   a transaction commit is required within the context of
--   <a>runSqlConn</a> (which brackets its provided action with a
--   transaction begin/commit pair).
transactionSave :: forall (m :: Type -> Type). MonadIO m => ReaderT SqlBackend m ()

-- | Commit the current transaction and begin a new one with the specified
--   isolation level.
transactionSaveWithIsolation :: forall (m :: Type -> Type). MonadIO m => IsolationLevel -> ReaderT SqlBackend m ()

-- | Roll back the current transaction and begin a new one. This rolls back
--   to the state of the last call to <a>transactionSave</a> or the
--   enclosing <a>runSqlConn</a> call.
transactionUndo :: forall (m :: Type -> Type). MonadIO m => ReaderT SqlBackend m ()

-- | Roll back the current transaction and begin a new one with the
--   specified isolation level.
transactionUndoWithIsolation :: forall (m :: Type -> Type). MonadIO m => IsolationLevel -> ReaderT SqlBackend m ()


-- | The <tt>esqueleto</tt> EDSL (embedded domain specific language). This
--   module replaces <tt>Database.Persist</tt>, so instead of importing
--   that module you should just import this one:
--   
--   <pre>
--   -- For a module using just esqueleto.
--   import Database.Esqueleto
--   </pre>
--   
--   If you need to use <tt>persistent</tt>'s default support for queries
--   as well, either import it qualified:
--   
--   <pre>
--   -- For a module that mostly uses esqueleto.
--   import Database.Esqueleto
--   import qualified Database.Persist as P
--   </pre>
--   
--   or import <tt>esqueleto</tt> itself qualified:
--   
--   <pre>
--   -- For a module that uses esqueleto just on some queries.
--   import Database.Persist
--   import qualified Database.Esqueleto as E
--   </pre>
--   
--   Other than identifier name clashes, <tt>esqueleto</tt> does not
--   conflict with <tt>persistent</tt> in any way.
--   
--   Note that the facilities for <tt>JOIN</tt> have been significantly
--   improved in the <a>Database.Esqueleto.Experimental</a> module. The
--   definition of <a>from</a> and <a>on</a> in this module will be
--   replaced with those at the 4.0.0.0 version, so you are encouraged to
--   migrate to the new method.
--   
--   This module has an attached WARNING message indicating that the
--   Experimental syntax will become the default. If you want to continue
--   using the old syntax, please refer to <a>Database.Esqueleto.Legacy</a>
--   as a drop-in replacement.

-- | <i>Warning: This module will switch over to the Experimental syntax in
--   an upcoming major version release. Please migrate to the
--   Database.Esqueleto.Legacy module to continue using the old syntax, or
--   translate to the new and improved syntax in
--   Database.Esqueleto.Experimental.</i>
module Database.Esqueleto

-- | <tt>WHERE</tt> clause: restrict the query's result.
where_ :: SqlExpr (Value Bool) -> SqlQuery ()

-- | An <tt>ON</tt> clause, useful to describe how two tables are related.
--   Cross joins and tuple-joins do not need an <a>on</a> clause, but
--   <a>InnerJoin</a> and the various outer joins do.
--   
--   <a>Database.Esqueleto.Experimental</a> in version 4.0.0.0 of the
--   library. The <tt>Experimental</tt> module has a dramatically improved
--   means for introducing tables and entities that provides more power and
--   less potential for runtime errors.
--   
--   If you don't include an <a>on</a> clause (or include too many!) then a
--   runtime exception will be thrown.
--   
--   As an example, consider this simple join:
--   
--   <pre>
--   <a>select</a> $
--   <a>from</a> $ \(foo `<a>InnerJoin</a>` bar) -&gt; do
--     <a>on</a> (foo <a>^.</a> FooId <a>==.</a> bar <a>^.</a> BarFooId)
--     ...
--   </pre>
--   
--   We need to specify the clause for joining the two columns together. If
--   we had this:
--   
--   <pre>
--   <a>select</a> $
--   <a>from</a> $ \(foo `<tt>CrossJoin</tt>` bar) -&gt; do
--     ...
--   </pre>
--   
--   Then we can safely omit the <a>on</a> clause, because the cross join
--   will make pairs of all records possible.
--   
--   You can do multiple <a>on</a> clauses in a query. This query joins
--   three tables, and has two <a>on</a> clauses:
--   
--   <pre>
--   <a>select</a> $
--   <a>from</a> $ \(foo `<a>InnerJoin</a>` bar `<a>InnerJoin</a>` baz) -&gt; do
--     <a>on</a> (baz <a>^.</a> BazId <a>==.</a> bar <a>^.</a> BarBazId)
--     <a>on</a> (foo <a>^.</a> FooId <a>==.</a> bar <a>^.</a> BarFooId)
--     ...
--   </pre>
--   
--   Old versions of esqueleto required that you provide the <a>on</a>
--   clauses in reverse order. This restriction has been lifted - you can
--   now provide <a>on</a> clauses in any order, and the SQL should work
--   itself out. The above query is now totally equivalent to this:
--   
--   <pre>
--   <a>select</a> $
--   <a>from</a> $ \(foo `<a>InnerJoin</a>` bar `<a>InnerJoin</a>` baz) -&gt; do
--     <a>on</a> (foo <a>^.</a> FooId <a>==.</a> bar <a>^.</a> BarFooId)
--     <a>on</a> (baz <a>^.</a> BazId <a>==.</a> bar <a>^.</a> BarBazId)
--     ...
--   </pre>
on :: SqlExpr (Value Bool) -> SqlQuery ()

-- | <tt>GROUP BY</tt> clause. You can enclose multiple columns in a tuple.
--   
--   <pre>
--   select $ <a>from</a> \(foo `<tt>InnerJoin</tt>` bar) -&gt; do
--     <a>on</a> (foo <a>^.</a> FooBarId <a>==.</a> bar <a>^.</a> BarId)
--     <a>groupBy</a> (bar <a>^.</a> BarId, bar <a>^.</a> BarName)
--     return (bar <a>^.</a> BarId, bar <a>^.</a> BarName, countRows)
--   </pre>
--   
--   With groupBy you can sort by aggregate functions, like so (we used
--   <tt>let</tt> to restrict the more general <a>countRows</a> to
--   <tt>SqlSqlExpr (Value Int)</tt> to avoid ambiguity---the second use of
--   <a>countRows</a> has its type restricted by the <tt>:: Int</tt>
--   below):
--   
--   <pre>
--   r &lt;- select $ <a>from</a> \(foo `<tt>InnerJoin</tt>` bar) -&gt; do
--     <a>on</a> (foo <a>^.</a> FooBarId <a>==.</a> bar <a>^.</a> BarId)
--     <a>groupBy</a> $ bar <a>^.</a> BarName
--     let countRows' = <a>countRows</a>
--     <a>orderBy</a> [<a>asc</a> countRows']
--     return (bar <a>^.</a> BarName, countRows')
--   forM_ r $ \(<a>Value</a> name, <a>Value</a> count) -&gt; do
--     print name
--     print (count :: Int)
--   </pre>
--   
--   <h3>Need more columns?</h3>
--   
--   The <a>ToSomeValues</a> class is defined for <a>SqlExpr</a> and tuples
--   of <a>SqlExpr</a>s. We only have definitions for up to 8 elements in a
--   tuple right now, so it's possible that you may need to have more than
--   8 elements.
--   
--   For example, consider a query with a <a>groupBy</a> call like this:
--   
--   <pre>
--   groupBy (e0, e1, e2, e3, e4, e5, e6, e7)
--   </pre>
--   
--   This is the biggest you can get with a single tuple. However, you can
--   easily nest the tuples to add more:
--   
--   <pre>
--   groupBy ((e0, e1, e2, e3, e4, e5, e6, e7), e8, e9)
--   </pre>
groupBy :: ToSomeValues a => a -> SqlQuery ()

-- | <tt>ORDER BY</tt> clause. See also <a>asc</a> and <a>desc</a>.
--   
--   Multiple calls to <a>orderBy</a> get concatenated on the final query,
--   including <a>distinctOnOrderBy</a>.
orderBy :: [SqlExpr OrderBy] -> SqlQuery ()

-- | Ascending order of this field or SqlExpression.
asc :: PersistField a => SqlExpr (Value a) -> SqlExpr OrderBy

-- | Descending order of this field or SqlExpression.
desc :: PersistField a => SqlExpr (Value a) -> SqlExpr OrderBy

-- | <tt>LIMIT</tt>. Limit the number of returned rows.
limit :: Int64 -> SqlQuery ()

-- | <tt>OFFSET</tt>. Usually used with <a>limit</a>.
offset :: Int64 -> SqlQuery ()

-- | <tt>DISTINCT</tt>. Change the current <tt>SELECT</tt> into <tt>SELECT
--   DISTINCT</tt>. For example:
--   
--   <pre>
--   select $ distinct $
--     <a>from</a> \foo -&gt; do
--     ...
--   </pre>
--   
--   Note that this also has the same effect:
--   
--   <pre>
--   select $
--     <a>from</a> \foo -&gt; do
--     distinct (return ())
--     ...
--   </pre>
distinct :: SqlQuery a -> SqlQuery a

-- | <tt>DISTINCT ON</tt>. Change the current <tt>SELECT</tt> into
--   <tt>SELECT DISTINCT ON (SqlExpressions)</tt>. For example:
--   
--   <pre>
--   select $
--     <a>from</a> \foo -&gt;
--     <a>distinctOn</a> [<a>don</a> (foo ^. FooName), <a>don</a> (foo ^. FooState)] $ do
--     ...
--   </pre>
--   
--   You can also chain different calls to <a>distinctOn</a>. The above is
--   equivalent to:
--   
--   <pre>
--   select $
--     <a>from</a> \foo -&gt;
--     <a>distinctOn</a> [<a>don</a> (foo ^. FooName)] $
--     <a>distinctOn</a> [<a>don</a> (foo ^. FooState)] $ do
--     ...
--   </pre>
--   
--   Each call to <a>distinctOn</a> adds more SqlExpressions. Calls to
--   <a>distinctOn</a> override any calls to <a>distinct</a>.
--   
--   Note that PostgreSQL requires the SqlExpressions on <tt>DISTINCT
--   ON</tt> to be the first ones to appear on a <tt>ORDER BY</tt>. This is
--   not managed automatically by esqueleto, keeping its spirit of trying
--   to be close to raw SQL.
--   
--   Supported by PostgreSQL only.

-- | <i>Deprecated: This function is deprecated, as it is only supported in
--   Postgresql. Please use the variant in <a>PostgreSQL</a> instead.</i>
distinctOn :: [SqlExpr DistinctOn] -> SqlQuery a -> SqlQuery a

-- | Erase an SqlExpression's type so that it's suitable to be used by
--   <a>distinctOn</a>.
don :: SqlExpr (Value a) -> SqlExpr DistinctOn

-- | A convenience function that calls both <a>distinctOn</a> and
--   <a>orderBy</a>. In other words,
--   
--   <pre>
--   <a>distinctOnOrderBy</a> [asc foo, desc bar, desc quux] $ do
--     ...
--   </pre>
--   
--   is the same as:
--   
--   <pre>
--   <a>distinctOn</a> [don foo, don  bar, don  quux] $ do
--     <a>orderBy</a>  [asc foo, desc bar, desc quux]
--     ...
--   </pre>

-- | <i>Deprecated: This function is deprecated, as it is only supported in
--   Postgresql. Please use the function defined in <a>PostgreSQL</a>
--   instead.</i>
distinctOnOrderBy :: [SqlExpr OrderBy] -> SqlQuery a -> SqlQuery a

-- | <tt>HAVING</tt>.
having :: SqlExpr (Value Bool) -> SqlQuery ()

-- | Add a locking clause to the query. Please read <a>LockingKind</a>
--   documentation and your RDBMS manual. Unsafe since not all locking
--   clauses are implemented for every RDBMS
--   
--   If multiple calls to <a>locking</a> are made on the same query, the
--   last one is used.
locking :: LockingKind -> SqlQuery ()

-- | Project a field of an entity.
(^.) :: forall typ val. (PersistEntity val, PersistField typ) => SqlExpr (Entity val) -> EntityField val typ -> SqlExpr (Value typ)
infixl 9 ^.

-- | Project an <a>EntityField</a> of a nullable entity. The result type
--   will be <a>Nullable</a>, meaning that nested <a>Maybe</a> won't be
--   produced here.
--   
--   As of v3.6.0.0, this will attempt to combine nested <a>Maybe</a>. If
--   you want to keep nested <a>Maybe</a>, then see <a>??.</a>.
(?.) :: (PersistEntity val, PersistField typ) => SqlExpr (Maybe (Entity val)) -> EntityField val typ -> SqlExpr (Value (Maybe (Nullable typ)))
infixl 9 ?.

-- | Lift a constant value from Haskell-land to the query.
val :: PersistField typ => typ -> SqlExpr (Value typ)

-- | <tt>IS NULL</tt> comparison.
--   
--   For <tt>IS NOT NULL</tt>, you can negate this with <a>not_</a>, as in
--   <tt>not_ (isNothing (person ^. PersonAge))</tt>
--   
--   Warning: Persistent and Esqueleto have different behavior for <tt>!=
--   Nothing</tt>:
--   
--   TODO: table
--   
--   In SQL, <tt>= NULL</tt> and <tt>!= NULL</tt> return NULL instead of
--   true or false. For this reason, you very likely do not want to use
--   <tt><a>!=.</a> Nothing</tt> in Esqueleto. You may find these
--   <tt>hlint</tt> rules helpful to enforce this:
--   
--   <pre>
--   - error: {lhs: v Database.Esqueleto.==. Database.Esqueleto.nothing, rhs: Database.Esqueleto.isNothing v, name: Use Esqueleto's isNothing}
--   - error: {lhs: v Database.Esqueleto.==. Database.Esqueleto.val Nothing, rhs: Database.Esqueleto.isNothing v, name: Use Esqueleto's isNothing}
--   - error: {lhs: v Database.Esqueleto.!=. Database.Esqueleto.nothing, rhs: not_ (Database.Esqueleto.isNothing v), name: Use Esqueleto's not isNothing}
--   - error: {lhs: v Database.Esqueleto.!=. Database.Esqueleto.val Nothing, rhs: not_ (Database.Esqueleto.isNothing v), name: Use Esqueleto's not isNothing}
--   </pre>
isNothing :: PersistField typ => SqlExpr (Value (Maybe typ)) -> SqlExpr (Value Bool)

-- | Analogous to <a>Just</a>, promotes a value of type <tt>typ</tt> into
--   one of type <tt>Maybe typ</tt>. It should hold that <tt><a>val</a> .
--   Just === just . <a>val</a></tt>.
--   
--   This function will try not to produce a nested <a>Maybe</a>. This is
--   in accord with how SQL represents <tt>NULL</tt>. That means that
--   <tt><a>just</a> . <a>just</a> = <a>just</a></tt>. This behavior was
--   changed in v3.6.0.0. If you want to produce nested <a>Maybe</a>, see
--   <a>just'</a>.
just :: NullableFieldProjection typ typ' => SqlExpr (Value typ) -> SqlExpr (Value (Maybe typ'))

-- | Like <a>just</a>, but this function does not try to collapse nested
--   <a>Maybe</a>. This may be useful if you have type inference problems
--   with <a>just</a>.
just' :: SqlExpr (Value typ) -> SqlExpr (Value (Maybe typ))

-- | <tt>NULL</tt> value.
nothing :: SqlExpr (Value (Maybe typ))

-- | Join nested <a>Maybe</a>s in a <a>Value</a> into one. This is useful
--   when calling aggregate functions on nullable fields.
--   
--   As of v3.6.0.0, this function will attempt to work on both
--   <tt><a>SqlExpr</a> (<a>Value</a> (<a>Maybe</a> a))</tt> as well as
--   <tt><a>SqlExpr</a> (<a>Value</a> (<a>Maybe</a> (<a>Maybe</a> a)))</tt>
--   inputs to make transitioning to <a>NullableFieldProjection</a> easier.
--   This may make type inference worse in some cases. If you want the
--   monomorphic variant, see <a>joinV'</a>
joinV :: NullableFieldProjection typ typ' => SqlExpr (Value (Maybe typ)) -> SqlExpr (Value (Maybe typ'))

-- | Like <a>joinV</a>, but monomorphic: the input type only works on
--   <tt><a>SqlExpr</a> (<a>Value</a> (Maybe (Maybe a)))</tt>.
--   
--   This function may be useful if you have type inference issues with
--   <a>joinV</a>.
joinV' :: SqlExpr (Value (Maybe (Maybe typ))) -> SqlExpr (Value (Maybe typ))

-- | Project an SqlExpression that may be null, guarding against null
--   cases.
withNonNull :: PersistField typ => SqlExpr (Value (Maybe typ)) -> (SqlExpr (Value typ) -> SqlQuery a) -> SqlQuery a

-- | <tt>COUNT(*)</tt> value.
countRows :: Num a => SqlExpr (Value a)

-- | <tt>COUNT</tt>.
count :: Num a => SqlExpr (Value typ) -> SqlExpr (Value a)

-- | <tt>COUNT(DISTINCT x)</tt>.
countDistinct :: Num a => SqlExpr (Value typ) -> SqlExpr (Value a)
not_ :: SqlExpr (Value Bool) -> SqlExpr (Value Bool)

-- | This operator produces the SQL operator <tt>=</tt>, which is used to
--   compare values for equality.
--   
--   Example:
--   
--   <pre>
--   query :: UserId -&gt; SqlPersistT IO [Entity User]
--   query userId = select $ do
--       user &lt;- from $ table @User
--       where_ (user ^. UserId ==. val userId)
--       pure user
--   </pre>
--   
--   This would generate the following SQL:
--   
--   <pre>
--   SELECT user.*
--   FROM user
--   WHERE user.id = ?
--   </pre>
(==.) :: PersistField typ => SqlExpr (Value typ) -> SqlExpr (Value typ) -> SqlExpr (Value Bool)
infix 4 ==.

-- | This operator translates to the SQL operator <tt>&gt;=</tt>.
--   
--   Example:
--   
--   <pre>
--   where_ $ user ^. UserAge &gt;=. val 21
--   </pre>
(>=.) :: PersistField typ => SqlExpr (Value typ) -> SqlExpr (Value typ) -> SqlExpr (Value Bool)
infix 4 >=.

-- | This operator translates to the SQL operator <tt>&gt;</tt>.
--   
--   Example:
--   
--   <pre>
--   where_ $ user ^. UserAge &gt;. val 20
--   </pre>
(>.) :: PersistField typ => SqlExpr (Value typ) -> SqlExpr (Value typ) -> SqlExpr (Value Bool)
infix 4 >.

-- | This operator translates to the SQL operator <tt>&lt;=</tt>.
--   
--   Example:
--   
--   <pre>
--   where_ $ val 21 &lt;=. user ^. UserAge
--   </pre>
(<=.) :: PersistField typ => SqlExpr (Value typ) -> SqlExpr (Value typ) -> SqlExpr (Value Bool)
infix 4 <=.

-- | This operator translates to the SQL operator <tt>&lt;</tt>.
--   
--   Example:
--   
--   <pre>
--   where_ $ val 20 &lt;. user ^. UserAge
--   </pre>
(<.) :: PersistField typ => SqlExpr (Value typ) -> SqlExpr (Value typ) -> SqlExpr (Value Bool)
infix 4 <.

-- | This operator translates to the SQL operator <tt>!=</tt>.
--   
--   Example:
--   
--   <pre>
--   where_ $ user ^. UserName !=. val <a>Bob</a>
--   </pre>
(!=.) :: PersistField typ => SqlExpr (Value typ) -> SqlExpr (Value typ) -> SqlExpr (Value Bool)
infix 4 !=.

-- | This operator translates to the SQL operator <tt>AND</tt>.
--   
--   Example:
--   
--   <pre>
--   where_ $
--           user ^. UserName ==. val <a>Matt</a>
--       &amp;&amp;. user ^. UserAge &gt;=. val 21
--   </pre>
(&&.) :: SqlExpr (Value Bool) -> SqlExpr (Value Bool) -> SqlExpr (Value Bool)
infixr 3 &&.

-- | This operator translates to the SQL operator <tt>AND</tt>.
--   
--   Example:
--   
--   <pre>
--   where_ $
--           user ^. UserName ==. val <a>Matt</a>
--       ||. user ^. UserName ==. val <a>John</a>
--   </pre>
(||.) :: SqlExpr (Value Bool) -> SqlExpr (Value Bool) -> SqlExpr (Value Bool)
infixr 2 ||.

-- | <tt>a <a>between</a> (b, c)</tt> translates to the SQL expression
--   <tt>a &gt;= b AND a &lt;= c</tt>. It does not use a SQL
--   <tt>BETWEEN</tt> operator.
--   
--   @since: 3.1.0
between :: PersistField a => SqlExpr (Value a) -> (SqlExpr (Value a), SqlExpr (Value a)) -> SqlExpr (Value Bool)

-- | This operator translates to the SQL operator <tt>+</tt>.
--   
--   This does not require or assume anything about the SQL values.
--   Interpreting what <tt>+.</tt> means for a given type is left to the
--   database engine.
--   
--   Example:
--   
--   <pre>
--   user ^. UserAge +. val 10
--   </pre>
(+.) :: PersistField a => SqlExpr (Value a) -> SqlExpr (Value a) -> SqlExpr (Value a)
infixl 6 +.

-- | This operator translates to the SQL operator <tt>-</tt>.
--   
--   This does not require or assume anything about the SQL values.
--   Interpreting what <tt>-.</tt> means for a given type is left to the
--   database engine.
--   
--   Example:
--   
--   <pre>
--   user ^. UserAge -. val 10
--   </pre>
(-.) :: PersistField a => SqlExpr (Value a) -> SqlExpr (Value a) -> SqlExpr (Value a)
infixl 6 -.

-- | This operator translates to the SQL operator <tt>/</tt>.
--   
--   This does not require or assume anything about the SQL values.
--   Interpreting what <tt>/.</tt> means for a given type is left to the
--   database engine.
--   
--   Example:
--   
--   <pre>
--   user ^. UserAge /. val 10
--   </pre>
(/.) :: PersistField a => SqlExpr (Value a) -> SqlExpr (Value a) -> SqlExpr (Value a)
infixl 7 /.

-- | This operator translates to the SQL operator <tt>*</tt>.
--   
--   This does not require or assume anything about the SQL values.
--   Interpreting what <tt>*.</tt> means for a given type is left to the
--   database engine.
--   
--   Example:
--   
--   <pre>
--   user ^. UserAge *. val 10
--   </pre>
(*.) :: PersistField a => SqlExpr (Value a) -> SqlExpr (Value a) -> SqlExpr (Value a)
infixl 7 *.
round_ :: (PersistField a, Num a, PersistField b, Num b) => SqlExpr (Value a) -> SqlExpr (Value b)
ceiling_ :: (PersistField a, Num a, PersistField b, Num b) => SqlExpr (Value a) -> SqlExpr (Value b)
floor_ :: (PersistField a, Num a, PersistField b, Num b) => SqlExpr (Value a) -> SqlExpr (Value b)
min_ :: PersistField a => SqlExpr (Value a) -> SqlExpr (Value (Maybe (Nullable a)))
max_ :: PersistField a => SqlExpr (Value a) -> SqlExpr (Value (Maybe (Nullable a)))
sum_ :: (PersistField a, PersistField b) => SqlExpr (Value a) -> SqlExpr (Value (Maybe b))
avg_ :: (PersistField a, PersistField b) => SqlExpr (Value a) -> SqlExpr (Value (Maybe b))

-- | Allow a number of one type to be used as one of another type via an
--   implicit cast. An explicit cast is not made, this function changes
--   only the types on the Haskell side.
--   
--   <i>Caveat</i>: Trying to use <tt>castNum</tt> from <tt>Double</tt> to
--   <tt>Int</tt> will not result in an integer, the original fractional
--   number will still be used! Use <a>round_</a>, <a>ceiling_</a> or
--   <a>floor_</a> instead.
--   
--   <i>Safety</i>: This operation is mostly safe due to the <a>Num</a>
--   constraint between the types and the fact that RDBMSs usually allow
--   numbers of different types to be used interchangeably. However, there
--   may still be issues with the query not being accepted by the RDBMS or
--   <tt>persistent</tt> not being able to parse it.
castNum :: (Num a, Num b) => SqlExpr (Value a) -> SqlExpr (Value b)

-- | Same as <a>castNum</a>, but for nullable values.
castNumM :: (Num a, Num b) => SqlExpr (Value (Maybe a)) -> SqlExpr (Value (Maybe b))

-- | <tt>COALESCE</tt> function. Evaluates the arguments in order and
--   returns the value of the first non-NULL SqlExpression, or NULL
--   (Nothing) otherwise. Some RDBMSs (such as SQLite) require at least two
--   arguments; please refer to the appropriate documentation.
coalesce :: (PersistField a, NullableFieldProjection a a') => [SqlExpr (Value (Maybe a))] -> SqlExpr (Value (Maybe a'))

-- | Like <tt>coalesce</tt>, but takes a non-nullable SqlExpression placed
--   at the end of the SqlExpression list, which guarantees a non-NULL
--   result.
coalesceDefault :: PersistField a => [SqlExpr (Value (Maybe a))] -> SqlExpr (Value a) -> SqlExpr (Value a)

-- | <tt>LOWER</tt> function.
lower_ :: SqlString s => SqlExpr (Value s) -> SqlExpr (Value s)

-- | <tt>UPPER</tt> function. @since 3.3.0
upper_ :: SqlString s => SqlExpr (Value s) -> SqlExpr (Value s)

-- | <tt>TRIM</tt> function. @since 3.3.0
trim_ :: SqlString s => SqlExpr (Value s) -> SqlExpr (Value s)

-- | <tt>LTRIM</tt> function. @since 3.3.0
ltrim_ :: SqlString s => SqlExpr (Value s) -> SqlExpr (Value s)

-- | <tt>RTRIM</tt> function. @since 3.3.0
rtrim_ :: SqlString s => SqlExpr (Value s) -> SqlExpr (Value s)

-- | <tt>LENGTH</tt> function. @since 3.3.0
length_ :: (SqlString s, Num a) => SqlExpr (Value s) -> SqlExpr (Value a)

-- | <tt>LEFT</tt> function. @since 3.3.0
left_ :: (SqlString s, Num a) => (SqlExpr (Value s), SqlExpr (Value a)) -> SqlExpr (Value s)

-- | <tt>RIGHT</tt> function. @since 3.3.0
right_ :: (SqlString s, Num a) => (SqlExpr (Value s), SqlExpr (Value a)) -> SqlExpr (Value s)

-- | <tt>LIKE</tt> operator.
like :: SqlString s => SqlExpr (Value s) -> SqlExpr (Value s) -> SqlExpr (Value Bool)
infixr 2 `like`

-- | <tt>ILIKE</tt> operator (case-insensitive <tt>LIKE</tt>).
--   
--   Supported by PostgreSQL only. Deprecated in version 3.6.0 in favor of
--   the version available from <a>Database.Esqueleto.PostgreSQL</a>.

-- | <i>Deprecated: Since 3.6.0: <a>ilike</a> is only supported on
--   Postgres. Please import it from 'Database.Esqueleto.PostgreSQL.</i>
ilike :: SqlString s => SqlExpr (Value s) -> SqlExpr (Value s) -> SqlExpr (Value Bool)
infixr 2 `ilike`

-- | The string <tt><a>%</a></tt>. May be useful while using <a>like</a>
--   and concatenation (<a>concat_</a> or <a>++.</a>, depending on your
--   database). Note that you always have to type the parenthesis, for
--   example:
--   
--   <pre>
--   name `<a>like</a>` (%) ++. <a>val</a> "John" ++. (%)
--   </pre>
(%) :: SqlString s => SqlExpr (Value s)

-- | The <tt>CONCAT</tt> function with a variable number of parameters.
--   Supported by MySQL and PostgreSQL. SQLite supports this in versions
--   after 3.44.0, and <tt>persistent-sqlite</tt> supports this in versions
--   <tt>2.13.3.0</tt> and after.
concat_ :: SqlString s => [SqlExpr (Value s)] -> SqlExpr (Value s)

-- | The <tt>||</tt> string concatenation operator (named after Haskell's
--   <a>++</a> in order to avoid naming clash with <a>||.</a>).
--   
--   Supported by SQLite and PostgreSQL.
--   
--   MySQL support requires setting the SQL mode to
--   <tt>PIPES_AS_CONCAT</tt> or <tt>ANSI</tt> - see <a>this StackOverflow
--   answer</a>.
(++.) :: SqlString s => SqlExpr (Value s) -> SqlExpr (Value s) -> SqlExpr (Value s)
infixr 5 ++.

-- | Cast a string type into <a>Text</a>. This function is very useful if
--   you want to use <tt>newtype</tt>s, or if you want to apply functions
--   such as <a>like</a> to strings of different types.
--   
--   <i>Safety:</i> This is a slightly unsafe function, especially if you
--   have defined your own instances of <a>SqlString</a>. Also, since
--   <a>Maybe</a> is an instance of <a>SqlString</a>, it's possible to turn
--   a nullable value into a non-nullable one. Avoid using this function if
--   possible.
castString :: (SqlString s, SqlString r) => SqlExpr (Value s) -> SqlExpr (Value r)

-- | Execute a subquery <tt>SELECT</tt> in an SqlExpression. Returns a list
--   of values.
subList_select :: PersistField a => SqlQuery (SqlExpr (Value a)) -> SqlExpr (ValueList a)

-- | Lift a list of constant value from Haskell-land to the query.
valList :: PersistField typ => [typ] -> SqlExpr (ValueList typ)

-- | Same as <a>just</a> but for <a>ValueList</a>. Most of the time you
--   won't need it, though, because you can use <a>just</a> from inside
--   <a>subList_select</a> or <a>Just</a> from inside <a>valList</a>.
justList :: SqlExpr (ValueList typ) -> SqlExpr (ValueList (Maybe typ))

-- | <tt>IN</tt> operator. For example if you want to select all
--   <tt>Person</tt>s by a list of IDs:
--   
--   <pre>
--   SELECT *
--   FROM Person
--   WHERE Person.id IN (?)
--   </pre>
--   
--   In <tt>esqueleto</tt>, we may write the same query above as:
--   
--   <pre>
--   select $
--   <a>from</a> $ \person -&gt; do
--   <a>where_</a> $ person <a>^.</a> PersonId `<tt>in_</tt>` <a>valList</a> personIds
--   return person
--   </pre>
--   
--   Where <tt>personIds</tt> is of type <tt>[Key Person]</tt>.
in_ :: PersistField typ => SqlExpr (Value typ) -> SqlExpr (ValueList typ) -> SqlExpr (Value Bool)

-- | <tt>NOT IN</tt> operator.
notIn :: PersistField typ => SqlExpr (Value typ) -> SqlExpr (ValueList typ) -> SqlExpr (Value Bool)

-- | <tt>EXISTS</tt> operator. For example:
--   
--   <pre>
--   select $
--   <a>from</a> $ \person -&gt; do
--   <a>where_</a> $ <a>exists</a> $
--            <a>from</a> $ \post -&gt; do
--            <a>where_</a> (post <a>^.</a> BlogPostAuthorId <a>==.</a> person <a>^.</a> PersonId)
--   return person
--   </pre>
exists :: SqlQuery () -> SqlExpr (Value Bool)

-- | <tt>NOT EXISTS</tt> operator.
notExists :: SqlQuery () -> SqlExpr (Value Bool)

-- | <tt>SET</tt> clause used on <tt>UPDATE</tt>s. Note that while it's not
--   a type error to use this function on a <tt>SELECT</tt>, it will most
--   certainly result in a runtime error.
set :: PersistEntity val => SqlExpr (Entity val) -> [SqlExpr (Entity val) -> SqlExpr Update] -> SqlQuery ()
(=.) :: (PersistEntity val, PersistField typ) => EntityField val typ -> SqlExpr (Value typ) -> SqlExpr (Entity val) -> SqlExpr Update
infixr 3 =.
(+=.) :: (PersistEntity val, PersistField a) => EntityField val a -> SqlExpr (Value a) -> SqlExpr (Entity val) -> SqlExpr Update
infixr 3 +=.
(-=.) :: (PersistEntity val, PersistField a) => EntityField val a -> SqlExpr (Value a) -> SqlExpr (Entity val) -> SqlExpr Update
infixr 3 -=.
(*=.) :: (PersistEntity val, PersistField a) => EntityField val a -> SqlExpr (Value a) -> SqlExpr (Entity val) -> SqlExpr Update
infixr 3 *=.
(/=.) :: (PersistEntity val, PersistField a) => EntityField val a -> SqlExpr (Value a) -> SqlExpr (Entity val) -> SqlExpr Update
infixr 3 /=.

-- | <tt>CASE</tt> statement. For example:
--   
--   <pre>
--   select $
--   return $
--   <a>case_</a>
--      [ <a>when_</a>
--          (<a>exists</a> $
--          <a>from</a> $ \p -&gt; do
--          <a>where_</a> (p <a>^.</a> PersonName <a>==.</a> <a>val</a> "Mike"))
--        <a>then_</a>
--          (<a>subSelect</a> $
--          <a>from</a> $ \v -&gt; do
--          let sub =
--                  <a>from</a> $ \c -&gt; do
--                  <a>where_</a> (c <a>^.</a> PersonName <a>==.</a> <a>val</a> "Mike")
--                  return (c <a>^.</a> PersonFavNum)
--          <a>where_</a> (<a>just</a> (v <a>^.</a> PersonFavNum) &gt;. <a>subSelect</a> sub)
--          return $ <a>count</a> (v <a>^.</a> PersonName) +. <a>val</a> (1 :: Int)) ]
--      (<a>else_</a> $ <a>val</a> (-1))
--   </pre>
--   
--   This query is a bit complicated, but basically it checks if a person
--   named <tt>"Mike"</tt> exists, and if that person does, run the
--   subquery to find out how many people have a ranking (by Fav Num)
--   higher than <tt>"Mike"</tt>.
--   
--   <b>NOTE:</b> There are a few things to be aware about this statement.
--   
--   <ul>
--   <li>This only implements the full CASE statement, it does not
--   implement the "simple" CASE statement.</li>
--   <li>At least one <a>when_</a> and <a>then_</a> is mandatory otherwise
--   it will emit an error.</li>
--   <li>The <a>else_</a> is also mandatory, unlike the SQL statement in
--   which if the <tt>ELSE</tt> is omitted it will return a <tt>NULL</tt>.
--   You can reproduce this via <a>nothing</a>.</li>
--   </ul>
case_ :: PersistField a => [(SqlExpr (Value Bool), SqlExpr (Value a))] -> SqlExpr (Value a) -> SqlExpr (Value a)

-- | Convert an entity's key into another entity's.
--   
--   This function is to be used when you change an entity's <tt>Id</tt> to
--   be that of another entity. For example:
--   
--   <pre>
--   Bar
--     barNum Int
--   Foo
--     bar BarId
--     fooNum Int
--     Primary bar
--   </pre>
--   
--   In this example, Bar is said to be the BaseEnt(ity), and Foo the
--   child. To model this in Esqueleto, declare:
--   
--   <pre>
--   instance ToBaseId Foo where
--     type BaseEnt Foo = Bar
--     toBaseIdWitness barId = FooKey barId
--   </pre>
--   
--   Now you're able to write queries such as:
--   
--   <pre>
--   <a>select</a> $
--   <a>from</a> $ (bar `<tt>InnerJoin</tt>` foo) -&gt; do
--   <a>on</a> (<a>toBaseId</a> (foo <a>^.</a> FooId) <a>==.</a> bar <a>^.</a> BarId)
--   return (bar, foo)
--   </pre>
--   
--   Note: this function may be unsafe to use in conditions not like the
--   one of the example above.
toBaseId :: ToBaseId ent => SqlExpr (Value (Key ent)) -> SqlExpr (Value (Key (BaseEnt ent)))

-- | The inverse of <a>toBaseId</a>. Note that this is somewhat less "safe"
--   than <a>toBaseId</a>. Calling <a>toBaseId</a> will usually mean that a
--   foreign key constraint is present that guarantees the presence of the
--   base ID. <a>fromBaseId</a> has no such guarantee. Consider the code
--   example given in <a>toBaseId</a>:
--   
--   <pre>
--   Bar
--     barNum Int
--   Foo
--     bar BarId
--     fooNum Int
--     Primary bar
--   </pre>
--   
--   <pre>
--   instance ToBaseId Foo where
--     type BaseEnt Foo = Bar
--     toBaseIdWitness barId = FooKey barId
--   </pre>
--   
--   The type of <a>toBaseId</a> for <tt>Foo</tt> would be:
--   
--   <pre>
--   toBaseId :: SqlExpr (Value FooId) -&gt; SqlExpr (Value BarId)
--   </pre>
--   
--   The foreign key constraint on <tt>Foo</tt> means that every
--   <tt>FooId</tt> points to a <tt>BarId</tt> in the database. However,
--   <a>fromBaseId</a> will not have this:
--   
--   <pre>
--   fromBaseId :: SqlExpr (Value BarId) -&gt; SqlExpr (Value FooId)
--   </pre>
fromBaseId :: ToBaseId ent => SqlExpr (Value (Key (BaseEnt ent))) -> SqlExpr (Value (Key ent))

-- | Like <a>toBaseId</a>, but works on <a>Maybe</a> keys.
toBaseIdMaybe :: ToBaseId ent => SqlExpr (Value (Maybe (Key ent))) -> SqlExpr (Value (Maybe (Key (BaseEnt ent))))

-- | As <a>fromBaseId</a>, but works on <a>Maybe</a> keys.
fromBaseIdMaybe :: ToBaseId ent => SqlExpr (Value (Maybe (Key (BaseEnt ent)))) -> SqlExpr (Value (Maybe (Key ent)))

-- | Execute a subquery <tt>SELECT</tt> in a <a>SqlExpr</a>. The query
--   passed to this function will only return a single result - it has a
--   <tt>LIMIT 1</tt> passed in to the query to make it safe, and the
--   return type is <a>Maybe</a> to indicate that the subquery might result
--   in 0 rows.
--   
--   If you find yourself writing <tt><a>joinV</a> . <a>subSelect</a></tt>,
--   then consider using <a>subSelectMaybe</a>.
--   
--   If you're performing a <a>countRows</a>, then you can use
--   <a>subSelectCount</a> which is safe.
--   
--   If you know that the subquery will always return exactly one row (eg a
--   foreign key constraint guarantees that you'll get exactly one row),
--   then consider <a>subSelectUnsafe</a>, along with a comment explaining
--   why it is safe.
subSelect :: (PersistField a, NullableFieldProjection a a') => SqlQuery (SqlExpr (Value a)) -> SqlExpr (Value (Maybe a'))

-- | Execute a subquery <tt>SELECT</tt> in a <a>SqlExpr</a>. This function
--   is a shorthand for the common <tt><a>joinV</a> . <a>subSelect</a></tt>
--   idiom, where you are calling <a>subSelect</a> on an expression that
--   would be <a>Maybe</a> already.
--   
--   As an example, you would use this function when calling <a>sum_</a> or
--   <a>max_</a>, which have <a>Maybe</a> in the result type (for a 0 row
--   query).
subSelectMaybe :: PersistField a => SqlQuery (SqlExpr (Value (Maybe a))) -> SqlExpr (Value (Maybe a))

-- | Performs a <tt>COUNT</tt> of the given query in a <tt>subSelect</tt>
--   manner. This is always guaranteed to return a result value, and is
--   completely safe.
subSelectCount :: (Num a, PersistField a) => SqlQuery ignored -> SqlExpr (Value a)

-- | Performs a sub-select using the given foreign key on the entity. This
--   is useful to extract values that are known to be present by the
--   database schema.
--   
--   As an example, consider the following persistent definition:
--   
--   <pre>
--   User
--     profile ProfileId
--   
--   Profile
--     name    Text
--   </pre>
--   
--   The following query will return the name of the user.
--   
--   <pre>
--   getUserWithName =
--       <a>select</a> $
--       <a>from</a> $ user -&gt;
--       <a>pure</a> (user, <a>subSelectForeign</a> user UserProfile (^. ProfileName)
--   </pre>
subSelectForeign :: (BackendCompatible SqlBackend (PersistEntityBackend val1), PersistEntity val1, PersistEntity val2, PersistField a) => SqlExpr (Entity val2) -> EntityField val2 (Key val1) -> (SqlExpr (Entity val1) -> SqlExpr (Value a)) -> SqlExpr (Value a)

-- | Execute a subquery <tt>SELECT</tt> in a <a>SqlExpr</a> that returns a
--   list. This is an alias for <a>subList_select</a> and is provided for
--   symmetry with the other safe subselect functions.
subSelectList :: PersistField a => SqlQuery (SqlExpr (Value a)) -> SqlExpr (ValueList a)

-- | Execute a subquery <tt>SELECT</tt> in a <a>SqlExpr</a>. This function
--   is unsafe, because it can throw runtime exceptions in two cases:
--   
--   <ol>
--   <li>If the query passed has 0 result rows, then it will return a
--   <tt>NULL</tt> value. The <tt>persistent</tt> parsing operations will
--   fail on an unexpected <tt>NULL</tt>.</li>
--   <li>If the query passed returns more than one row, then the SQL engine
--   will fail with an error like "More than one row returned by a subquery
--   used as an expression".</li>
--   </ol>
--   
--   This function is safe if you guarantee that exactly one row will be
--   returned, or if the result already has a <a>Maybe</a> type for some
--   reason.
--   
--   For variants with the safety encoded already, see <a>subSelect</a> and
--   <a>subSelectMaybe</a>. For the most common safe use of this, see
--   <a>subSelectCount</a>.
subSelectUnsafe :: PersistField a => SqlQuery (SqlExpr (Value a)) -> SqlExpr (Value a)

-- | Class that enables one to use <a>toBaseId</a> to convert an entity's
--   key on a query into another (cf. <a>toBaseId</a>).
class ToBaseId ent where {
    
    -- | e.g. <tt>type BaseEnt MyBase = MyChild</tt>
    type BaseEnt ent;
}

-- | Convert from the key of the BaseEnt(ity) to the key of the child
--   entity. This function is not actually called, but that it typechecks
--   proves this operation is safe.
toBaseIdWitness :: ToBaseId ent => Key (BaseEnt ent) -> Key ent

-- | Syntax sugar for <a>case_</a>.
when_ :: expr (Value Bool) -> () -> expr a -> (expr (Value Bool), expr a)

-- | Syntax sugar for <a>case_</a>.
then_ :: ()

-- | Syntax sugar for <a>case_</a>.
else_ :: expr a -> expr a

-- | <tt>FROM</tt> clause: bring entities into scope.
--   
--   Note that this function will be replaced by the one in
--   <a>Database.Esqueleto.Experimental</a> in version 4.0.0.0 of the
--   library. The <tt>Experimental</tt> module has a dramatically improved
--   means for introducing tables and entities that provides more power and
--   less potential for runtime errors.
--   
--   This function internally uses two type classes in order to provide
--   some flexibility of how you may call it. Internally we refer to these
--   type classes as the two different magics.
--   
--   The innermost magic allows you to use <tt>from</tt> with the following
--   types:
--   
--   <ul>
--   <li><tt>expr (Entity val)</tt>, which brings a single entity into
--   scope.</li>
--   <li><tt>expr (Maybe (Entity val))</tt>, which brings a single entity
--   that may be <tt>NULL</tt> into scope. Used for <tt>OUTER
--   JOIN</tt>s.</li>
--   <li>A <tt>JOIN</tt> of any other two types allowed by the innermost
--   magic, where a <tt>JOIN</tt> may be an <a>InnerJoin</a>, a
--   <a>CrossJoin</a>, a <a>LeftOuterJoin</a>, a <a>RightOuterJoin</a>, or
--   a <a>FullOuterJoin</a>. The <tt>JOINs</tt> have left fixity.</li>
--   </ul>
--   
--   The outermost magic allows you to use <tt>from</tt> on any tuples of
--   types supported by innermost magic (and also tuples of tuples, and so
--   on), up to 8-tuples.
--   
--   Note that using <tt>from</tt> for the same entity twice does work and
--   corresponds to a self-join. You don't even need to use two different
--   calls to <tt>from</tt>, you may use a <tt>JOIN</tt> or a tuple.
--   
--   The following are valid examples of uses of <tt>from</tt> (the types
--   of the arguments of the lambda are inside square brackets):
--   
--   <pre>
--   <a>from</a> $ \person -&gt; ...
--   <a>from</a> $ \(person, blogPost) -&gt; ...
--   <a>from</a> $ \(p `<a>LeftOuterJoin</a>` mb) -&gt; ...
--   <a>from</a> $ \(p1 `<a>InnerJoin</a>` f `<a>InnerJoin</a>` p2) -&gt; ...
--   <a>from</a> $ \((p1 `<a>InnerJoin</a>` f) `<a>InnerJoin</a>` p2) -&gt; ...
--   </pre>
--   
--   The types of the arguments to the lambdas above are, respectively:
--   
--   <pre>
--   person
--     :: ( Esqueleto query expr backend
--        , PersistEntity Person
--        , PersistEntityBackend Person ~ backend
--        ) =&gt; expr (Entity Person)
--   (person, blogPost)
--     :: (...) =&gt; (expr (Entity Person), expr (Entity BlogPost))
--   (p `<a>LeftOuterJoin</a>` mb)
--     :: (...) =&gt; InnerJoin (expr (Entity Person)) (expr (Maybe (Entity BlogPost)))
--   (p1 `<a>InnerJoin</a>` f `<a>InnerJoin</a>` p2)
--     :: (...) =&gt; InnerJoin
--                   (InnerJoin (expr (Entity Person))
--                              (expr (Entity Follow)))
--                   (expr (Entity Person))
--   (p1 `<a>InnerJoin</a>` (f `<a>InnerJoin</a>` p2)) ::
--     :: (...) =&gt; InnerJoin
--                   (expr (Entity Person))
--                   (InnerJoin (expr (Entity Follow))
--                              (expr (Entity Person)))
--   </pre>
--   
--   Note that some backends may not support all kinds of <tt>JOIN</tt>s.
from :: From a => (a -> SqlQuery b) -> SqlQuery b

-- | A single value (as opposed to a whole entity). You may use
--   <tt>(<a>^.</a>)</tt> or <tt>(<a>?.</a>)</tt> to get a <a>Value</a>
--   from an <a>Entity</a>.
newtype Value a
Value :: a -> Value a
[unValue] :: Value a -> a

-- | A list of single values. There's a limited set of functions able to
--   work with this data type (such as <a>subList_select</a>,
--   <a>valList</a>, <a>in_</a> and <a>exists</a>).
newtype ValueList a
ValueList :: a -> ValueList a

-- | Phantom type used by <a>orderBy</a>, <a>asc</a> and <a>desc</a>.
data OrderBy

-- | Phantom type used by <a>distinctOn</a> and <a>don</a>.
data DistinctOn

-- | Different kinds of locking clauses supported by <a>locking</a>.
--   
--   Note that each RDBMS has different locking support. The constructors
--   of this datatype specify only the <i>syntax</i> of the locking
--   mechanism, not its <i>semantics</i>. For example, even though both
--   MySQL and PostgreSQL support <a>ForUpdate</a>, there are no guarantees
--   that they will behave the same.
data LockingKind

-- | <tt>FOR UPDATE</tt> syntax. Supported by MySQL, Oracle and PostgreSQL.

-- | <i>Deprecated: The constructors for <a>LockingKind</a> are deprecated
--   in v3.6.0.0. Instead, please refer to the smart constructors
--   <a>forUpdate</a> and <a>forUpdateSkipLocked</a>.</i>
ForUpdate :: LockingKind

-- | <tt>FOR UPDATE SKIP LOCKED</tt> syntax. Supported by MySQL, Oracle and
--   PostgreSQL.

-- | <i>Deprecated: The constructors for <a>LockingKind</a> are deprecated
--   in v3.6.0.0. Instead, please refer to the smart constructors
--   <a>forUpdate</a> and <a>forUpdateSkipLocked</a>.</i>
ForUpdateSkipLocked :: LockingKind

-- | <tt>FOR SHARE</tt> syntax. Supported by PostgreSQL.

-- | <i>Deprecated: The constructors for <a>LockingKind</a> are deprecated
--   in v3.6.0.0. Instead, please refer to the smart constructor
--   <tt>forShare</tt> exported from Database.Esqueleto.PostgreSQL.</i>
ForShare :: LockingKind

-- | <tt>LOCK IN SHARE MODE</tt> syntax. Supported by MySQL.

-- | <i>Deprecated: The constructors for <a>LockingKind</a> are deprecated
--   in v3.6.0.0. Instead, please refer to the smart constructors
--   <tt>lockInShareMode</tt> exported from Database.Esqueleto.MySQL.</i>
LockInShareMode :: LockingKind

-- | <tt>FOR UPDATE</tt> syntax.
--   
--   Usage:
--   
--   <pre>
--   <a>locking</a> <a>forUpdate</a>
--   </pre>
forUpdate :: LockingKind

-- | <tt>FOR UPDATE SKIP LOCKED</tt> syntax.
--   
--   <pre>
--   <a>locking</a> <a>forUpdateSkipLocked</a>
--   </pre>
forUpdateSkipLocked :: LockingKind

-- | Lockable entity
--   
--   Example use:
--   
--   <pre>
--   select $ do
--       (p :&amp; bp) &lt;- from $
--           table <tt>Person
--           <tt>innerJoin</tt> table </tt>BlogPost
--               <a>on</a> do
--                   (p :&amp; bp) -&gt; p ^. PersonId ==. b ^. BlogPostAuthorId
--       forUpdateOf (p :&amp; b) skipLocked
--       return p
--   </pre>
class LockableEntity a
flattenLockableEntity :: LockableEntity a => a -> NonEmpty LockableSqlExpr

-- | Phantom class of data types that are treated as strings by the RDBMS.
--   It has no methods because it's only used to avoid type errors such as
--   trying to concatenate integers.
--   
--   If you have a custom data type or <tt>newtype</tt>, feel free to make
--   it an instance of this class.
class PersistField a => SqlString a

-- | Data type that represents an <tt>INNER JOIN</tt> (see
--   <a>LeftOuterJoin</a> for an example).
data InnerJoin a b
InnerJoin :: a -> b -> InnerJoin a b
infixl 2 `InnerJoin`
infixl 2 `InnerJoin`

-- | Data type that represents a <tt>CROSS JOIN</tt> (see
--   <a>LeftOuterJoin</a> for an example).
data CrossJoin a b
CrossJoin :: a -> b -> CrossJoin a b
infixl 2 `CrossJoin`
infixl 2 `CrossJoin`

-- | Data type that represents a <tt>LEFT OUTER JOIN</tt>. For example,
--   
--   <pre>
--   select $
--   <a>from</a> $ \(person `<tt>LeftOuterJoin</tt>` pet) -&gt;
--     ...
--   </pre>
--   
--   is translated into
--   
--   <pre>
--   SELECT ...
--   FROM Person LEFT OUTER JOIN Pet
--   ...
--   </pre>
--   
--   See also: <a>from</a>.
data LeftOuterJoin a b
LeftOuterJoin :: a -> b -> LeftOuterJoin a b
infixl 2 `LeftOuterJoin`
infixl 2 `LeftOuterJoin`

-- | Data type that represents a <tt>RIGHT OUTER JOIN</tt> (see
--   <a>LeftOuterJoin</a> for an example).
data RightOuterJoin a b
RightOuterJoin :: a -> b -> RightOuterJoin a b
infixl 2 `RightOuterJoin`
infixl 2 `RightOuterJoin`

-- | Data type that represents a <tt>FULL OUTER JOIN</tt> (see
--   <a>LeftOuterJoin</a> for an example).
data FullOuterJoin a b
FullOuterJoin :: a -> b -> FullOuterJoin a b
infixl 2 `FullOuterJoin`
infixl 2 `FullOuterJoin`

-- | (Internal) A kind of <tt>JOIN</tt>.
data JoinKind

-- | <pre>
--   INNER JOIN
--   </pre>
InnerJoinKind :: JoinKind

-- | <pre>
--   CROSS JOIN
--   </pre>
CrossJoinKind :: JoinKind

-- | <pre>
--   LEFT OUTER JOIN
--   </pre>
LeftOuterJoinKind :: JoinKind

-- | <pre>
--   RIGHT OUTER JOIN
--   </pre>
RightOuterJoinKind :: JoinKind

-- | <pre>
--   FULL OUTER JOIN
--   </pre>
FullOuterJoinKind :: JoinKind

-- | Exception thrown whenever <a>on</a> is used to create an <tt>ON</tt>
--   clause but no matching <tt>JOIN</tt> is found.
data OnClauseWithoutMatchingJoinException
OnClauseWithoutMatchingJoinException :: String -> OnClauseWithoutMatchingJoinException

-- | SQL backend for <tt>esqueleto</tt> using <a>SqlPersistT</a>.
data SqlQuery a

-- | An expression on the SQL backend.
--   
--   Raw expression: Contains a <a>SqlExprMeta</a> and a function for
--   building the expr. It recieves a parameter telling it whether it is in
--   a parenthesized context, and takes information about the SQL
--   connection (mainly for escaping names) and returns both an string
--   (<a>Builder</a>) and a list of values to be interpolated by the SQL
--   backend.
data SqlExpr a

-- | Constraint synonym for <tt>persistent</tt> entities whose backend is
--   <a>SqlBackend</a>.
type SqlEntity ent = (PersistEntity ent, PersistEntityBackend ent ~ SqlBackend)

-- | Execute an <tt>esqueleto</tt> <tt>SELECT</tt> query inside
--   <tt>persistent</tt>'s <a>SqlPersistT</a> monad and return a list of
--   rows.
--   
--   We've seen that <a>from</a> has some magic about which kinds of things
--   you may bring into scope. This <a>select</a> function also has some
--   magic for which kinds of things you may bring back to Haskell-land by
--   using <tt>SqlQuery</tt>'s <tt>return</tt>:
--   
--   <ul>
--   <li>You may return a <tt>SqlExpr (<a>Entity</a> v)</tt> for an entity
--   <tt>v</tt> (i.e., like the <tt>*</tt> in SQL), which is then returned
--   to Haskell-land as just <tt>Entity v</tt>.</li>
--   <li>You may return a <tt>SqlExpr (Maybe (Entity v))</tt> for an entity
--   <tt>v</tt> that may be <tt>NULL</tt>, which is then returned to
--   Haskell-land as <tt>Maybe (Entity v)</tt>. Used for <tt>OUTER
--   JOIN</tt>s.</li>
--   <li>You may return a <tt>SqlExpr (<a>Value</a> t)</tt> for a value
--   <tt>t</tt> (i.e., a single column), where <tt>t</tt> is any instance
--   of <a>PersistField</a>, which is then returned to Haskell-land as
--   <tt>Value t</tt>. You may use <tt>Value</tt> to return projections of
--   an <tt>Entity</tt> (see <tt>(<a>^.</a>)</tt> and <tt>(<a>?.</a>)</tt>)
--   or to return any other value calculated on the query (e.g.,
--   <a>countRows</a> or <a>subSelect</a>).</li>
--   </ul>
--   
--   The <tt>SqlSelect a r</tt> class has functional dependencies that
--   allow type information to flow both from <tt>a</tt> to <tt>r</tt> and
--   vice-versa. This means that you'll almost never have to give any type
--   signatures for <tt>esqueleto</tt> queries. For example, the query
--   <tt><a>select</a> $ from $ \p -&gt; return p</tt> alone is ambiguous,
--   but in the context of
--   
--   <pre>
--   do ps &lt;- <a>select</a> $
--            <a>from</a> $ \p -&gt;
--            return p
--      liftIO $ mapM_ (putStrLn . personName . entityVal) ps
--   </pre>
--   
--   we are able to infer from that single <tt>personName . entityVal</tt>
--   function composition that the <tt>p</tt> inside the query is of type
--   <tt>SqlExpr (Entity Person)</tt>.
select :: forall a r (m :: Type -> Type) backend. (SqlSelect a r, MonadIO m, SqlBackendCanRead backend) => SqlQuery a -> ReaderT backend m [r]

-- | Execute an <tt>esqueleto</tt> <tt>SELECT</tt> query inside
--   <tt>persistent</tt>'s <a>SqlPersistT</a> monad and return the first
--   entry wrapped in a <tt>Maybe</tt>. @since 3.5.1.0
--   
--   <h3><b>Example usage</b></h3>
--   
--   <pre>
--   firstPerson :: MonadIO m =&gt; SqlPersistT m (Maybe (Entity Person))
--   firstPerson =
--    <a>selectOne</a> $ do
--        person &lt;- <a>from</a> $ <tt>table</tt> @Person
--        return person
--   </pre>
--   
--   The above query is equivalent to a <a>select</a> combined with
--   <a>limit</a> but you would still have to transform the results from a
--   list:
--   
--   <pre>
--   firstPerson :: MonadIO m =&gt; SqlPersistT m [Entity Person]
--   firstPerson =
--    <a>select</a> $ do
--        person &lt;- <a>from</a> $ <tt>table</tt> @Person
--        <a>limit</a> 1
--        return person
--   </pre>
selectOne :: forall a r (m :: Type -> Type) backend. (SqlSelect a r, MonadIO m, SqlBackendCanRead backend) => SqlQuery a -> ReaderT backend m (Maybe r)

-- | Execute an <tt>esqueleto</tt> <tt>SELECT</tt> query inside
--   <tt>persistent</tt>'s <a>SqlPersistT</a> monad and return a
--   <a>Source</a> of rows.
selectSource :: forall a r backend (m :: Type -> Type). (SqlSelect a r, BackendCompatible SqlBackend backend, IsPersistBackend backend, PersistQueryRead backend, PersistStoreRead backend, PersistUniqueRead backend, MonadResource m) => SqlQuery a -> ConduitT () r (ReaderT backend m) ()

-- | Execute an <tt>esqueleto</tt> <tt>DELETE</tt> query inside
--   <tt>persistent</tt>'s <a>SqlPersistT</a> monad. Note that currently
--   there are no type checks for statements that should not appear on a
--   <tt>DELETE</tt> query.
--   
--   Example of usage:
--   
--   <pre>
--   <a>delete</a> $
--   <a>from</a> $ \appointment -&gt;
--   <a>where_</a> (appointment <a>^.</a> AppointmentDate <a>&lt;.</a> <a>val</a> now)
--   </pre>
--   
--   Unlike <a>select</a>, there is a useful way of using <a>delete</a>
--   that will lead to type ambiguities. If you want to delete all rows
--   (i.e., no <a>where_</a> clause), you'll have to use a type signature:
--   
--   <pre>
--   <a>delete</a> $
--   <a>from</a> $ \(appointment :: <a>SqlExpr</a> (<a>Entity</a> Appointment)) -&gt;
--   return ()
--   </pre>
--   
--   <h4><a>Database.Esqueleto.Experimental</a>:</h4>
--   
--   <pre>
--   delete $ do
--     userFeature &lt;- from $ table @UserFeature
--     where_ ((userFeature ^. UserFeatureFeature) <a>notIn</a> valList allKnownFeatureFlags)
--   </pre>
delete :: forall (m :: Type -> Type) backend. (MonadIO m, SqlBackendCanWrite backend) => SqlQuery () -> ReaderT backend m ()

-- | Same as <a>delete</a>, but returns the number of rows affected.
deleteCount :: forall (m :: Type -> Type) backend. (MonadIO m, SqlBackendCanWrite backend) => SqlQuery () -> ReaderT backend m Int64

-- | Execute an <tt>esqueleto</tt> <tt>UPDATE</tt> query inside
--   <tt>persistent</tt>'s <a>SqlPersistT</a> monad. Note that currently
--   there are no type checks for statements that should not appear on a
--   <tt>UPDATE</tt> query.
--   
--   Example of usage:
--   
--   <pre>
--   <a>update</a> $ \p -&gt; do
--   <a>set</a> p [ PersonAge <a>=.</a> <a>just</a> (<a>val</a> thisYear) -. p <a>^.</a> PersonBorn ]
--   <a>where_</a> $ isNothing (p <a>^.</a> PersonAge)
--   </pre>
update :: forall (m :: Type -> Type) val backend. (MonadIO m, PersistEntity val, BackendCompatible SqlBackend (PersistEntityBackend val), SqlBackendCanWrite backend) => (SqlExpr (Entity val) -> SqlQuery ()) -> ReaderT backend m ()

-- | Same as <a>update</a>, but returns the number of rows affected.
updateCount :: forall (m :: Type -> Type) val backend. (MonadIO m, PersistEntity val, BackendCompatible SqlBackend (PersistEntityBackend val), SqlBackendCanWrite backend) => (SqlExpr (Entity val) -> SqlQuery ()) -> ReaderT backend m Int64

-- | Insert a <a>PersistField</a> for every selected value.
insertSelect :: forall (m :: Type -> Type) a backend. (MonadIO m, PersistEntity a, SqlBackendCanWrite backend) => SqlQuery (SqlExpr (Insertion a)) -> ReaderT backend m ()

-- | Insert a <a>PersistField</a> for every selected value, return the
--   count afterward
insertSelectCount :: forall (m :: Type -> Type) a backend. (MonadIO m, PersistEntity a, SqlBackendCanWrite backend) => SqlQuery (SqlExpr (Insertion a)) -> ReaderT backend m Int64

-- | Apply a <a>PersistField</a> constructor to <tt>SqlExpr Value</tt>
--   arguments.
(<#) :: (a -> b) -> SqlExpr (Value a) -> SqlExpr (Insertion b)

-- | Apply extra <tt>SqlExpr Value</tt> arguments to a <a>PersistField</a>
--   constructor
(<&>) :: SqlExpr (Insertion (a -> b)) -> SqlExpr (Value a) -> SqlExpr (Insertion b)

-- | Renders a <a>SqlQuery</a> into a <a>Text</a> value along with the list
--   of <a>PersistValue</a>s that would be supplied to the database for
--   <tt>?</tt> placeholders.
--   
--   You must ensure that the <a>Mode</a> you pass to this function
--   corresponds with the actual <a>SqlQuery</a>. If you pass a query that
--   uses incompatible features (like an <tt>INSERT</tt> statement with a
--   <tt>SELECT</tt> mode) then you'll get a weird result.
renderQueryToText :: forall a r backend (m :: Type -> Type). (SqlSelect a r, BackendCompatible SqlBackend backend, Monad m) => Mode -> SqlQuery a -> ReaderT backend m (Text, [PersistValue])

-- | Renders a <a>SqlQuery</a> into a <a>Text</a> value along with the list
--   of <a>PersistValue</a>s that would be supplied to the database for
--   <tt>?</tt> placeholders.
renderQuerySelect :: forall a r backend (m :: Type -> Type). (SqlSelect a r, BackendCompatible SqlBackend backend, Monad m) => SqlQuery a -> ReaderT backend m (Text, [PersistValue])

-- | Renders a <a>SqlQuery</a> into a <a>Text</a> value along with the list
--   of <a>PersistValue</a>s that would be supplied to the database for
--   <tt>?</tt> placeholders.
renderQueryUpdate :: forall a r backend (m :: Type -> Type). (SqlSelect a r, BackendCompatible SqlBackend backend, Monad m) => SqlQuery a -> ReaderT backend m (Text, [PersistValue])

-- | Renders a <a>SqlQuery</a> into a <a>Text</a> value along with the list
--   of <a>PersistValue</a>s that would be supplied to the database for
--   <tt>?</tt> placeholders.
renderQueryDelete :: forall a r backend (m :: Type -> Type). (SqlSelect a r, BackendCompatible SqlBackend backend, Monad m) => SqlQuery a -> ReaderT backend m (Text, [PersistValue])

-- | Renders a <a>SqlQuery</a> into a <a>Text</a> value along with the list
--   of <a>PersistValue</a>s that would be supplied to the database for
--   <tt>?</tt> placeholders.
renderQueryInsertInto :: forall a r backend (m :: Type -> Type). (SqlSelect a r, BackendCompatible SqlBackend backend, Monad m) => SqlQuery a -> ReaderT backend m (Text, [PersistValue])

-- | (Internal) Class that implements the tuple <a>from</a> magic (see
--   <a>fromStart</a>).
class From a

-- | <tt>valkey i = <a>val</a> . <a>toSqlKey</a></tt>
--   (<a>https://github.com/prowdsponsor/esqueleto/issues/9</a>).
valkey :: (ToBackendKey SqlBackend entity, PersistField (Key entity)) => Int64 -> SqlExpr (Value (Key entity))

-- | <tt>valJ</tt> is like <tt>val</tt> but for something that is already a
--   <tt>Value</tt>. The use case it was written for was, given a
--   <tt>Value</tt> lift the <tt>Key</tt> for that <tt>Value</tt> into the
--   query expression in a type safe way. However, the implementation is
--   more generic than that so we call it <tt>valJ</tt>.
--   
--   Its important to note that the input entity and the output entity are
--   constrained to be the same by the type signature on the function
--   (<a>https://github.com/prowdsponsor/esqueleto/pull/69</a>).
valJ :: PersistField (Key entity) => Value (Key entity) -> SqlExpr (Value (Key entity))

-- | Avoid N+1 queries and join entities into a map structure.
--   
--   This function is useful to call on the result of a single
--   <tt>JOIN</tt>. For example, suppose you have this query:
--   
--   <pre>
--   getFoosAndNestedBarsFromParent
--       :: ParentId
--       -&gt; SqlPersistT IO [(Entity Foo, Maybe (Entity Bar))]
--   getFoosAndNestedBarsFromParent parentId =
--       <a>select</a> $ do
--           (foo :&amp; bar) &lt;- from $
--               table <tt>Foo
--               <a>`LeftOuterJoin`</a>
--               table </tt>Bar
--                   <a>`on`</a> do
--                       \(foo :&amp; bar) -&gt;
--                           foo ^. FooId ==. bar ?. BarFooId
--           where_ $
--               foo ^. FooParentId ==. val parentId
--           pure (foo, bar)
--   </pre>
--   
--   This is a natural result type for SQL - a list of tuples. However,
--   it's not what we usually want in Haskell - each <tt>Foo</tt> in the
--   list will be represented multiple times, once for each <tt>Bar</tt>.
--   
--   We can write <tt><a>fmap</a> <a>associateJoin</a></tt> and it will
--   translate it into a <tt>Map</tt> that is keyed on the <a>Key</a> of
--   the left <a>Entity</a>, and the value is a tuple of the entity's value
--   as well as the list of each coresponding entity.
--   
--   <pre>
--   getFoosAndNestedBarsFromParentHaskellese
--       :: ParentId
--       -&gt; SqlPersistT (Map (Key Foo) (Foo, [Maybe (Entity Bar)]))
--   getFoosAndNestedBarsFromParentHaskellese parentId =
--       <a>fmap</a> <a>associateJoin</a> $ getFoosdAndNestedBarsFromParent parentId
--   </pre>
--   
--   What if you have multiple joins?
--   
--   Let's use <a>associateJoin</a> with a *two* join query.
--   
--   <pre>
--   userPostComments
--       :: SqlQuery (SqlExpr (Entity User, Entity Post, Entity Comment))
--   userPostsComment = do
--       (u :&amp; p :&amp; c) &lt;- from $
--           table <tt>User
--           <a>`InnerJoin`</a>
--           table </tt>Post
--               <a>on</a> do
--                   \(u :&amp; p) -&gt;
--                       u ^. UserId ==. p ^. PostUserId
--           <a>`InnerJoin`</a>
--           table @Comment
--               <a>`on`</a> do
--                   \(_ :&amp; p :&amp; c) -&gt;
--                       p ^. PostId ==. c ^. CommentPostId
--       pure (u, p, c)
--   </pre>
--   
--   This query returns a User, with all of the users Posts, and then all
--   of the Comments on that post.
--   
--   First, we *nest* the tuple.
--   
--   <pre>
--   nest :: (a, b, c) -&gt; (a, (b, c))
--   nest (a, b, c) = (a, (b, c))
--   </pre>
--   
--   This makes the return of the query conform to the input expected from
--   <a>associateJoin</a>.
--   
--   <pre>
--   nestedUserPostComments
--       :: SqlPersistT IO [(Entity User, (Entity Post, Entity Comment))]
--   nestedUserPostComments =
--       fmap nest $ select userPostsComments
--   </pre>
--   
--   Now, we can call <a>associateJoin</a> on it.
--   
--   <pre>
--   associateUsers
--       :: [(Entity User, (Entity Post, Entity Comment))]
--       -&gt; Map UserId (User, [(Entity Post, Entity Comment)])
--   associateUsers =
--       associateJoin
--   </pre>
--   
--   Next, we'll use the <a>Functor</a> instances for <tt>Map</tt> and
--   tuple to call <a>associateJoin</a> on the <tt>[(Entity Post, Entity
--   Comment)]</tt>.
--   
--   <pre>
--   associatePostsAndComments
--       :: Map UserId (User, [(Entity Post, Entity Comment)])
--       -&gt; Map UserId (User, Map PostId (Post, [Entity Comment]))
--   associatePostsAndComments =
--       fmap (fmap associateJoin)
--   </pre>
--   
--   For more reading on this topic, see <a>this Foxhound Systems blog
--   post</a>.
associateJoin :: forall e1 e0. Ord (Key e0) => [(Entity e0, e1)] -> Map (Key e0) (e0, [e1])

-- | Synonym for <a>delete</a> that does not clash with
--   <tt>esqueleto</tt>'s <a>delete</a>.
deleteKey :: forall backend val (m :: Type -> Type). (PersistStore backend, BaseBackend backend ~ PersistEntityBackend val, MonadIO m, PersistEntity val) => Key val -> ReaderT backend m ()

-- | Persistent serialized Haskell records to the database. A Database
--   <a>Entity</a> (A row in SQL, a document in MongoDB, etc) corresponds
--   to a <a>Key</a> plus a Haskell record.
--   
--   For every Haskell record type stored in the database there is a
--   corresponding <a>PersistEntity</a> 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 <a>PersistEntity</a>, with each query returning
--   different types of Haskell records.
--   
--   Some advanced type system capabilities are used to make this process
--   type-safe. Persistent users usually don't need to understand the class
--   associated data and functions.
class (PersistField Key record, ToJSON Key record, FromJSON Key record, Show Key record, Read Key record, Eq Key record, Ord Key record) => PersistEntity record where {
    
    -- | Persistent allows multiple different backends (databases).
    type PersistEntityBackend record;
    
    -- | By default, a backend will automatically generate the key Instead you
    --   can specify a Primary key made up of unique values.
    data Key record;
    
    -- | An <a>EntityField</a> is parameterised by the Haskell record it
    --   belongs to and the additional type of that field.
    --   
    --   As of <tt>persistent-2.11.0.0</tt>, it's possible to use the
    --   <tt>OverloadedLabels</tt> language extension to refer to
    --   <a>EntityField</a> values polymorphically. See the documentation on
    --   <a>SymbolToField</a> for more information.
    data EntityField record :: Type -> Type;
    
    -- | Unique keys besides the <a>Key</a>.
    data Unique record;
}

-- | A lower-level key operation.
keyToValues :: PersistEntity record => Key record -> [PersistValue]

-- | A lower-level key operation.
keyFromValues :: PersistEntity record => [PersistValue] -> Either Text (Key record)

-- | A meta-operation to retrieve the <a>Key</a> <a>EntityField</a>.
persistIdField :: PersistEntity record => EntityField record (Key record)

-- | Retrieve the <a>EntityDef</a> meta-data for the record.
entityDef :: PersistEntity record => proxy record -> EntityDef

-- | Return meta-data for a given <a>EntityField</a>.
persistFieldDef :: PersistEntity record => EntityField record typ -> FieldDef

-- | A meta-operation to get the database fields of a record.
toPersistFields :: PersistEntity record => record -> [PersistValue]

-- | A lower-level operation to convert from database values to a Haskell
--   record.
fromPersistValues :: PersistEntity record => [PersistValue] -> Either Text record

-- | This function allows you to build an <tt><a>Entity</a> a</tt> by
--   specifying an action that returns a value for the field in the
--   callback function. Let's look at an example.
--   
--   <pre>
--   parseFromEnvironmentVariables :: IO (Entity User)
--   parseFromEnvironmentVariables =
--       tabulateEntityA $ \userField -&gt;
--           case userField of
--               UserName -&gt;
--                   getEnv <a>USER_NAME</a>
--               UserAge -&gt; do
--                   ageVar &lt;- getEnv <a>USER_AGE</a>
--                   case readMaybe ageVar of
--                       Just age -&gt;
--                           pure age
--                       Nothing -&gt;
--                           error $ "Failed to parse Age from: " &lt;&gt; ageVar
--               UserAddressId -&gt; do
--                   addressVar &lt;- getEnv <a>USER_ADDRESS_ID</a>
--                   pure $ AddressKey addressVar
--   </pre>
tabulateEntityA :: (PersistEntity record, Applicative f) => (forall a. () => EntityField record a -> f a) -> f (Entity record)

-- | Like <a>tabulateEntityA</a>, but works with any <a>Apply</a> f. This
--   works because all entities have at least one field, and so we can
--   tabulate things into semigroup-like shapes instead.
tabulateEntityApply :: (PersistEntity record, Apply f) => (forall a. () => EntityField record a -> f a) -> f (Entity record)

-- | A meta operation to retrieve all the <a>Unique</a> keys.
persistUniqueKeys :: PersistEntity record => record -> [Unique record]

-- | A lower level operation.
persistUniqueToFieldNames :: PersistEntity record => Unique record -> NonEmpty (FieldNameHS, FieldNameDB)

-- | A lower level operation.
persistUniqueToValues :: PersistEntity record => Unique record -> [PersistValue]

-- | Use a <a>PersistField</a> as a lens.
fieldLens :: PersistEntity record => EntityField record field -> forall (f :: Type -> Type). Functor f => (field -> f field) -> Entity record -> f (Entity record)

-- | Extract a <tt><a>Key</a> record</tt> from a <tt>record</tt> value.
--   Currently, this is only defined for entities using the
--   <tt>Primary</tt> syntax for natural/composite keys. In a future
--   version of <tt>persistent</tt> which incorporates the ID directly into
--   the entity, this will always be Just.
keyFromRecordM :: PersistEntity record => Maybe (record -> Key record)

-- | By default, a backend will automatically generate the key Instead you
--   can specify a Primary key made up of unique values.
data family Key record
class (Show BackendKey backend, Read BackendKey backend, Eq BackendKey backend, Ord BackendKey backend, PersistStoreRead backend, PersistField BackendKey backend, ToJSON BackendKey backend, FromJSON BackendKey backend) => PersistStoreWrite backend

-- | Create a new record in the database, returning an automatically
--   created key (in SQL an auto-increment id).
--   
--   <h3><b>Example usage</b></h3>
--   
--   Using <a>schema-1</a> and <a>dataset-1</a>, let's insert a new user
--   <tt>John</tt>.
--   
--   <pre>
--   insertJohn :: MonadIO m =&gt; ReaderT SqlBackend m (Key User)
--   insertJohn = insert $ User "John" 30
--   </pre>
--   
--   <pre>
--   johnId &lt;- insertJohn
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will produce this:
--   
--   <pre>
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |40   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   |3    |John  |30   |
--   +-----+------+-----+
--   </pre>
insert :: forall record (m :: Type -> Type). (PersistStoreWrite backend, MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => record -> ReaderT backend m (Key record)

-- | Same as <a>insert</a>, but doesn't return a <tt>Key</tt>.
--   
--   <h3><b>Example usage</b></h3>
--   
--   with <a>schema-1</a> and <a>dataset-1</a>,
--   
--   <pre>
--   insertJohn :: MonadIO m =&gt; ReaderT SqlBackend m (Key User)
--   insertJohn = insert_ $ User "John" 30
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will produce this:
--   
--   <pre>
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |40   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   |3    |John  |30   |
--   +-----+------+-----+
--   </pre>
insert_ :: forall record (m :: Type -> Type). (PersistStoreWrite backend, MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => record -> ReaderT backend m ()

-- | Create multiple records in the database and return their <a>Key</a>s.
--   
--   If you don't need the inserted <a>Key</a>s, use <a>insertMany_</a>.
--   
--   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
--   <tt>mapM insert</tt>.
--   
--   <h3><b>Example usage</b></h3>
--   
--   with <a>schema-1</a> and <a>dataset-1</a>,
--   
--   <pre>
--   insertUsers :: MonadIO m =&gt; ReaderT SqlBackend m [Key User]
--   insertUsers = insertMany [User "John" 30, User "Nick" 32, User "Jane" 20]
--   </pre>
--   
--   <pre>
--   userIds &lt;- insertUsers
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will produce this:
--   
--   <pre>
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |40   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   |3    |John  |30   |
--   +-----+------+-----+
--   |4    |Nick  |32   |
--   +-----+------+-----+
--   |5    |Jane  |20   |
--   +-----+------+-----+
--   </pre>
insertMany :: forall record (m :: Type -> Type). (PersistStoreWrite backend, MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => [record] -> ReaderT backend m [Key record]

-- | Same as <a>insertMany</a>, but doesn't return any <a>Key</a>s.
--   
--   The MongoDB, PostgreSQL, SQLite and MySQL backends insert all records
--   in one database query.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>,
--   
--   <pre>
--   insertUsers_ :: MonadIO m =&gt; ReaderT SqlBackend m ()
--   insertUsers_ = insertMany_ [User "John" 30, User "Nick" 32, User "Jane" 20]
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will produce this:
--   
--   <pre>
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |40   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   |3    |John  |30   |
--   +-----+------+-----+
--   |4    |Nick  |32   |
--   +-----+------+-----+
--   |5    |Jane  |20   |
--   +-----+------+-----+
--   </pre>
insertMany_ :: forall record (m :: Type -> Type). (PersistStoreWrite backend, MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => [record] -> ReaderT backend m ()

-- | Same as <a>insertMany_</a>, but takes an <a>Entity</a> 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.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>,
--   
--   <pre>
--   insertUserEntityMany :: MonadIO m =&gt; ReaderT SqlBackend m ()
--   insertUserEntityMany = insertEntityMany [SnakeEntity, EvaEntity]
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will produce this:
--   
--   <pre>
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |40   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   |3    |Snake |38   |
--   +-----+------+-----+
--   |4    |Eva   |38   |
--   +-----+------+-----+
--   </pre>
insertEntityMany :: forall record (m :: Type -> Type). (PersistStoreWrite backend, MonadIO m, PersistRecordBackend record backend) => [Entity record] -> ReaderT backend m ()

-- | Create a new record in the database using the given key.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>,
--   
--   <pre>
--   insertAliceKey :: MonadIO m =&gt; Key User -&gt; ReaderT SqlBackend m ()
--   insertAliceKey key = insertKey key $ User "Alice" 20
--   </pre>
--   
--   <pre>
--   insertAliceKey $ UserKey {unUserKey = SqlBackendKey {unSqlBackendKey = 3}}
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will produce this:
--   
--   <pre>
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |40   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   |3    |Alice |20   |
--   +-----+------+-----+
--   </pre>
insertKey :: forall record (m :: Type -> Type). (PersistStoreWrite backend, MonadIO m, PersistRecordBackend record backend) => Key record -> record -> ReaderT backend m ()

-- | Put the record in the database with the given key. Unlike
--   <a>replace</a>, if a record with the given key does not exist then a
--   new record will be inserted.
--   
--   <h3><b>Example usage</b></h3>
--   
--   We try to explain <tt>upsertBy</tt> using <a>schema-1</a> and
--   <a>dataset-1</a>.
--   
--   First, we insert Philip to <a>dataset-1</a>.
--   
--   <pre>
--   insertPhilip :: MonadIO m =&gt; ReaderT SqlBackend m (Key User)
--   insertPhilip = insert $ User "Philip" 42
--   </pre>
--   
--   <pre>
--   philipId &lt;- insertPhilip
--   </pre>
--   
--   This query will produce:
--   
--   <pre>
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |40   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   |3    |Philip|42   |
--   +-----+------+-----+
--   </pre>
--   
--   <pre>
--   repsertHaskell :: MonadIO m =&gt; Key record -&gt; ReaderT SqlBackend m ()
--   repsertHaskell id = repsert id $ User "Haskell" 81
--   </pre>
--   
--   <pre>
--   repsertHaskell philipId
--   </pre>
--   
--   This query will replace Philip's record with Haskell's one:
--   
--   <pre>
--   +-----+-----------------+--------+
--   |id   |name             |age     |
--   +-----+-----------------+--------+
--   |1    |SPJ              |40      |
--   +-----+-----------------+--------+
--   |2    |Simon            |41      |
--   +-----+-----------------+--------+
--   |3    |Philip -&gt; Haskell|42 -&gt; 81|
--   +-----+-----------------+--------+
--   </pre>
--   
--   <a>repsert</a> inserts the given record if the key doesn't exist.
--   
--   <pre>
--   repsertXToUnknown :: MonadIO m =&gt; ReaderT SqlBackend m ()
--   repsertXToUnknown = repsert unknownId $ User "X" 999
--   </pre>
--   
--   For example, applying the above query to <a>dataset-1</a> will produce
--   this:
--   
--   <pre>
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |40   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   |3    |X     |999  |
--   +-----+------+-----+
--   </pre>
repsert :: forall record (m :: Type -> Type). (PersistStoreWrite backend, MonadIO m, PersistRecordBackend record backend) => Key record -> record -> ReaderT backend m ()

-- | Put many entities into the database.
--   
--   Batch version of <a>repsert</a> for SQL backends.
--   
--   Useful when migrating data from one entity to another and want to
--   preserve ids.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>,
--   
--   <pre>
--   repsertManyUsers :: MonadIO m =&gt;ReaderT SqlBackend m ()
--   repsertManyusers = repsertMany [(simonId, User "Philip" 20), (unknownId999, User "Mr. X" 999)]
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will produce this:
--   
--   <pre>
--   +-----+----------------+---------+
--   |id   |name            |age      |
--   +-----+----------------+---------+
--   |1    |SPJ             |40       |
--   +-----+----------------+---------+
--   |2    |Simon -&gt; Philip |41 -&gt; 20 |
--   +-----+----------------+---------+
--   |999  |Mr. X           |999      |
--   +-----+----------------+---------+
--   </pre>
repsertMany :: forall record (m :: Type -> Type). (PersistStoreWrite backend, 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
--   <a>insertKey</a> or <a>repsert</a> in these cases.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1 schama-1</a> and <a>dataset-1</a>,
--   
--   <pre>
--   replaceSpj :: MonadIO m =&gt; User -&gt; ReaderT SqlBackend m ()
--   replaceSpj record = replace spjId record
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will produce this:
--   
--   <pre>
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |Mike  |45   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   </pre>
replace :: forall record (m :: Type -> Type). (PersistStoreWrite backend, MonadIO m, PersistRecordBackend record backend) => Key record -> record -> ReaderT backend m ()

-- | Update individual fields on a specific record, and retrieve the
--   updated value from the database.
--   
--   Note that this function will throw an exception if the given key is
--   not found in the database.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>,
--   
--   <pre>
--   updateGetSpj :: MonadIO m =&gt; [Update User] -&gt; ReaderT SqlBackend m User
--   updateGetSpj updates = updateGet spjId updates
--   </pre>
--   
--   <pre>
--   spj &lt;- updateGetSpj [UserAge +=. 100]
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will produce this:
--   
--   <pre>
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |140  |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   </pre>
updateGet :: forall record (m :: Type -> Type). (PersistStoreWrite backend, MonadIO m, PersistRecordBackend record backend) => Key record -> [Update record] -> ReaderT backend m record
data PersistFilter
Eq :: PersistFilter
Ne :: PersistFilter
Gt :: PersistFilter
Lt :: PersistFilter
Ge :: PersistFilter
Le :: PersistFilter
In :: PersistFilter
NotIn :: PersistFilter
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

-- | Get a record by identifier, if available.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>,
--   
--   <pre>
--   getSpj :: MonadIO m =&gt; ReaderT SqlBackend m (Maybe User)
--   getSpj = get spjId
--   </pre>
--   
--   <pre>
--   mspj &lt;- getSpj
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will get this:
--   
--   <pre>
--   +------+-----+
--   | name | age |
--   +------+-----+
--   | SPJ  |  40 |
--   +------+-----+
--   </pre>
get :: forall record (m :: Type -> Type). (PersistStoreRead backend, MonadIO m, PersistRecordBackend record backend) => Key record -> ReaderT backend m (Maybe record)

-- | Get many records by their respective identifiers, if available.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>:
--   
--   <pre>
--   getUsers :: MonadIO m =&gt; ReaderT SqlBackend m (Map (Key User) User)
--   getUsers = getMany allkeys
--   </pre>
--   
--   <pre>
--   musers &lt;- getUsers
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will get these
--   records:
--   
--   <pre>
--   +----+-------+-----+
--   | id | name  | age |
--   +----+-------+-----+
--   |  1 | SPJ   |  40 |
--   +----+-------+-----+
--   |  2 | Simon |  41 |
--   +----+-------+-----+
--   </pre>
getMany :: forall record (m :: Type -> Type). (PersistStoreRead backend, MonadIO m, PersistRecordBackend record backend) => [Key record] -> ReaderT backend m (Map (Key record) record)

-- | Some functions in this module (<a>insertUnique</a>, <a>insertBy</a>,
--   and <a>replaceUnique</a>) first query the unique indexes to check for
--   conflicts. You could instead optimistically attempt to perform the
--   operation (e.g. <a>replace</a> instead of <a>replaceUnique</a>).
--   However,
--   
--   <ul>
--   <li>there is some fragility to trying to catch the correct exception
--   and determing the column of failure;</li>
--   <li>an exception will automatically abort the current SQL
--   transaction.</li>
--   </ul>
class (PersistUniqueRead backend, PersistStoreWrite backend) => PersistUniqueWrite backend

-- | Delete a specific record by unique key. Does nothing if no record
--   matches.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>,
--   
--   <pre>
--   deleteBySpjName :: MonadIO m =&gt; ReaderT SqlBackend m ()
--   deleteBySpjName = deleteBy (UniqueUserName "SPJ")
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will produce this:
--   
--   <pre>
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   </pre>
deleteBy :: forall record (m :: Type -> Type). (PersistUniqueWrite backend, MonadIO m, PersistRecordBackend record backend) => Unique record -> ReaderT backend m ()

-- | Like <a>insert</a>, but returns <a>Nothing</a> when the record
--   couldn't be inserted because of a uniqueness constraint.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>, we try to insert the
--   following two records:
--   
--   <pre>
--   linusId &lt;- insertUnique $ User "Linus" 48
--   spjId   &lt;- insertUnique $ User "SPJ" 90
--   </pre>
--   
--   <pre>
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |40   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   |3    |Linus |48   |
--   +-----+------+-----+
--   </pre>
--   
--   Linus's record was inserted to <a>dataset-1</a>, while SPJ wasn't
--   because SPJ already exists in <a>dataset-1</a>.
insertUnique :: forall record (m :: Type -> Type). (PersistUniqueWrite backend, MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => record -> ReaderT backend m (Maybe (Key record))

-- | Same as <a>insertUnique</a> but doesn't return a <tt>Key</tt>.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>, we try to insert the
--   following two records:
--   
--   <pre>
--   linusId &lt;- insertUnique_ $ User "Linus" 48
--   spjId   &lt;- insertUnique_ $ User "SPJ" 90
--   </pre>
--   
--   <pre>
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |40   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   |3    |Linus |48   |
--   +-----+------+-----+
--   </pre>
--   
--   Linus's record was inserted to <a>dataset-1</a>, while SPJ wasn't
--   because SPJ already exists in <a>dataset-1</a>.
insertUnique_ :: forall record (m :: Type -> Type). (PersistUniqueWrite backend, MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => record -> ReaderT backend m (Maybe ())

-- | Update based on a uniqueness constraint or insert:
--   
--   <ul>
--   <li>insert the new record if it does not exist;</li>
--   <li>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.</li>
--   </ul>
--   
--   <h3><b>Example usage</b></h3>
--   
--   First, we try to explain <a>upsert</a> using <a>schema-1</a> and
--   <a>dataset-1</a>.
--   
--   <pre>
--   upsertSpj :: MonadIO m =&gt; [Update User] -&gt; ReaderT SqlBackend m (Maybe (Entity User))
--   upsertSpj updates = upsert (User "SPJ" 999) updates
--   </pre>
--   
--   <pre>
--   mSpjEnt &lt;- upsertSpj [UserAge +=. 15]
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will produce this:
--   
--   <pre>
--   +-----+-----+--------+
--   |id   |name |age     |
--   +-----+-----+--------+
--   |1    |SPJ  |40 -&gt; 55|
--   +-----+-----+--------+
--   |2    |Simon|41      |
--   +-----+-----+--------+
--   </pre>
--   
--   <pre>
--   upsertX :: MonadIO m =&gt; [Update User] -&gt; ReaderT SqlBackend m (Maybe (Entity User))
--   upsertX updates = upsert (User "X" 999) updates
--   </pre>
--   
--   <pre>
--   mXEnt &lt;- upsertX [UserAge +=. 15]
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will produce this:
--   
--   <pre>
--   +-----+-----+--------+
--   |id   |name |age     |
--   +-----+-----+--------+
--   |1    |SPJ  |40      |
--   +-----+-----+--------+
--   |2    |Simon|41      |
--   +-----+-----+--------+
--   |3    |X    |999     |
--   +-----+-----+--------+
--   </pre>
--   
--   Next, what if the schema has two uniqueness constraints? Let's check
--   it out using <a>schema-2</a>:
--   
--   <pre>
--   mSpjEnt &lt;- upsertSpj [UserAge +=. 15]
--   </pre>
--   
--   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
--   <a>upsertBy</a> to select the unique key we want.
upsert :: forall record (m :: Type -> Type). (PersistUniqueWrite backend, MonadIO m, PersistRecordBackend record backend, OnlyOneUniqueKey record, SafeToInsert record) => record -> [Update record] -> ReaderT backend m (Entity record)

-- | Update based on a given uniqueness constraint or insert:
--   
--   <ul>
--   <li>insert the new record if it does not exist;</li>
--   <li>update the existing record that matches the given uniqueness
--   constraint.</li>
--   </ul>
--   
--   <h3><b>Example usage</b></h3>
--   
--   We try to explain <a>upsertBy</a> using <a>schema-2</a> and
--   <a>dataset-1</a>.
--   
--   <pre>
--   upsertBySpjName :: MonadIO m =&gt; User -&gt; [Update User] -&gt; ReaderT SqlBackend m (Entity User)
--   upsertBySpjName record updates = upsertBy (UniqueUserName "SPJ") record updates
--   </pre>
--   
--   <pre>
--   mSpjEnt &lt;- upsertBySpjName (Person "X" 999) [PersonAge += .15]
--   </pre>
--   
--   The above query will alter <a>dataset-1</a> to:
--   
--   <pre>
--   +-----+-----+--------+
--   |id   |name |age     |
--   +-----+-----+--------+
--   |1    |SPJ  |40 -&gt; 55|
--   +-----+-----+--------+
--   |2    |Simon|41      |
--   +-----+-----+--------+
--   </pre>
--   
--   <pre>
--   upsertBySimonAge :: MonadIO m =&gt; User -&gt; [Update User] -&gt; ReaderT SqlBackend m (Entity User)
--   upsertBySimonAge record updates = upsertBy (UniqueUserName "SPJ") record updates
--   </pre>
--   
--   <pre>
--   mPhilipEnt &lt;- upsertBySimonAge (User "X" 999) [UserName =. "Philip"]
--   </pre>
--   
--   The above query will alter <a>dataset-1</a> to:
--   
--   <pre>
--   +----+-----------------+-----+
--   | id |      name       | age |
--   +----+-----------------+-----+
--   |  1 | SPJ             |  40 |
--   +----+-----------------+-----+
--   |  2 | Simon -&gt; Philip |  41 |
--   +----+-----------------+-----+
--   </pre>
--   
--   <pre>
--   upsertByUnknownName :: MonadIO m =&gt; User -&gt; [Update User] -&gt; ReaderT SqlBackend m (Entity User)
--   upsertByUnknownName record updates = upsertBy (UniqueUserName "Unknown") record updates
--   </pre>
--   
--   <pre>
--   mXEnt &lt;- upsertByUnknownName (User "X" 999) [UserAge +=. 15]
--   </pre>
--   
--   This query will alter <a>dataset-1</a> to:
--   
--   <pre>
--   +-----+-----+-----+
--   |id   |name |age  |
--   +-----+-----+-----+
--   |1    |SPJ  |40   |
--   +-----+-----+-----+
--   |2    |Simon|41   |
--   +-----+-----+-----+
--   |3    |X    |999  |
--   +-----+-----+-----+
--   </pre>
upsertBy :: forall record (m :: Type -> Type). (PersistUniqueWrite backend, MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => Unique record -> record -> [Update record] -> ReaderT backend m (Entity record)

-- | Put many records into db
--   
--   <ul>
--   <li>insert new records that do not exist (or violate any unique
--   constraints)</li>
--   <li>replace existing records (matching any unique constraint)</li>
--   </ul>
putMany :: forall record (m :: Type -> Type). (PersistUniqueWrite backend, MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => [record] -> ReaderT backend m ()

-- | Insert a value, checking for conflicts with any unique constraints. If
--   a duplicate exists in the database, it is returned as <a>Left</a>.
--   Otherwise, the new 'Key is returned as <a>Right</a>.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-2</a> and <a>dataset-1</a>, we have following lines of
--   code:
--   
--   <pre>
--   l1 &lt;- insertBy $ User "SPJ" 20
--   l2 &lt;- insertBy $ User "XXX" 41
--   l3 &lt;- insertBy $ User "SPJ" 40
--   r1 &lt;- insertBy $ User "XXX" 100
--   </pre>
--   
--   First three lines return <a>Left</a> because there're duplicates in
--   given record's uniqueness constraints. While the last line returns a
--   new key as <a>Right</a>.
insertBy :: forall record backend (m :: Type -> Type). (MonadIO m, PersistUniqueWrite backend, PersistRecordBackend record backend, AtLeastOneUniqueKey record, SafeToInsert record) => record -> ReaderT backend m (Either (Entity record) (Key record))

-- | Given a list of old entity definitions and a new <a>EntityDef</a> in
--   <tt>val</tt>, this creates a <a>Migration</a> to update the old list
--   of definitions with the new one.
migrate :: [EntityDef] -> EntityDef -> Migration

-- | Report a single error in a <a>Migration</a>.
reportError :: Text -> Migration

-- | Unique keys besides the <a>Key</a>.
data family Unique record

-- | A single column (see <tt>rawSql</tt>). Any <tt>PersistField</tt> may
--   be used here, including <a>PersistValue</a> (which does not do any
--   processing).
newtype Single a
Single :: a -> Single a
[unSingle] :: Single a -> a
data Column
Column :: !FieldNameDB -> !Bool -> !SqlType -> !Maybe Text -> !Maybe Text -> !Maybe ConstraintNameDB -> !Maybe Integer -> !Maybe ColumnReference -> Column
[cName] :: Column -> !FieldNameDB
[cNull] :: Column -> !Bool
[cSqlType] :: Column -> !SqlType
[cDefault] :: Column -> !Maybe Text
[cGenerated] :: Column -> !Maybe Text
[cDefaultConstraintName] :: Column -> !Maybe ConstraintNameDB
[cMaxLen] :: Column -> !Maybe Integer
[cReference] :: Column -> !Maybe ColumnReference

-- | Execute a raw SQL statement and return its results as a list. If you
--   do not expect a return value, use of <a>rawExecute</a> is recommended.
--   
--   If you're using <a>Entity</a><tt>s</tt> (which is quite likely), then
--   you <i>must</i> use entity selection placeholders (double question
--   mark, <tt>??</tt>). These <tt>??</tt> placeholders are then replaced
--   for the names of the columns that we need for your entities. You'll
--   receive an error if you don't use the placeholders. Please see the
--   <a>Entity</a><tt>s</tt> documentation for more details.
--   
--   You may put value placeholders (question marks, <tt>?</tt>) in your
--   SQL query. These placeholders are then replaced by the values you pass
--   on the second parameter, already correctly escaped. You may want to
--   use <a>toPersistValue</a> to help you constructing the placeholder
--   values.
--   
--   Since you're giving a raw SQL statement, you don't get any guarantees
--   regarding safety. If <a>rawSql</a> is not able to parse the results of
--   your query back, then an exception is raised. However, most common
--   problems are mitigated by using the entity selection placeholder
--   <tt>??</tt>, and you shouldn't see any error at all if you're not
--   using <a>Single</a>.
--   
--   Some example of <a>rawSql</a> based on this schema:
--   
--   <pre>
--   share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
--   Person
--       name String
--       age Int Maybe
--       deriving Show
--   BlogPost
--       title String
--       authorId PersonId
--       deriving Show
--   |]
--   </pre>
--   
--   Examples based on the above schema:
--   
--   <pre>
--   getPerson :: MonadIO m =&gt; ReaderT SqlBackend m [Entity Person]
--   getPerson = rawSql "select ?? from person where name=?" [PersistText "john"]
--   
--   getAge :: MonadIO m =&gt; ReaderT SqlBackend m [Single Int]
--   getAge = rawSql "select person.age from person where name=?" [PersistText "john"]
--   
--   getAgeName :: MonadIO m =&gt; ReaderT SqlBackend m [(Single Int, Single Text)]
--   getAgeName = rawSql "select person.age, person.name from person where name=?" [PersistText "john"]
--   
--   getPersonBlog :: MonadIO m =&gt; ReaderT SqlBackend m [(Entity Person, Entity BlogPost)]
--   getPersonBlog = rawSql "select ??,?? from person,blog_post where person.id = blog_post.author_id" []
--   </pre>
--   
--   Minimal working program for PostgreSQL backend based on the above
--   concepts:
--   
--   <pre>
--   {-# LANGUAGE EmptyDataDecls             #-}
--   {-# LANGUAGE FlexibleContexts           #-}
--   {-# LANGUAGE GADTs                      #-}
--   {-# LANGUAGE GeneralizedNewtypeDeriving #-}
--   {-# LANGUAGE MultiParamTypeClasses      #-}
--   {-# LANGUAGE OverloadedStrings          #-}
--   {-# LANGUAGE QuasiQuotes                #-}
--   {-# LANGUAGE TemplateHaskell            #-}
--   {-# LANGUAGE TypeFamilies               #-}
--   
--   import           Control.Monad.IO.Class  (liftIO)
--   import           Control.Monad.Logger    (runStderrLoggingT)
--   import           Database.Persist
--   import           Control.Monad.Reader
--   import           Data.Text
--   import           Database.Persist.Sql
--   import           Database.Persist.Postgresql
--   import           Database.Persist.TH
--   
--   share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
--   Person
--       name String
--       age Int Maybe
--       deriving Show
--   |]
--   
--   conn = "host=localhost dbname=new_db user=postgres password=postgres port=5432"
--   
--   getPerson :: MonadIO m =&gt; ReaderT SqlBackend m [Entity Person]
--   getPerson = rawSql "select ?? from person where name=?" [PersistText "sibi"]
--   
--   liftSqlPersistMPool y x = liftIO (runSqlPersistMPool y x)
--   
--   main :: IO ()
--   main = runStderrLoggingT $ withPostgresqlPool conn 10 $ liftSqlPersistMPool $ do
--            runMigration migrateAll
--            xs &lt;- getPerson
--            liftIO (print xs)
--   </pre>
rawSql :: forall a (m :: Type -> Type) backend. (RawSql a, MonadIO m, BackendCompatible SqlBackend backend) => Text -> [PersistValue] -> ReaderT backend m [a]

-- | Represents a value containing all the configuration options for a
--   specific backend. This abstraction makes it easier to write code that
--   can easily swap backends.
class PersistConfig c where {
    type PersistConfigBackend c :: Type -> Type -> Type -> Type;
    type PersistConfigPool c;
}

-- | Load the config settings from a <a>Value</a>, most likely taken from a
--   YAML config file.
loadConfig :: PersistConfig c => Value -> Parser c

-- | Modify the config settings based on environment variables.
applyEnv :: PersistConfig c => c -> IO c

-- | Create a new connection pool based on the given config settings.
createPoolConfig :: PersistConfig c => c -> IO (PersistConfigPool c)

-- | Run a database action by taking a connection from the pool.
runPool :: (PersistConfig c, MonadUnliftIO m) => c -> PersistConfigBackend c m a -> PersistConfigPool c -> m a
type family PersistConfigBackend c :: Type -> Type -> Type -> Type
type family PersistConfigPool c

-- | An <a>ConstraintNameHS</a> represents the Haskell-side name that
--   <tt>persistent</tt> will use for a constraint.
newtype ConstraintNameHS
ConstraintNameHS :: Text -> ConstraintNameHS
[unConstraintNameHS] :: ConstraintNameHS -> Text

-- | A <a>ConstraintNameDB</a> represents the datastore-side name that
--   <tt>persistent</tt> will use for a constraint.
newtype ConstraintNameDB
ConstraintNameDB :: Text -> ConstraintNameDB
[unConstraintNameDB] :: ConstraintNameDB -> Text

-- | An <a>EntityNameDB</a> represents the datastore-side name that
--   <tt>persistent</tt> will use for an entity.
newtype EntityNameDB
EntityNameDB :: Text -> EntityNameDB
[unEntityNameDB] :: EntityNameDB -> Text

-- | An <a>EntityNameHS</a> represents the Haskell-side name that
--   <tt>persistent</tt> will use for an entity.
newtype EntityNameHS
EntityNameHS :: Text -> EntityNameHS
[unEntityNameHS] :: EntityNameHS -> Text

-- | A <a>FieldNameHS</a> represents the Haskell-side name that
--   <tt>persistent</tt> will use for a field.
newtype FieldNameHS
FieldNameHS :: Text -> FieldNameHS
[unFieldNameHS] :: FieldNameHS -> Text

-- | A <a>FieldNameDB</a> represents the datastore-side name that
--   <tt>persistent</tt> will use for a field.
newtype FieldNameDB
FieldNameDB :: Text -> FieldNameDB
[unFieldNameDB] :: FieldNameDB -> Text

-- | Convenience operations for working with '-NameDB' types.
class DatabaseName a
escapeWith :: DatabaseName a => (Text -> str) -> a -> str

-- | A type that determines how a backend should handle the literal.
data LiteralType

-- | The accompanying value will be escaped before inserting into the
--   database. This is the correct default choice to use.
Escaped :: LiteralType

-- | The accompanying value will not be escaped when inserting into the
--   database. This is potentially dangerous - use this with care.
Unescaped :: LiteralType

-- | The <a>DbSpecific</a> constructor corresponds to the legacy
--   <a>PersistDbSpecific</a> 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.
DbSpecific :: LiteralType

-- | A raw value which can be stored in any backend and can be marshalled
--   to and from a <tt>PersistField</tt>.
data PersistValue
PersistText :: Text -> PersistValue
PersistByteString :: ByteString -> PersistValue
PersistInt64 :: Int64 -> PersistValue
PersistDouble :: Double -> PersistValue
PersistRational :: Rational -> PersistValue
PersistBool :: Bool -> PersistValue
PersistDay :: Day -> PersistValue
PersistTimeOfDay :: TimeOfDay -> PersistValue
PersistUTCTime :: UTCTime -> PersistValue
PersistNull :: PersistValue
PersistList :: [PersistValue] -> PersistValue
PersistMap :: [(Text, PersistValue)] -> PersistValue

-- | Intended especially for MongoDB backend
PersistObjectId :: ByteString -> PersistValue

-- | Intended especially for PostgreSQL backend for text arrays
PersistArray :: [PersistValue] -> PersistValue

-- | This constructor is used to specify some raw literal value for the
--   backend. The <a>LiteralType</a> value specifies how the value should
--   be escaped. This can be used to make special, custom types avaialable
--   in the back end.
PersistLiteral_ :: LiteralType -> ByteString -> PersistValue

-- | This pattern synonym used to be a data constructor on
--   <a>PersistValue</a>, but was changed into a catch-all pattern synonym
--   to allow backwards compatiblity with database types. See the
--   documentation on <a>PersistDbSpecific</a> for more details.
pattern PersistLiteral :: ByteString -> PersistValue

-- | This pattern synonym used to be a data constructor on
--   <a>PersistValue</a>, but was changed into a catch-all pattern synonym
--   to allow backwards compatiblity with database types. See the
--   documentation on <a>PersistDbSpecific</a> for more details.
pattern PersistLiteralEscaped :: ByteString -> PersistValue

-- | This pattern synonym used to be a data constructor for the
--   <a>PersistValue</a> 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 <a>PersistLiteral_</a> directly.
--   
--   If you use this, it will overlap a patern match on the
--   'PersistLiteral_, <a>PersistLiteral</a>, and
--   <a>PersistLiteralEscaped</a> patterns. If you need to disambiguate
--   between these constructors, pattern match on <a>PersistLiteral_</a>
--   directly.
pattern PersistDbSpecific :: ByteString -> PersistValue
fromPersistValueText :: PersistValue -> Either Text Text

-- | Please refer to the documentation for the database in question for a
--   full overview of the semantics of the varying isolation levels
data IsolationLevel
ReadUncommitted :: IsolationLevel
ReadCommitted :: IsolationLevel
RepeatableRead :: IsolationLevel
Serializable :: IsolationLevel

-- | A <a>FieldDef</a> represents the inormation that <tt>persistent</tt>
--   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.
data FieldDef
FieldDef :: !FieldNameHS -> !FieldNameDB -> !FieldType -> !SqlType -> ![FieldAttr] -> !Bool -> !ReferenceDef -> !FieldCascade -> !Maybe Text -> !Maybe Text -> !Bool -> FieldDef

-- | The 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
--   <a>FieldDef</a> that contains a <tt><a>FieldNameHS</a> "name"</tt> for
--   a type <tt>User</tt> will have a record field <tt>userName</tt>.
[fieldHaskell] :: FieldDef -> !FieldNameHS

-- | The name of the field in the database. For SQL databases, this
--   corresponds to the column name.
[fieldDB] :: FieldDef -> !FieldNameDB

-- | The type of the field in Haskell.
[fieldType] :: FieldDef -> !FieldType

-- | The type of the field in a SQL database.
[fieldSqlType] :: FieldDef -> !SqlType

-- | User annotations for a field. These are provided with the <tt>!</tt>
--   operator.
[fieldAttrs] :: FieldDef -> ![FieldAttr]

-- | If this is <a>True</a>, then the Haskell datatype will have a strict
--   record field. The default value for this is <a>True</a>.
[fieldStrict] :: FieldDef -> !Bool
[fieldReference] :: FieldDef -> !ReferenceDef

-- | Defines how operations on the field cascade on to the referenced
--   tables. This doesn't have any meaning if the <a>fieldReference</a> is
--   set to <a>NoReference</a> or <a>SelfReference</a>. The cascade option
--   here should be the same as the one obtained in the
--   <a>fieldReference</a>.
[fieldCascade] :: FieldDef -> !FieldCascade

-- | Optional comments for a <tt>Field</tt>.
[fieldComments] :: FieldDef -> !Maybe Text

-- | Whether or not the field is a <tt>GENERATED</tt> column, and
--   additionally the expression to use for generation.
[fieldGenerated] :: FieldDef -> !Maybe Text

-- | <a>True</a> if the field is an implicit ID column. <a>False</a>
--   otherwise.
[fieldIsImplicitIdColumn] :: FieldDef -> !Bool
data PersistUpdate
Assign :: PersistUpdate
Add :: PersistUpdate
Subtract :: PersistUpdate
Multiply :: PersistUpdate
Divide :: PersistUpdate
BackendSpecificUpdate :: Text -> PersistUpdate
type family BackendSpecificUpdate backend record
data UpdateException
KeyNotFound :: String -> UpdateException
UpsertError :: String -> UpdateException

-- | 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.
data SqlType
SqlString :: SqlType
SqlInt32 :: SqlType
SqlInt64 :: SqlType
SqlReal :: SqlType
SqlNumeric :: Word32 -> Word32 -> SqlType
SqlBool :: SqlType
SqlDay :: SqlType
SqlTime :: SqlType

-- | Always uses UTC timezone
SqlDayTime :: SqlType
SqlBlob :: SqlType

-- | a backend-specific name
SqlOther :: Text -> SqlType
data PersistException

-- | Generic Exception
PersistError :: Text -> PersistException
PersistMarshalError :: Text -> PersistException
PersistInvalidField :: Text -> PersistException
PersistForeignConstraintUnmet :: Text -> PersistException
PersistMongoDBError :: Text -> PersistException
PersistMongoDBUnsupported :: Text -> PersistException

-- | An action that might happen on a deletion or update on a foreign key
--   change.
data CascadeAction
Cascade :: CascadeAction
Restrict :: CascadeAction
SetNull :: CascadeAction
SetDefault :: CascadeAction

-- | 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 <a>Nothing</a> in either of the field values means that
--   the user has not specified a <a>CascadeAction</a>. An unspecified
--   <a>CascadeAction</a> is defaulted to <a>Restrict</a> when doing
--   migrations.
data FieldCascade
FieldCascade :: !Maybe CascadeAction -> !Maybe CascadeAction -> FieldCascade
[fcOnUpdate] :: FieldCascade -> !Maybe CascadeAction
[fcOnDelete] :: FieldCascade -> !Maybe CascadeAction
data ForeignDef
ForeignDef :: !EntityNameHS -> !EntityNameDB -> !ConstraintNameHS -> !ConstraintNameDB -> !FieldCascade -> ![(ForeignFieldDef, ForeignFieldDef)] -> ![Attr] -> Bool -> Bool -> ForeignDef
[foreignRefTableHaskell] :: ForeignDef -> !EntityNameHS
[foreignRefTableDBName] :: ForeignDef -> !EntityNameDB
[foreignConstraintNameHaskell] :: ForeignDef -> !ConstraintNameHS
[foreignConstraintNameDBName] :: ForeignDef -> !ConstraintNameDB

-- | Determine how the field will cascade on updates and deletions.
[foreignFieldCascade] :: ForeignDef -> !FieldCascade
[foreignFields] :: ForeignDef -> ![(ForeignFieldDef, ForeignFieldDef)]
[foreignAttrs] :: ForeignDef -> ![Attr]
[foreignNullable] :: ForeignDef -> Bool

-- | Determines if the reference is towards a Primary Key or not.
[foreignToPrimary] :: ForeignDef -> Bool

-- | Used instead of FieldDef to generate a smaller amount of code
type ForeignFieldDef = (FieldNameHS, FieldNameDB)
data CompositeDef
CompositeDef :: !NonEmpty FieldDef -> ![Attr] -> CompositeDef
[compositeFields] :: CompositeDef -> !NonEmpty FieldDef
[compositeAttrs] :: CompositeDef -> ![Attr]

-- | Type for storing the Uniqueness constraint in the Schema. Assume you
--   have the following schema with a uniqueness constraint:
--   
--   <pre>
--   Person
--     name String
--     age Int
--     UniqueAge age
--   </pre>
--   
--   This will be represented as:
--   
--   <pre>
--   UniqueDef
--       { uniqueHaskell = ConstraintNameHS (packPTH <a>UniqueAge</a>)
--       , uniqueDBName = ConstraintNameDB (packPTH "unique_age")
--       , uniqueFields = [(FieldNameHS (packPTH "age"), FieldNameDB (packPTH "age"))]
--       , uniqueAttrs = []
--       }
--   </pre>
data UniqueDef
UniqueDef :: !ConstraintNameHS -> !ConstraintNameDB -> !NonEmpty (FieldNameHS, FieldNameDB) -> ![Attr] -> UniqueDef
[uniqueHaskell] :: UniqueDef -> !ConstraintNameHS
[uniqueDBName] :: UniqueDef -> !ConstraintNameDB
[uniqueFields] :: UniqueDef -> !NonEmpty (FieldNameHS, FieldNameDB)
[uniqueAttrs] :: UniqueDef -> ![Attr]

-- | An EmbedFieldDef is the same as a FieldDef But it is only used for
--   embeddedFields so it only has data needed for embedding
data EmbedFieldDef
EmbedFieldDef :: FieldNameDB -> Maybe (Either SelfEmbed EntityNameHS) -> EmbedFieldDef
[emFieldDB] :: EmbedFieldDef -> FieldNameDB
[emFieldEmbed] :: EmbedFieldDef -> Maybe (Either SelfEmbed EntityNameHS)

-- | An EmbedEntityDef is the same as an EntityDef But it is only used for
--   fieldReference so it only has data needed for embedding
data EmbedEntityDef
EmbedEntityDef :: EntityNameHS -> [EmbedFieldDef] -> EmbedEntityDef
[embeddedHaskell] :: EmbedEntityDef -> EntityNameHS
[embeddedFields] :: EmbedEntityDef -> [EmbedFieldDef]

-- | There are 3 kinds of references 1) composite (to fields that exist in
--   the record) 2) single field 3) embedded
data ReferenceDef
NoReference :: ReferenceDef

-- | A 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
ForeignRef :: !EntityNameHS -> ReferenceDef
EmbedRef :: EntityNameHS -> ReferenceDef

-- | A SelfReference stops an immediate cycle which causes non-termination
--   at compile-time (issue #311).
SelfReference :: ReferenceDef

-- | A <a>FieldType</a> describes a field parsed from the QuasiQuoter and
--   is used to determine the Haskell type in the generated code.
--   
--   <tt>name Text</tt> parses into <tt>FTTypeCon Nothing <a>Text</a></tt>
--   
--   <tt>name T.Text</tt> parses into <tt>FTTypeCon (Just <a>T</a>
--   <a>Text</a>)</tt>
--   
--   <tt>name (Jsonb User)</tt> parses into:
--   
--   <pre>
--   FTApp (FTTypeCon Nothing <a>Jsonb</a>) (FTTypeCon Nothing <a>User</a>)
--   </pre>
data FieldType

-- | Optional module and name.
FTTypeCon :: Maybe Text -> Text -> FieldType
FTLit :: FieldTypeLit -> FieldType
FTTypePromoted :: Text -> FieldType
FTApp :: FieldType -> FieldType -> FieldType
FTList :: FieldType -> FieldType

-- | 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 <a>FieldAttr</a> is extensible through its constructor
--   <a>FieldAttrOther</a>.
data FieldAttr

-- | The <a>Maybe</a> keyword goes after the type. This indicates that the
--   column is nullable, and the generated Haskell code will have a
--   <tt><a>Maybe</a></tt> type for it.
--   
--   Example:
--   
--   <pre>
--   User
--       name Text Maybe
--   </pre>
FieldAttrMaybe :: FieldAttr

-- | This indicates that the column is nullable, but should not have a
--   <a>Maybe</a> type. For this to work out, you need to ensure that the
--   <tt>PersistField</tt> instance for the type in question can support a
--   <a>PersistNull</a> value.
--   
--   <pre>
--   data What = NoWhat | Hello Text
--   
--   instance PersistField What where
--       fromPersistValue PersistNull =
--           pure NoWhat
--       fromPersistValue pv =
--           Hello <a>$</a> fromPersistValue pv
--   
--   instance PersistFieldSql What where
--       sqlType _ = SqlString
--   
--   User
--       what What nullable
--   </pre>
FieldAttrNullable :: FieldAttr

-- | This 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.
--   
--   <pre>
--   User
--       oldName Text MigrationOnly
--       newName Text
--   </pre>
FieldAttrMigrationOnly :: FieldAttr

-- | A <tt>SafeToRemove</tt> attribute is not present on the Haskell
--   datatype, and the backend migrations should attempt to drop the column
--   without triggering any unsafe migration warnings.
--   
--   Useful after you've used <tt>MigrationOnly</tt> to remove a column
--   from the database in phases.
--   
--   <pre>
--   User
--       oldName Text SafeToRemove
--       newName Text
--   </pre>
FieldAttrSafeToRemove :: FieldAttr

-- | This attribute indicates that we should not create a foreign key
--   reference from a column. By default, <tt>persistent</tt> will try and
--   create a foreign key reference for a column if it can determine that
--   the type of the column is a <tt><tt>Key</tt> entity</tt> or an
--   <tt>EntityId</tt> and the <tt>Entity</tt>'s name was present in
--   <tt>mkPersist</tt>.
--   
--   This is useful if you want to use the explicit foreign key syntax.
--   
--   <pre>
--   Post
--       title    Text
--   
--   Comment
--       postId   PostId      noreference
--       Foreign Post fk_comment_post postId
--   </pre>
FieldAttrNoreference :: FieldAttr

-- | This is set to specify precisely the database table the column refers
--   to.
--   
--   <pre>
--   Post
--       title    Text
--   
--   Comment
--       postId   PostId references="post"
--   </pre>
--   
--   You should not need this - <tt>persistent</tt> should be capable of
--   correctly determining the target table's name. If you do need this,
--   please file an issue describing why.
FieldAttrReference :: Text -> FieldAttr

-- | Specify a name for the constraint on the foreign key reference for
--   this table.
--   
--   <pre>
--   Post
--       title    Text
--   
--   Comment
--       postId   PostId constraint="my_cool_constraint_name"
--   </pre>
FieldAttrConstraint :: Text -> FieldAttr

-- | Specify the default value for a column.
--   
--   <pre>
--   User
--       createdAt    UTCTime     default="NOW()"
--   </pre>
--   
--   Note that a <tt>default=</tt> attribute does not mean you can omit the
--   value while inserting.
FieldAttrDefault :: Text -> FieldAttr

-- | Specify a custom SQL type for the column. Generally, you should define
--   a custom datatype with a custom <tt>PersistFieldSql</tt> instance
--   instead of using this.
--   
--   <pre>
--   User
--       uuid     Text    sqltype=<a>UUID</a>
--   </pre>
FieldAttrSqltype :: Text -> FieldAttr

-- | Set a maximum length for a column. Useful for VARCHAR and indexes.
--   
--   <pre>
--   User
--       name     Text    maxlen=200
--   
--       UniqueName name
--   </pre>
FieldAttrMaxlen :: Integer -> FieldAttr

-- | Specify the database name of the column.
--   
--   <pre>
--   User
--       blarghle     Int     sql="b_l_a_r_g_h_l_e"
--   </pre>
--   
--   Useful for performing phased migrations, where one column is renamed
--   to another column over time.
FieldAttrSql :: Text -> FieldAttr

-- | A grab bag of random attributes that were unrecognized by the parser.
FieldAttrOther :: Text -> FieldAttr
type Attr = Text
type ExtraLine = [Text]

-- | The definition for the entity's primary key ID.
data EntityIdDef

-- | The entity has a single key column, and it is a surrogate key - that
--   is, you can't go from <tt>rec -&gt; Key rec</tt>.
EntityIdField :: !FieldDef -> EntityIdDef

-- | The entity has a natural key. This means you can write <tt>rec -&gt;
--   Key rec</tt> because all the key fields are present on the datatype.
--   
--   A natural key can have one or more columns.
EntityIdNaturalKey :: !CompositeDef -> EntityIdDef

-- | An <a>EntityDef</a> represents the information that
--   <tt>persistent</tt> knows about an Entity. It uses this information to
--   generate the Haskell datatype, the SQL migrations, and other relevant
--   conversions.
data EntityDef

-- | The reason why a field is <tt>nullable</tt> is very important. A field
--   that is nullable because of a <tt>Maybe</tt> tag will have its type
--   changed from <tt>A</tt> to <tt>Maybe A</tt>. OTOH, a field that is
--   nullable because of a <tt>nullable</tt> tag will remain with the same
--   type.
data WhyNullable
ByMaybeAttr :: WhyNullable
ByNullableAttr :: WhyNullable
data IsNullable
Nullable :: !WhyNullable -> IsNullable
NotNullable :: IsNullable

-- | A <a>Checkmark</a> 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.
--   
--   <i>NOTE:</i> You need to mark any <tt>Checkmark</tt> fields as
--   <tt>nullable</tt> (see the following example).
--   
--   For example, suppose there's a <tt>Location</tt> entity that
--   represents where a user has lived:
--   
--   <pre>
--   Location
--       user    UserId
--       name    Text
--       current Checkmark nullable
--   
--       UniqueLocation user current
--   </pre>
--   
--   The <tt>UniqueLocation</tt> constraint allows any number of
--   <a>Inactive</a> <tt>Location</tt>s to be <tt>current</tt>. However,
--   there may be at most one <tt>current</tt> <tt>Location</tt> per user
--   (i.e., either zero or one per user).
--   
--   This data type works because of the way that SQL treats
--   <tt>NULL</tt>able fields within uniqueness constraints. The SQL
--   standard says that <tt>NULL</tt> values should be considered
--   different, so we represent <a>Inactive</a> as SQL <tt>NULL</tt>, thus
--   allowing any number of <a>Inactive</a> records. On the other hand, we
--   represent <a>Active</a> as <tt>TRUE</tt>, so the uniqueness constraint
--   will disallow more than one <a>Active</a> record.
--   
--   <i>Note:</i> There may be DBMSs that do not respect the SQL standard's
--   treatment of <tt>NULL</tt> values on uniqueness constraints, please
--   check if this data type works before relying on it.
--   
--   The SQL <tt>BOOLEAN</tt> type is used because it's the smallest data
--   type available. Note that we never use <tt>FALSE</tt>, just
--   <tt>TRUE</tt> and <tt>NULL</tt>. Provides the same behavior <tt>Maybe
--   ()</tt> would if <tt>()</tt> was a valid <tt>PersistField</tt>.
data Checkmark

-- | When used on a uniqueness constraint, there may be at most one
--   <a>Active</a> record.
Active :: Checkmark

-- | When used on a uniqueness constraint, there may be any number of
--   <a>Inactive</a> records.
Inactive :: Checkmark
fieldAttrsContainsNullable :: [FieldAttr] -> IsNullable

-- | Return the <tt>[<a>FieldDef</a>]</tt> for the entity keys.
entitiesPrimary :: EntityDef -> NonEmpty FieldDef
entityPrimary :: EntityDef -> Maybe CompositeDef

-- | Returns a <a>NonEmpty</a> list of <a>FieldDef</a> that correspond with
--   the key columns for an <a>EntityDef</a>.
keyAndEntityFields :: EntityDef -> NonEmpty FieldDef

-- | Returns a <a>NonEmpty</a> list of <a>FieldDef</a> that correspond with
--   the key columns for an <a>EntityDef</a> including those fields that
--   are marked as <tt>MigrationOnly</tt> (and therefore only present in
--   the database) or <tt>SafeToRemove</tt> (and a migration will drop the
--   column if it exists in the database).
--   
--   For fields on the Haskell type use <a>keyAndEntityFieldsDatabase</a>
keyAndEntityFieldsDatabase :: EntityDef -> NonEmpty FieldDef

-- | Parse raw field attributes into structured form. Any unrecognized
--   attributes will be preserved, identically as they are encountered, as
--   <a>FieldAttrOther</a> values.
parseFieldAttrs :: [Text] -> [FieldAttr]
isFieldNotGenerated :: FieldDef -> Bool

-- | Returns <a>True</a> if the <a>FieldDef</a> does not have a
--   <tt>MigrationOnly</tt> or <tt>SafeToRemove</tt> flag from the
--   QuasiQuoter.
isHaskellField :: FieldDef -> Bool

-- | A <a>FieldCascade</a> that does nothing.
noCascade :: FieldCascade

-- | Renders a <a>FieldCascade</a> value such that it can be used in SQL
--   migrations.
renderFieldCascade :: FieldCascade -> Text

-- | Render a <a>CascadeAction</a> to <a>Text</a> such that it can be used
--   in a SQL command.
renderCascadeAction :: CascadeAction -> Text

-- | A <a>Statement</a> is a representation of a database query that has
--   been prepared and stored on the server side.
data Statement
Statement :: IO () -> IO () -> ([PersistValue] -> IO Int64) -> (forall (m :: Type -> Type). MonadIO m => [PersistValue] -> Acquire (ConduitM () [PersistValue] m ())) -> Statement
[stmtFinalize] :: Statement -> IO ()
[stmtReset] :: Statement -> IO ()
[stmtExecute] :: Statement -> [PersistValue] -> IO Int64
[stmtQuery] :: Statement -> forall (m :: Type -> Type). MonadIO m => [PersistValue] -> Acquire (ConduitM () [PersistValue] m ())
data InsertSqlResult
ISRSingle :: Text -> InsertSqlResult
ISRInsertGet :: Text -> Text -> InsertSqlResult
ISRManyKeys :: Text -> [PersistValue] -> InsertSqlResult
type LogFunc = Loc -> LogSource -> LogLevel -> LogStr -> IO ()

-- | Replace the <a>FieldDef</a> <a>FieldAttr</a> with the new list.
setFieldAttrs :: [FieldAttr] -> FieldDef -> FieldDef

-- | Modify the list of field attributes.
overFieldAttrs :: ([FieldAttr] -> [FieldAttr]) -> FieldDef -> FieldDef

-- | Add an attribute to the list of field attributes.
addFieldAttr :: FieldAttr -> FieldDef -> FieldDef

-- | Check if the field definition is nullable
isFieldNullable :: FieldDef -> IsNullable

-- | Check if the field is `Maybe a`
isFieldMaybe :: FieldDef -> Bool

-- | Retrieve the list of <a>UniqueDef</a> from an <a>EntityDef</a>. This
--   does not include a <tt>Primary</tt> key, if one is defined. A future
--   version of <tt>persistent</tt> will include a <tt>Primary</tt> key
--   among the <tt>Unique</tt> constructors for the <tt>Entity</tt>.
getEntityUniquesNoPrimaryKey :: EntityDef -> [UniqueDef]

-- | Retrieve the list of <a>UniqueDef</a> from an <a>EntityDef</a>. 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
--   <a>getEntityUniquesNoPrimaryKey</a>.
getEntityUniques :: EntityDef -> [UniqueDef]

-- | Retrieve the Haskell name of the given entity.
getEntityHaskellName :: EntityDef -> EntityNameHS

-- | Return the database name for the given entity.
getEntityDBName :: EntityDef -> EntityNameDB
getEntityExtra :: EntityDef -> Map Text [[Text]]

setEntityDBName :: EntityNameDB -> EntityDef -> EntityDef
getEntityComments :: EntityDef -> Maybe Text

getEntityForeignDefs :: EntityDef -> [ForeignDef]

-- | Retrieve the list of <a>FieldDef</a> that makes up the fields of the
--   entity.
--   
--   This does not return the fields for an <tt>Id</tt> column or an
--   implicit <tt>id</tt>. It will return the key columns if you used the
--   <tt>Primary</tt> syntax for defining the primary key.
--   
--   This does not return fields that are marked <tt>SafeToRemove</tt> or
--   <tt>MigrationOnly</tt> - so it only returns fields that are
--   represented in the Haskell type. If you need those fields, use
--   <a>getEntityFieldsDatabase</a>.
getEntityFields :: EntityDef -> [FieldDef]

-- | This returns all of the <a>FieldDef</a> defined for the
--   <a>EntityDef</a>, including those fields that are marked as
--   <tt>MigrationOnly</tt> (and therefore only present in the database) or
--   <tt>SafeToRemove</tt> (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
--   <a>getEntityFields</a>.
getEntityFieldsDatabase :: EntityDef -> [FieldDef]

isEntitySum :: EntityDef -> Bool

getEntityId :: EntityDef -> EntityIdDef

getEntityIdField :: EntityDef -> Maybe FieldDef

-- | Set an <a>entityId</a> to be the given <a>FieldDef</a>.
setEntityId :: FieldDef -> EntityDef -> EntityDef

setEntityIdDef :: EntityIdDef -> EntityDef -> EntityDef

getEntityKeyFields :: EntityDef -> NonEmpty FieldDef

-- | Perform a mapping function over all of the entity fields, as
--   determined by <a>getEntityFieldsDatabase</a>.
overEntityFields :: ([FieldDef] -> [FieldDef]) -> EntityDef -> EntityDef

-- | Gets the <tt>Source</tt> of the definition of the entity.
--   
--   Note that as of this writing the span covers the entire file or
--   quasiquote where the item is defined due to parsing limitations. This
--   may be changed in a future release to be more accurate.
getEntitySpan :: EntityDef -> Maybe SourceSpan

-- | Prior to <tt>persistent-2.11.0</tt>, we provided an instance of
--   <a>PersistField</a> for the <a>Natural</a> type. This was in error,
--   because <a>Natural</a> represents an infinite value, and databases
--   don't have reasonable types for this.
--   
--   The instance for <a>Natural</a> used the <a>Int64</a> 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 <a>Word</a> series of types
--   from <a>Data.Word</a>. These have a bounded size, are guaranteed to be
--   non-negative, and are quite efficient for the database to store.
newtype OverflowNatural
OverflowNatural :: Natural -> OverflowNatural
[unOverflowNatural] :: OverflowNatural -> Natural

-- | This class teaches Persistent how to take a custom type and marshal it
--   to and from a <a>PersistValue</a>, allowing it to be stored in a
--   database.
--   
--   <h4><b>Examples</b></h4>
--   
--   <h5>Simple Newtype</h5>
--   
--   You can use <tt>newtype</tt> to add more type safety/readability to a
--   basis type like <a>ByteString</a>. In these cases, just derive
--   <a>PersistField</a> and <tt>PersistFieldSql</tt>:
--   
--   <pre>
--   {-# LANGUAGE GeneralizedNewtypeDeriving #-}
--   
--   newtype HashedPassword = HashedPassword <a>ByteString</a>
--     deriving (Eq, Show, <a>PersistField</a>, PersistFieldSql)
--   </pre>
--   
--   <h5>Smart Constructor Newtype</h5>
--   
--   In this example, we create a <a>PersistField</a> instance for a
--   newtype following the "Smart Constructor" pattern.
--   
--   <pre>
--   {-# LANGUAGE GeneralizedNewtypeDeriving #-}
--   import qualified <a>Data.Text</a> as T
--   import qualified <a>Data.Char</a> as C
--   
--   -- | An American Social Security Number
--   newtype SSN = SSN <a>Text</a>
--    deriving (Eq, Show, PersistFieldSql)
--   
--   mkSSN :: <a>Text</a> -&gt; <a>Either</a> <a>Text</a> SSN
--   mkSSN t = if (T.length t == 9) &amp;&amp; (T.all C.isDigit t)
--    then <a>Right</a> $ SSN t
--    else <a>Left</a> $ "Invalid SSN: " &lt;&gt; t
--   
--   instance <a>PersistField</a> SSN where
--     <a>toPersistValue</a> (SSN t) = <a>PersistText</a> t
--     <a>fromPersistValue</a> (<a>PersistText</a> t) = mkSSN t
--     -- Handle cases where the database does not give us PersistText
--     <a>fromPersistValue</a> x = <a>Left</a> $ "File.hs: When trying to deserialize an SSN: expected PersistText, received: " &lt;&gt; T.pack (show x)
--   </pre>
--   
--   Tips:
--   
--   <ul>
--   <li>This file contain dozens of <a>PersistField</a> instances you can
--   look at for examples.</li>
--   <li>Typically custom <a>PersistField</a> instances will only accept a
--   single <a>PersistValue</a> constructor in
--   <a>fromPersistValue</a>.</li>
--   <li>Internal <a>PersistField</a> instances accept a wide variety of
--   <a>PersistValue</a>s to accomodate e.g. storing booleans as integers,
--   booleans or strings.</li>
--   <li>If you're making a custom instance and using a SQL database,
--   you'll also need <tt>PersistFieldSql</tt> to specify the type of the
--   database column.</li>
--   </ul>
class PersistField a
toPersistValue :: PersistField a => a -> PersistValue
fromPersistValue :: PersistField a => PersistValue -> Either Text a

-- | A type class which is used to witness that a type is safe to insert
--   into the database without providing a primary key.
--   
--   The <tt>TemplateHaskell</tt> function <tt>mkPersist</tt> 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 <tt>Primary</tt> natural key, then this works fine. But
--   if the entity has an <tt>Id</tt> column with no <tt>default=</tt>,
--   then this does a <a>TypeError</a> and forces the user to use
--   <tt>insertKey</tt>.
class SafeToInsert a

-- | This type class is used with the <tt>OverloadedLabels</tt> extension
--   to provide a more convenient means of using the <a>EntityField</a>
--   type. <a>EntityField</a> definitions are prefixed with the type name
--   to avoid ambiguity, but this ambiguity can result in verbose code.
--   
--   If you have a table <tt>User</tt> with a <tt>name Text</tt> field,
--   then the corresponding <a>EntityField</a> is <tt>UserName</tt>. With
--   this, we can write <tt>#name :: <a>EntityField</a> User Text</tt>.
--   
--   What's more fun is that the type is more general: it's actually <tt>
--   #name :: (<a>SymbolToField</a> "name" rec typ) =&gt; EntityField rec
--   typ </tt>
--   
--   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.
class SymbolToField (sym :: Symbol) rec typ | sym rec -> typ
symbolToField :: SymbolToField sym rec typ => EntityField rec typ

-- | Datatype that represents an entity, with both its <a>Key</a> and its
--   Haskell record representation.
--   
--   When using a SQL-based backend (such as SQLite or PostgreSQL), an
--   <a>Entity</a> may take any number of columns depending on how many
--   fields it has. In order to reconstruct your entity on the Haskell
--   side, <tt>persistent</tt> needs all of your entity columns and in the
--   right order. Note that you don't need to worry about this when using
--   <tt>persistent</tt>'s API since everything is handled correctly behind
--   the scenes.
--   
--   However, if you want to issue a raw SQL command that returns an
--   <a>Entity</a>, then you have to be careful with the column order.
--   While you could use <tt>SELECT Entity.* WHERE ...</tt> 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 <tt>persistent</tt>
--   expects (for example, if you add a new field in the middle of you
--   entity definition and then use the migration code --
--   <tt>persistent</tt> 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 <a>rawSql</a> (from the
--   <a>Database.Persist.Sql</a> module) with its /entity selection
--   placeholder/ (a double question mark <tt>??</tt>). Using
--   <tt>rawSql</tt> the query above must be written as <tt>SELECT ?? WHERE
--   ..</tt>. Then <tt>rawSql</tt> will replace <tt>??</tt> with the list
--   of all columns that we need from your entity in the right order. If
--   your query returns two entities (i.e. <tt>(Entity backend a, Entity
--   backend b)</tt>), then you must you use <tt>SELECT ??, ?? WHERE
--   ...</tt>, and so on.
data Entity record
Entity :: Key record -> record -> Entity record
[entityKey] :: Entity record -> Key record
[entityVal] :: Entity record -> record

-- | Value to filter with. Highly dependant on the type of filter used.
data FilterValue typ
[FilterValue] :: forall typ. typ -> FilterValue typ
[FilterValues] :: forall typ. [typ] -> FilterValue typ
[UnsafeValue] :: forall a typ. PersistField a => a -> FilterValue typ

-- | Persistent allows multiple different backends (databases).
type family PersistEntityBackend record

-- | An <a>EntityField</a> is parameterised by the Haskell record it
--   belongs to and the additional type of that field.
--   
--   As of <tt>persistent-2.11.0.0</tt>, it's possible to use the
--   <tt>OverloadedLabels</tt> language extension to refer to
--   <a>EntityField</a> values polymorphically. See the documentation on
--   <a>SymbolToField</a> for more information.
data family EntityField record :: Type -> Type

-- | Construct an <tt><a>Entity</a> record</tt> by providing a value for
--   each of the record's fields.
--   
--   These constructions are equivalent:
--   
--   <pre>
--   entityMattConstructor, entityMattTabulate :: Entity User
--   entityMattConstructor =
--       Entity
--           { entityKey = toSqlKey 123
--           , entityVal =
--               User
--                   { userName = <a>Matt</a>
--                   , userAge = 33
--                   }
--           }
--   
--   entityMattTabulate =
--       tabulateEntity $ \case
--           UserId -&gt;
--               toSqlKey 123
--           UserName -&gt;
--               <a>Matt</a>
--           UserAge -&gt;
--               33
--   </pre>
--   
--   This is a specialization of <a>tabulateEntityA</a>, which allows you
--   to construct an <a>Entity</a> by providing an <a>Applicative</a>
--   action for each field instead of a regular function.
tabulateEntity :: PersistEntity record => (forall a. () => EntityField record a -> a) -> Entity record

-- | Get list of values corresponding to given entity.
entityValues :: PersistEntity record => Entity record -> [PersistValue]

-- | Predefined <tt>toJSON</tt>. The resulting JSON looks like <tt>{"key":
--   1, "value": {"name": ...}}</tt>.
--   
--   The typical usage is:
--   
--   <pre>
--   instance ToJSON (Entity User) where
--       toJSON = keyValueEntityToJSON
--   </pre>
keyValueEntityToJSON :: (PersistEntity record, ToJSON record) => Entity record -> Value

-- | Predefined <tt>parseJSON</tt>. The input JSON looks like <tt>{"key":
--   1, "value": {"name": ...}}</tt>.
--   
--   The typical usage is:
--   
--   <pre>
--   instance FromJSON (Entity User) where
--       parseJSON = keyValueEntityFromJSON
--   </pre>
keyValueEntityFromJSON :: (PersistEntity record, FromJSON record) => Value -> Parser (Entity record)

-- | Predefined <tt>toJSON</tt>. The resulting JSON looks like <tt>{"id":
--   1, "name": ...}</tt>.
--   
--   The typical usage is:
--   
--   <pre>
--   instance ToJSON (Entity User) where
--       toJSON = entityIdToJSON
--   </pre>
entityIdToJSON :: (PersistEntity record, ToJSON record) => Entity record -> Value

-- | Predefined <tt>parseJSON</tt>. The input JSON looks like <tt>{"id": 1,
--   "name": ...}</tt>.
--   
--   The typical usage is:
--   
--   <pre>
--   instance FromJSON (Entity User) where
--       parseJSON = entityIdFromJSON
--   </pre>
entityIdFromJSON :: (PersistEntity record, FromJSON record) => Value -> Parser (Entity record)

-- | Convenience function for getting a free <a>PersistField</a> instance
--   from a type with JSON instances.
--   
--   Example usage in combination with <a>fromPersistValueJSON</a>:
--   
--   <pre>
--   instance PersistField MyData where
--     fromPersistValue = fromPersistValueJSON
--     toPersistValue = toPersistValueJSON
--   </pre>
toPersistValueJSON :: ToJSON a => a -> PersistValue

-- | Convenience function for getting a free <a>PersistField</a> 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 <a>toPersistValueJSON</a>:
--   
--   <pre>
--   instance PersistField MyData where
--     fromPersistValue = fromPersistValueJSON
--     toPersistValue = toPersistValueJSON
--   </pre>
fromPersistValueJSON :: FromJSON a => PersistValue -> Either Text a
class PersistCore backend where {
    data BackendKey backend;
}
data family BackendKey backend

-- | <a>ToBackendKey</a> converts a <a>PersistEntity</a> <a>Key</a> into a
--   <a>BackendKey</a> This can be used by each backend to convert between
--   a <a>Key</a> and a plain Haskell type. For Sql, that is done with
--   <tt>toSqlKey</tt> and <tt>fromSqlKey</tt>.
--   
--   By default, a <a>PersistEntity</a> uses the default <a>BackendKey</a>
--   for its Key and is an instance of ToBackendKey
--   
--   A <a>Key</a> that instead uses a custom type will not be an instance
--   of <a>ToBackendKey</a>.
class (PersistEntity record, PersistEntityBackend record ~ backend, PersistCore backend) => ToBackendKey backend record
toBackendKey :: ToBackendKey backend record => Key record -> BackendKey backend
fromBackendKey :: ToBackendKey backend record => BackendKey backend -> Key record

-- | A convenient alias for common type signatures
type PersistRecordBackend record backend = (PersistEntity record, PersistEntityBackend record ~ BaseBackend backend)

-- | This class witnesses that two backend are compatible, and that you can
--   convert from the <tt>sub</tt> backend into the <tt>sup</tt> backend.
--   This is similar to the <a>HasPersistBackend</a> and
--   <a>IsPersistBackend</a> classes, but where you don't want to fix the
--   type associated with the <a>PersistEntityBackend</a> of a record.
--   
--   Generally speaking, where you might have:
--   
--   <pre>
--   foo ::
--     ( <a>PersistEntity</a> record
--     , <a>PersistEntityBackend</a> record ~ <a>BaseBackend</a> backend
--     , <tt>IsSqlBackend</tt> backend
--     )
--   </pre>
--   
--   this can be replaced with:
--   
--   <pre>
--   foo ::
--     ( <a>PersistEntity</a> record,
--     , <a>PersistEntityBackend</a> record ~ backend
--     , <a>BackendCompatible</a> <tt>SqlBackend</tt> backend
--     )
--   </pre>
--   
--   This works for <tt>SqlReadBackend</tt> because of the <tt>instance
--   <a>BackendCompatible</a> <tt>SqlBackend</tt>
--   <tt>SqlReadBackend</tt></tt>, without needing to go through the
--   <a>BaseBackend</a> type family.
--   
--   Likewise, functions that are currently hardcoded to use
--   <tt>SqlBackend</tt> can be generalized:
--   
--   <pre>
--   -- before:
--   asdf :: <a>ReaderT</a> <tt>SqlBackend</tt> m ()
--   asdf = pure ()
--   
--   -- after:
--   asdf' :: <a>BackendCompatible</a> SqlBackend backend =&gt; ReaderT backend m ()
--   asdf' = <a>withCompatibleBackend</a> asdf
--   </pre>
class BackendCompatible sup sub
projectBackend :: BackendCompatible sup sub => sub -> sup

-- | Class which witnesses that <tt>backend</tt> is essentially the same as
--   <tt>BaseBackend backend</tt>. That is, they're isomorphic and
--   <tt>backend</tt> is just some wrapper over <tt>BaseBackend
--   backend</tt>.
class HasPersistBackend backend => IsPersistBackend backend

-- | Class which allows the plucking of a <tt>BaseBackend backend</tt> from
--   some larger type. For example, <tt> instance HasPersistBackend
--   (SqlReadBackend, Int) where type BaseBackend (SqlReadBackend, Int) =
--   SqlBackend persistBackend = unSqlReadBackend . fst </tt>
class HasPersistBackend backend where {
    type BaseBackend backend;
}
persistBackend :: HasPersistBackend backend => backend -> BaseBackend backend
type family BaseBackend backend

-- | Run a query against a larger backend by plucking out <tt>BaseBackend
--   backend</tt>
--   
--   This is a helper for reusing existing queries when expanding the
--   backend type.
withBaseBackend :: forall backend (m :: Type -> Type) a. HasPersistBackend backend => ReaderT (BaseBackend backend) m a -> ReaderT backend m a

-- | Run a query against a compatible backend, by projecting the backend
--   
--   This is a helper for using queries which run against a specific
--   backend type that your backend is compatible with.
withCompatibleBackend :: forall sup sub (m :: Type -> Type) a. BackendCompatible sup sub => ReaderT sup m a -> ReaderT sub m a
liftPersist :: (MonadIO m, MonadReader backend m) => ReaderT backend IO b -> m b

-- | Same as <a>get</a>, but for a non-null (not Maybe) foreign key. Unsafe
--   unless your database is enforcing that the foreign key is valid.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>,
--   
--   <pre>
--   getJustSpj :: MonadIO m =&gt; ReaderT SqlBackend m User
--   getJustSpj = getJust spjId
--   </pre>
--   
--   <pre>
--   spj &lt;- getJust spjId
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will get this
--   record:
--   
--   <pre>
--   +----+------+-----+
--   | id | name | age |
--   +----+------+-----+
--   |  1 | SPJ  |  40 |
--   +----+------+-----+
--   </pre>
--   
--   <pre>
--   getJustUnknown :: MonadIO m =&gt; ReaderT SqlBackend m User
--   getJustUnknown = getJust unknownId
--   </pre>
--   
--   mrx &lt;- getJustUnknown
--   
--   This just throws an error.
getJust :: forall record backend (m :: Type -> Type). (PersistStoreRead backend, PersistRecordBackend record backend, MonadIO m) => Key record -> ReaderT backend m record

-- | Same as <a>getJust</a>, but returns an <a>Entity</a> instead of just
--   the record.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>,
--   
--   <pre>
--   getJustEntitySpj :: MonadIO m =&gt; ReaderT SqlBackend m (Entity User)
--   getJustEntitySpj = getJustEntity spjId
--   </pre>
--   
--   <pre>
--   spjEnt &lt;- getJustEntitySpj
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will get this
--   entity:
--   
--   <pre>
--   +----+------+-----+
--   | id | name | age |
--   +----+------+-----+
--   |  1 | SPJ  |  40 |
--   +----+------+-----+
--   </pre>
getJustEntity :: forall record backend (m :: Type -> Type). (PersistEntityBackend record ~ BaseBackend backend, MonadIO m, PersistEntity record, PersistStoreRead backend) => Key record -> ReaderT backend m (Entity record)

-- | Curry this to make a convenience function that loads an associated
--   model.
--   
--   <pre>
--   foreign = belongsTo foreignId
--   </pre>
belongsTo :: forall ent1 ent2 backend (m :: Type -> Type). (PersistStoreRead backend, PersistEntity ent1, PersistRecordBackend ent2 backend, MonadIO m) => (ent1 -> Maybe (Key ent2)) -> ent1 -> ReaderT backend m (Maybe ent2)

-- | Same as <a>belongsTo</a>, but uses <tt>getJust</tt> and therefore is
--   similarly unsafe.
belongsToJust :: forall ent1 ent2 backend (m :: Type -> Type). (PersistStoreRead backend, PersistEntity ent1, PersistRecordBackend ent2 backend, MonadIO m) => (ent1 -> Key ent2) -> ent1 -> ReaderT backend m ent2

-- | Like <tt>insert</tt>, but returns the complete <tt>Entity</tt>.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>,
--   
--   <pre>
--   insertHaskellEntity :: MonadIO m =&gt; ReaderT SqlBackend m (Entity User)
--   insertHaskellEntity = insertEntity $ User "Haskell" 81
--   </pre>
--   
--   <pre>
--   haskellEnt &lt;- insertHaskellEntity
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will produce this:
--   
--   <pre>
--   +----+---------+-----+
--   | id |  name   | age |
--   +----+---------+-----+
--   |  1 | SPJ     |  40 |
--   +----+---------+-----+
--   |  2 | Simon   |  41 |
--   +----+---------+-----+
--   |  3 | Haskell |  81 |
--   +----+---------+-----+
--   </pre>
insertEntity :: forall e backend (m :: Type -> Type). (PersistStoreWrite backend, PersistRecordBackend e backend, SafeToInsert e, MonadIO m, HasCallStack) => e -> ReaderT backend m (Entity e)

-- | Like <tt>get</tt>, but returns the complete <tt>Entity</tt>.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>,
--   
--   <pre>
--   getSpjEntity :: MonadIO m =&gt; ReaderT SqlBackend m (Maybe (Entity User))
--   getSpjEntity = getEntity spjId
--   </pre>
--   
--   <pre>
--   mSpjEnt &lt;- getSpjEntity
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will get this
--   entity:
--   
--   <pre>
--   +----+------+-----+
--   | id | name | age |
--   +----+------+-----+
--   |  1 | SPJ  |  40 |
--   +----+------+-----+
--   </pre>
getEntity :: forall e backend (m :: Type -> Type). (PersistStoreRead backend, PersistRecordBackend e backend, MonadIO m) => Key e -> ReaderT backend m (Maybe (Entity e))

-- | Like <a>insertEntity</a> but just returns the record instead of
--   <a>Entity</a>.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>,
--   
--   <pre>
--   insertDaveRecord :: MonadIO m =&gt; ReaderT SqlBackend m User
--   insertDaveRecord = insertRecord $ User "Dave" 50
--   </pre>
--   
--   <pre>
--   dave &lt;- insertDaveRecord
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will produce this:
--   
--   <pre>
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |40   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   |3    |Dave  |50   |
--   +-----+------+-----+
--   </pre>
insertRecord :: forall record backend (m :: Type -> Type). (PersistEntityBackend record ~ BaseBackend backend, PersistEntity record, MonadIO m, PersistStoreWrite backend, SafeToInsert record, HasCallStack) => record -> ReaderT backend m record

-- | A <a>SqlBackend</a> represents a handle or connection to a database.
--   It contains functions and values that allow databases to have more
--   optimized implementations, as well as references that benefit
--   performance and sharing.
--   
--   Instead of using the <a>SqlBackend</a> constructor directly, use the
--   <a>mkSqlBackend</a> function.
--   
--   A <a>SqlBackend</a> is *not* thread-safe. You should not assume that a
--   <a>SqlBackend</a> can be shared among threads and run concurrent
--   queries. This *will* result in problems. Instead, you should create a
--   <tt><tt>Pool</tt> <a>SqlBackend</a></tt>, known as a
--   <tt>ConnectionPool</tt>, and pass that around in multi-threaded
--   applications.
--   
--   To run actions in the <tt>persistent</tt> library, you should use the
--   <tt>runSqlConn</tt> function. If you're using a multithreaded
--   application, use the <tt>runSqlPool</tt> function.
data SqlBackend

-- | 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 <tt>TypeError</tt> instances for records that
--   have 0 unique keys.
class PersistEntity record => AtLeastOneUniqueKey record
requireUniquesP :: AtLeastOneUniqueKey record => record -> NonEmpty (Unique record)

-- | This is an error message. It is used when an entity has multiple
--   unique keys, and the function expects a single unique key.
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 writing instances of
--   <a>OnlyOneUniqueKey</a> for an entity that has no unique keys.
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 class is used to ensure that <a>upsert</a> is only called on
--   records that have a single <a>Unique</a> key. The quasiquoter
--   automatically generates working instances for appropriate records, and
--   generates <tt>TypeError</tt> instances for records that have 0 or
--   multiple unique keys.
class PersistEntity record => OnlyOneUniqueKey record
onlyUniqueP :: OnlyOneUniqueKey record => record -> Unique record

-- | Queries against <a>Unique</a> keys (other than the id <a>Key</a>).
--   
--   Please read the general Persistent documentation to learn how to
--   create <a>Unique</a> keys.
--   
--   Using this with an Entity without a Unique key leads to undefined
--   behavior. A few of these functions require a <i>single</i>
--   <a>Unique</a>, so using an Entity with multiple <a>Unique</a>s is also
--   undefined. In these cases persistent's goal is to throw an exception
--   as soon as possible, but persistent is still transitioning to that.
--   
--   SQL backends automatically create uniqueness constraints, but for
--   MongoDB you must manually place a unique index on a field to have a
--   uniqueness constraint.
class PersistStoreRead backend => PersistUniqueRead backend

-- | Get a record by unique key, if available. Returns also the identifier.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>:
--   
--   <pre>
--   getBySpjName :: MonadIO m  =&gt; ReaderT SqlBackend m (Maybe (Entity User))
--   getBySpjName = getBy $ UniqueUserName "SPJ"
--   </pre>
--   
--   <pre>
--   mSpjEnt &lt;- getBySpjName
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will get this
--   entity:
--   
--   <pre>
--   +----+------+-----+
--   | id | name | age |
--   +----+------+-----+
--   |  1 | SPJ  |  40 |
--   +----+------+-----+
--   </pre>
getBy :: forall record (m :: Type -> Type). (PersistUniqueRead backend, MonadIO m, PersistRecordBackend record backend) => Unique record -> ReaderT backend m (Maybe (Entity record))

-- | Returns True if a record with this unique key exists, otherwise False.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>:
--   
--   <pre>
--   existsBySpjName :: MonadIO m  =&gt; ReaderT SqlBackend m Bool
--   existsBySpjName = existsBy $ UniqueUserName "SPJ"
--   </pre>
--   
--   <pre>
--   spjEntExists &lt;- existsBySpjName
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will return the
--   value True.
existsBy :: forall record (m :: Type -> Type). (PersistUniqueRead backend, MonadIO m, PersistRecordBackend record backend) => Unique record -> ReaderT backend m Bool

-- | Given a proxy for a <a>PersistEntity</a> record, this returns the sole
--   <a>UniqueDef</a> for that entity.
onlyOneUniqueDef :: (OnlyOneUniqueKey record, Monad proxy) => proxy record -> UniqueDef

-- | Like <a>insertEntity</a>, but returns <a>Nothing</a> when the record
--   couldn't be inserted because of a uniqueness constraint.
--   
--   <h3><b>Example usage</b></h3>
--   
--   We use <a>schema-2</a> and <a>dataset-1</a> here.
--   
--   <pre>
--   insertUniqueSpjEntity :: MonadIO m =&gt; ReaderT SqlBackend m (Maybe (Entity User))
--   insertUniqueSpjEntity = insertUniqueEntity $ User "SPJ" 50
--   </pre>
--   
--   <pre>
--   mSpjEnt &lt;- insertUniqueSpjEntity
--   </pre>
--   
--   The above query results <a>Nothing</a> as SPJ already exists.
--   
--   <pre>
--   insertUniqueAlexaEntity :: MonadIO m =&gt; ReaderT SqlBackend m (Maybe (Entity User))
--   insertUniqueAlexaEntity = insertUniqueEntity $ User "Alexa" 3
--   </pre>
--   
--   <pre>
--   mAlexaEnt &lt;- insertUniqueSpjEntity
--   </pre>
--   
--   Because there's no such unique keywords of the given record, the above
--   query when applied on <a>dataset-1</a>, will produce this:
--   
--   <pre>
--   +----+-------+-----+
--   | id | name  | age |
--   +----+-------+-----+
--   |  1 | SPJ   |  40 |
--   +----+-------+-----+
--   |  2 | Simon |  41 |
--   +----+-------+-----+
--   |  3 | Alexa |   3 |
--   +----+-------+-----+
--   </pre>
insertUniqueEntity :: forall record backend (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend, PersistUniqueWrite backend, SafeToInsert record) => record -> ReaderT backend m (Maybe (Entity record))

-- | Return the single unique key for a record.
--   
--   <h3><b>Example usage</b></h3>
--   
--   We use shcema-1 and <a>dataset-1</a> here.
--   
--   <pre>
--   onlySimonConst :: MonadIO m =&gt; ReaderT SqlBackend m (Unique User)
--   onlySimonConst = onlyUnique $ User "Simon" 999
--   </pre>
--   
--   <pre>
--   mSimonConst &lt;- onlySimonConst
--   </pre>
--   
--   <tt>mSimonConst</tt> would be Simon's uniqueness constraint. Note that
--   <tt>onlyUnique</tt> doesn't work if there're more than two
--   constraints. It will fail with a type error instead.
onlyUnique :: forall record backend (m :: Type -> Type). (MonadIO m, PersistUniqueWrite backend, PersistRecordBackend record backend, OnlyOneUniqueKey record) => record -> ReaderT backend m (Unique record)

-- | A modification of <a>getBy</a>, which takes the <a>PersistEntity</a>
--   itself instead of a <a>Unique</a> record. Returns a record matching
--   <i>one</i> of the unique keys. This function makes the most sense on
--   entities with a single <a>Unique</a> constructor.
--   
--   <h3><b>Example usage</b></h3>
--   
--   With <a>schema-1</a> and <a>dataset-1</a>,
--   
--   getBySpjValue :: MonadIO m =&gt; ReaderT SqlBackend m (Maybe (Entity
--   User)) getBySpjValue = getByValue $ User <a>SPJ</a> 999
--   
--   <pre>
--   mSpjEnt &lt;- getBySpjValue
--   </pre>
--   
--   The above query when applied on <a>dataset-1</a>, will get this
--   record:
--   
--   <pre>
--   +----+------+-----+
--   | id | name | age |
--   +----+------+-----+
--   |  1 | SPJ  |  40 |
--   +----+------+-----+
--   </pre>
getByValue :: forall record (m :: Type -> Type) backend. (MonadIO m, PersistUniqueRead backend, PersistRecordBackend record backend, AtLeastOneUniqueKey record) => record -> ReaderT backend m (Maybe (Entity record))

-- | Attempt to replace the record of the given key with the given new
--   record. First query the unique fields to make sure the replacement
--   maintains uniqueness constraints.
--   
--   Return <a>Nothing</a> if the replacement was made. If uniqueness is
--   violated, return a <a>Just</a> with the <a>Unique</a> violation
replaceUnique :: forall record backend (m :: Type -> Type). (MonadIO m, Eq (Unique record), PersistRecordBackend record backend, PersistUniqueWrite backend) => Key record -> record -> ReaderT backend m (Maybe (Unique record))

-- | Check whether there are any conflicts for unique keys with this entity
--   and existing entities in the database.
--   
--   Returns <a>Nothing</a> if the entity would be unique, and could thus
--   safely be inserted. on a conflict returns the conflicting key
--   
--   <h3><b>Example usage</b></h3>
--   
--   We use <a>schema-1</a> and <a>dataset-1</a> here.
--   
--   This would be <a>Nothing</a>:
--   
--   <pre>
--   mAlanConst &lt;- checkUnique $ User "Alan" 70
--   </pre>
--   
--   While this would be <a>Just</a> because SPJ already exists:
--   
--   <pre>
--   mSpjConst &lt;- checkUnique $ User "SPJ" 60
--   </pre>
checkUnique :: forall record backend (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend, PersistUniqueRead backend) => record -> ReaderT backend m (Maybe (Unique record))

-- | Check whether there are any conflicts for unique keys with this entity
--   and existing entities in the database.
--   
--   Returns <a>Nothing</a> if the entity would stay unique, and could thus
--   safely be updated. on a conflict returns the conflicting key
--   
--   This is similar to <a>checkUnique</a>, except it's useful for updating
--   - when the particular entity already exists, it would normally
--   conflict with itself. This variant ignores those conflicts
--   
--   <h3><b>Example usage</b></h3>
--   
--   We use <a>schema-1</a> and <a>dataset-1</a> here.
--   
--   This would be <a>Nothing</a>:
--   
--   <pre>
--   mAlanConst &lt;- checkUnique $ User "Alan" 70
--   </pre>
--   
--   While this would be <a>Just</a> because SPJ already exists:
--   
--   <pre>
--   mSpjConst &lt;- checkUnique $ User "SPJ" 60
--   </pre>
checkUniqueUpdateable :: forall record backend (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend, PersistUniqueRead backend) => Entity record -> ReaderT backend m (Maybe (Unique record))

-- | Backends supporting conditional write operations
class (PersistQueryRead backend, PersistStoreWrite backend) => PersistQueryWrite backend

-- | Update individual fields on any record matching the given criterion.
updateWhere :: forall (m :: Type -> Type) record. (PersistQueryWrite backend, MonadIO m, PersistRecordBackend record backend) => [Filter record] -> [Update record] -> ReaderT backend m ()

-- | Delete all records matching the given criterion.
deleteWhere :: forall (m :: Type -> Type) record. (PersistQueryWrite backend, MonadIO m, PersistRecordBackend record backend) => [Filter record] -> ReaderT backend m ()

-- | Backends supporting conditional read operations.
class (PersistCore backend, PersistStoreRead backend) => PersistQueryRead backend

-- | Get all records matching the given criterion in the specified order.
--   Returns also the identifiers.
--   
--   NOTE: This function returns an <a>Acquire</a> and a <a>ConduitM</a>,
--   which implies that it streams from the database. It does not. Please
--   use <a>selectList</a> to simplify the code. If you want streaming
--   behavior, consider <tt>persistent-pagination</tt> which efficiently
--   chunks a query into ranges, or investigate a backend-specific
--   streaming solution.
selectSourceRes :: forall record (m1 :: Type -> Type) (m2 :: Type -> Type). (PersistQueryRead backend, PersistRecordBackend record backend, MonadIO m1, MonadIO m2) => [Filter record] -> [SelectOpt record] -> ReaderT backend m1 (Acquire (ConduitM () (Entity record) m2 ()))

-- | Get just the first record for the criterion.
selectFirst :: forall (m :: Type -> Type) record. (PersistQueryRead backend, MonadIO m, PersistRecordBackend record backend) => [Filter record] -> [SelectOpt record] -> ReaderT backend m (Maybe (Entity record))

-- | Get the <a>Key</a>s of all records matching the given criterion.
selectKeysRes :: forall (m1 :: Type -> Type) (m2 :: Type -> Type) record. (PersistQueryRead backend, MonadIO m1, MonadIO m2, PersistRecordBackend record backend) => [Filter record] -> [SelectOpt record] -> ReaderT backend m1 (Acquire (ConduitM () (Key record) m2 ()))

-- | Get the <a>Key</a>s of all records matching the given criterion.
--   
--   For an example, see <a>selectList</a>.
selectKeys :: forall record backend (m :: Type -> Type). (PersistQueryRead backend, MonadResource m, PersistRecordBackend record backend, MonadReader backend m) => [Filter record] -> [SelectOpt record] -> ConduitM () (Key record) m ()

-- | 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.
type PersistStore a = PersistStoreWrite a

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

-- | A backend which is a wrapper around <tt>SqlBackend</tt>.
type IsSqlBackend backend = (IsPersistBackend backend, BaseBackend backend ~ SqlBackend)

-- | Like <tt>SqlPersistT</tt> but compatible with any SQL backend which
--   can handle read and write queries.
type SqlWriteT (m :: Type -> Type) a = forall backend. SqlBackendCanWrite backend => ReaderT backend m a

-- | Like <tt>SqlPersistT</tt> but compatible with any SQL backend which
--   can handle read queries.
type SqlReadT (m :: Type -> Type) a = forall backend. SqlBackendCanRead backend => ReaderT backend m a

-- | A constraint synonym which witnesses that a backend is SQL and can run
--   read and write queries.
type SqlBackendCanWrite backend = (SqlBackendCanRead backend, PersistQueryWrite backend, PersistStoreWrite backend, PersistUniqueWrite backend)

-- | A constraint synonym which witnesses that a backend is SQL and can run
--   read queries.
type SqlBackendCanRead backend = (BackendCompatible SqlBackend backend, PersistQueryRead backend, PersistStoreRead backend, PersistUniqueRead backend)

-- | An SQL backend which can handle read or write queries
--   
--   The constructor was exposed in 2.10.0
newtype SqlWriteBackend
SqlWriteBackend :: SqlBackend -> SqlWriteBackend
[unSqlWriteBackend] :: SqlWriteBackend -> SqlBackend

-- | An SQL backend which can only handle read queries
--   
--   The constructor was exposed in 2.10.0.
newtype SqlReadBackend
SqlReadBackend :: SqlBackend -> SqlReadBackend
[unSqlReadBackend] :: SqlReadBackend -> SqlBackend

-- | Useful for running a write query against an untagged backend with
--   unknown capabilities.
writeToUnknown :: forall (m :: Type -> Type) a. Monad m => ReaderT SqlWriteBackend m a -> ReaderT SqlBackend m a

-- | Useful for running a read query against a backend with read and write
--   capabilities.
readToWrite :: forall (m :: Type -> Type) a. Monad m => ReaderT SqlReadBackend m a -> ReaderT SqlWriteBackend m a

-- | Useful for running a read query against a backend with unknown
--   capabilities.
readToUnknown :: forall (m :: Type -> Type) a. Monad m => ReaderT SqlReadBackend m a -> ReaderT SqlBackend m a

-- | Values to configure a pool of database connections. See
--   <a>Data.Pool</a> for details.
data ConnectionPoolConfig
ConnectionPoolConfig :: Int -> NominalDiffTime -> Int -> ConnectionPoolConfig

-- | How many stripes to divide the pool into. See <a>Data.Pool</a> for
--   details. Default: 1.
[connectionPoolConfigStripes] :: ConnectionPoolConfig -> Int

-- | How long connections can remain idle before being disposed of, in
--   seconds. Default: 600
[connectionPoolConfigIdleTimeout] :: ConnectionPoolConfig -> NominalDiffTime

-- | How many connections should be held in the connection pool. Default:
--   10
[connectionPoolConfigSize] :: ConnectionPoolConfig -> Int
type ConnectionPool = Pool SqlBackend
type SqlPersistM = SqlPersistT NoLoggingT ResourceT IO
type SqlPersistT = ReaderT SqlBackend
data PersistentSqlException
StatementAlreadyFinalized :: Text -> PersistentSqlException
Couldn'tGetSQLConnection :: PersistentSqlException

-- | This value specifies how a field references another table.
data ColumnReference
ColumnReference :: !EntityNameDB -> !ConstraintNameDB -> !FieldCascade -> ColumnReference

-- | The table name that the
[crTableName] :: ColumnReference -> !EntityNameDB

-- | The name of the foreign key constraint.
[crConstraintName] :: ColumnReference -> !ConstraintNameDB

-- | Whether or not updates/deletions to the referenced table cascade to
--   this table.
[crFieldCascade] :: ColumnReference -> !FieldCascade

-- | Initializes a ConnectionPoolConfig with default values. See the
--   documentation of <a>ConnectionPoolConfig</a> for each field's default
--   value.
defaultConnectionPoolConfig :: ConnectionPoolConfig

-- | Record of functions to override the default behavior in
--   <a>mkColumns</a>. It is recommended you initialize this with
--   <a>emptyBackendSpecificOverrides</a> and override the default values,
--   so that as new fields are added, your code still compiles.
--   
--   For added safety, use the <tt>getBackendSpecific*</tt> and
--   <tt>setBackendSpecific*</tt> functions, as a breaking change to the
--   record field labels won't be reflected in a major version bump of the
--   library.
data BackendSpecificOverrides

-- | If the override is defined, then this returns a function that accepts
--   an entity name and field name and provides the <a>ConstraintNameDB</a>
--   for the foreign key constraint.
--   
--   An abstract accessor for the <a>BackendSpecificOverrides</a>
getBackendSpecificForeignKeyName :: BackendSpecificOverrides -> Maybe (EntityNameDB -> FieldNameDB -> ConstraintNameDB)

-- | Set the backend's foreign key generation function to this value.
setBackendSpecificForeignKeyName :: (EntityNameDB -> FieldNameDB -> ConstraintNameDB) -> BackendSpecificOverrides -> BackendSpecificOverrides

-- | Creates an empty <a>BackendSpecificOverrides</a> (i.e. use the default
--   behavior; no overrides)
emptyBackendSpecificOverrides :: BackendSpecificOverrides
defaultAttribute :: [FieldAttr] -> Maybe Text

-- | Create the list of columns for the given entity.
mkColumns :: [EntityDef] -> EntityDef -> BackendSpecificOverrides -> ([Column], [UniqueDef], [ForeignDef])

-- | A more general way to convert instances of <a>ToJSON</a> type class to
--   strict text <a>Text</a>.
toJsonText :: ToJSON j => j -> Text

-- | Tells Persistent what database column type should be used to store a
--   Haskell type.
--   
--   <h4><b>Examples</b></h4>
--   
--   <h5>Simple Boolean Alternative</h5>
--   
--   <pre>
--   data Switch = On | Off
--     deriving (Show, Eq)
--   
--   instance <a>PersistField</a> Switch where
--     <a>toPersistValue</a> s = case s of
--       On -&gt; <a>PersistBool</a> True
--       Off -&gt; <a>PersistBool</a> False
--     <a>fromPersistValue</a> (<a>PersistBool</a> b) = if b then <a>Right</a> On else <a>Right</a> Off
--     <a>fromPersistValue</a> x = Left $ "File.hs: When trying to deserialize a Switch: expected PersistBool, received: " &lt;&gt; T.pack (show x)
--   
--   instance <a>PersistFieldSql</a> Switch where
--     <a>sqlType</a> _ = <a>SqlBool</a>
--   </pre>
--   
--   <h5>Non-Standard Database Types</h5>
--   
--   If your database supports non-standard types, such as Postgres'
--   <tt>uuid</tt>, you can use <a>SqlOther</a> to use them:
--   
--   <pre>
--   import qualified Data.UUID as UUID
--   instance <a>PersistField</a> UUID where
--     <a>toPersistValue</a> = <tt>PersistLiteralEncoded</tt> . toASCIIBytes
--     <a>fromPersistValue</a> (<tt>PersistLiteralEncoded</tt> uuid) =
--       case fromASCIIBytes uuid of
--         <a>Nothing</a> -&gt; <a>Left</a> $ "Model/CustomTypes.hs: Failed to deserialize a UUID; received: " &lt;&gt; T.pack (show uuid)
--         <a>Just</a> uuid' -&gt; <a>Right</a> uuid'
--     <a>fromPersistValue</a> x = Left $ "File.hs: When trying to deserialize a UUID: expected PersistLiteralEncoded, received: "-- &gt;  &lt;&gt; T.pack (show x)
--   
--   instance <a>PersistFieldSql</a> UUID where
--     <a>sqlType</a> _ = <a>SqlOther</a> "uuid"
--   </pre>
--   
--   <h5>User Created Database Types</h5>
--   
--   Similarly, some databases support creating custom types, e.g.
--   Postgres' <a>DOMAIN</a> and <a>ENUM</a> features. You can use
--   <a>SqlOther</a> to specify a custom type:
--   
--   <pre>
--   CREATE DOMAIN ssn AS text
--         CHECK ( value ~ '^[0-9]{9}$');
--   </pre>
--   
--   <pre>
--   instance <tt>PersistFieldSQL</tt> SSN where
--     <a>sqlType</a> _ = <a>SqlOther</a> "ssn"
--   </pre>
--   
--   <pre>
--   CREATE TYPE rainbow_color AS ENUM ('red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet');
--   </pre>
--   
--   <pre>
--   instance <tt>PersistFieldSQL</tt> RainbowColor where
--     <a>sqlType</a> _ = <a>SqlOther</a> "rainbow_color"
--   </pre>
class PersistField a => PersistFieldSql a
sqlType :: PersistFieldSql a => Proxy a -> SqlType

-- | This newtype wrapper is useful when selecting an entity out of the
--   database and you want to provide a prefix to the table being selected.
--   
--   Consider this raw SQL query:
--   
--   <pre>
--   SELECT ??
--   FROM my_long_table_name AS mltn
--   INNER JOIN other_table AS ot
--      ON mltn.some_col = ot.other_col
--   WHERE ...
--   </pre>
--   
--   We don't want to refer to <tt>my_long_table_name</tt> every time, so
--   we create an alias. If we want to select it, we have to tell the raw
--   SQL quasi-quoter that we expect the entity to be prefixed with some
--   other name.
--   
--   We can give the above query a type with this, like:
--   
--   <pre>
--   getStuff :: <a>SqlPersistM</a> [<a>EntityWithPrefix</a> "mltn" MyLongTableName]
--   getStuff = rawSql queryText []
--   </pre>
--   
--   The <a>EntityWithPrefix</a> bit is a boilerplate newtype wrapper, so
--   you can remove it with <a>unPrefix</a>, like this:
--   
--   <pre>
--   getStuff :: <a>SqlPersistM</a> [<a>Entity</a> MyLongTableName]
--   getStuff = <a>unPrefix</a> @"mltn" <a>&lt;$&gt;</a> <tt>rawSql</tt> queryText []
--   </pre>
--   
--   The <tt> symbol is a "type application" and requires the
--   </tt>TypeApplications@ language extension.
newtype EntityWithPrefix (prefix :: Symbol) record
EntityWithPrefix :: Entity record -> EntityWithPrefix (prefix :: Symbol) record
[unEntityWithPrefix] :: EntityWithPrefix (prefix :: Symbol) record -> Entity record

-- | Class for data types that may be retrived from a <tt>rawSql</tt>
--   query.
class RawSql a

-- | Number of columns that this data type needs and the list of
--   substitutions for <tt>SELECT</tt> placeholders <tt>??</tt>.
rawSqlCols :: RawSql a => (Text -> Text) -> a -> (Int, [Text])

-- | A string telling the user why the column count is what it is.
rawSqlColCountReason :: RawSql a => a -> String

-- | Transform a row of the result into the data type.
rawSqlProcessRow :: RawSql a => [PersistValue] -> Either Text a

-- | A helper function to tell GHC what the <a>EntityWithPrefix</a> prefix
--   should be. This allows you to use a type application to specify the
--   prefix, instead of specifying the etype on the result.
--   
--   As an example, here's code that uses this:
--   
--   <pre>
--   myQuery :: <a>SqlPersistM</a> [<a>Entity</a> Person]
--   myQuery = fmap (unPrefix @"p") <a>$</a> rawSql query []
--     where
--       query = "SELECT ?? FROM person AS p"
--   </pre>
unPrefix :: forall (prefix :: Symbol) record. EntityWithPrefix prefix record -> Entity record
rawQuery :: forall (m :: Type -> Type) env. (MonadResource m, MonadReader env m, BackendCompatible SqlBackend env) => Text -> [PersistValue] -> ConduitM () [PersistValue] m ()
rawQueryRes :: forall (m1 :: Type -> Type) (m2 :: Type -> Type) env. (MonadIO m1, MonadIO m2, BackendCompatible SqlBackend env) => Text -> [PersistValue] -> ReaderT env m1 (Acquire (ConduitM () [PersistValue] m2 ()))

-- | Execute a raw SQL statement
rawExecute :: forall (m :: Type -> Type) backend. (MonadIO m, BackendCompatible SqlBackend backend) => Text -> [PersistValue] -> ReaderT backend m ()

-- | Execute a raw SQL statement and return the number of rows it has
--   modified.
rawExecuteCount :: forall (m :: Type -> Type) backend. (MonadIO m, BackendCompatible SqlBackend backend) => Text -> [PersistValue] -> ReaderT backend m Int64
getStmtConn :: SqlBackend -> Text -> IO Statement

-- | Get a connection from the pool, run the given action, and then return
--   the connection to the pool.
--   
--   This function performs the given action in a transaction. If an
--   exception occurs during the action, then the transaction is rolled
--   back.
--   
--   Note: This function previously timed out after 2 seconds, but this
--   behavior was buggy and caused more problems than it solved. Since
--   version 2.1.2, it performs no timeout checks.
runSqlPool :: forall backend m a. (MonadUnliftIO m, BackendCompatible SqlBackend backend) => ReaderT backend m a -> Pool backend -> m a

-- | Like <a>runSqlPool</a>, but supports specifying an isolation level.
runSqlPoolWithIsolation :: forall backend m a. (MonadUnliftIO m, BackendCompatible SqlBackend backend) => ReaderT backend m a -> Pool backend -> IsolationLevel -> m a

-- | Like <a>runSqlPool</a>, but does not surround the action in a
--   transaction. This action might leave your database in a weird state.
runSqlPoolNoTransaction :: forall backend m a. (MonadUnliftIO m, BackendCompatible SqlBackend backend) => ReaderT backend m a -> Pool backend -> Maybe IsolationLevel -> m a

-- | This function is how <a>runSqlPool</a> and
--   <a>runSqlPoolNoTransaction</a> are defined. In addition to the action
--   to be performed and the <a>Pool</a> of conections to use, we give you
--   the opportunity to provide three actions - initialize, afterwards, and
--   onException.
runSqlPoolWithHooks :: forall backend m a before after onException. (MonadUnliftIO m, BackendCompatible SqlBackend backend) => ReaderT backend m a -> Pool backend -> Maybe IsolationLevel -> (backend -> m before) -> (backend -> m after) -> (backend -> SomeException -> m onException) -> m a

-- | This function is how <a>runSqlPoolWithHooks</a> is defined.
--   
--   It's currently the most general function for using a SQL pool.
runSqlPoolWithExtensibleHooks :: forall backend m a. (MonadUnliftIO m, BackendCompatible SqlBackend backend) => ReaderT backend m a -> Pool backend -> Maybe IsolationLevel -> SqlPoolHooks m backend -> m a

-- | Starts a new transaction on the connection. When the acquired
--   connection is released the transaction is committed and the connection
--   returned to the pool.
--   
--   Upon an exception the transaction is rolled back and the connection
--   destroyed.
--   
--   This is equivalent to <a>runSqlConn</a> but does not incur the
--   <a>MonadUnliftIO</a> constraint, meaning it can be used within, for
--   example, a <tt>Conduit</tt> pipeline.
acquireSqlConn :: (MonadReader backend m, BackendCompatible SqlBackend backend) => m (Acquire backend)

-- | Like <a>acquireSqlConn</a>, but lets you specify an explicit isolation
--   level.
acquireSqlConnWithIsolation :: (MonadReader backend m, BackendCompatible SqlBackend backend) => IsolationLevel -> m (Acquire backend)
runSqlConn :: forall backend m a. (MonadUnliftIO m, BackendCompatible SqlBackend backend) => ReaderT backend m a -> backend -> m a

-- | Like <a>runSqlConn</a>, but supports specifying an isolation level.
runSqlConnWithIsolation :: forall backend m a. (MonadUnliftIO m, BackendCompatible SqlBackend backend) => ReaderT backend m a -> backend -> IsolationLevel -> m a
runSqlPersistM :: BackendCompatible SqlBackend backend => ReaderT backend (NoLoggingT (ResourceT IO)) a -> backend -> IO a
runSqlPersistMPool :: BackendCompatible SqlBackend backend => ReaderT backend (NoLoggingT (ResourceT IO)) a -> Pool backend -> IO a
liftSqlPersistMPool :: forall backend m a. (MonadIO m, BackendCompatible SqlBackend backend) => ReaderT backend (NoLoggingT (ResourceT IO)) a -> Pool backend -> m a
withSqlPool :: forall backend m a. (MonadLoggerIO m, MonadUnliftIO m, BackendCompatible SqlBackend backend) => (LogFunc -> IO backend) -> Int -> (Pool backend -> m a) -> m a

-- | Creates a pool of connections to a SQL database which can be used by
--   the <tt>Pool backend -&gt; m a</tt> function. After the function
--   completes, the connections are destroyed.
withSqlPoolWithConfig :: forall backend m a. (MonadLoggerIO m, MonadUnliftIO m, BackendCompatible SqlBackend backend) => (LogFunc -> IO backend) -> ConnectionPoolConfig -> (Pool backend -> m a) -> m a
createSqlPool :: forall backend m. (MonadLoggerIO m, MonadUnliftIO m, BackendCompatible SqlBackend backend) => (LogFunc -> IO backend) -> Int -> m (Pool backend)

-- | Creates a pool of connections to a SQL database.
createSqlPoolWithConfig :: (MonadLoggerIO m, MonadUnliftIO m, BackendCompatible SqlBackend backend) => (LogFunc -> IO backend) -> ConnectionPoolConfig -> m (Pool backend)

-- | Create a connection and run sql queries within it. This function
--   automatically closes the connection on it's completion.
--   
--   <h3><b>Example usage</b></h3>
--   
--   <pre>
--   {-# LANGUAGE GADTs #-}
--   {-# LANGUAGE ScopedTypeVariables #-}
--   {-# LANGUAGE OverloadedStrings #-}
--   {-# LANGUAGE MultiParamTypeClasses #-}
--   {-# LANGUAGE TypeFamilies#-}
--   {-# LANGUAGE TemplateHaskell#-}
--   {-# LANGUAGE QuasiQuotes#-}
--   {-# LANGUAGE GeneralizedNewtypeDeriving #-}
--   
--   import Control.Monad.IO.Class  (liftIO)
--   import Control.Monad.Logger
--   import Conduit
--   import Database.Persist
--   import Database.Sqlite
--   import Database.Persist.Sqlite
--   import Database.Persist.TH
--   
--   share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
--   Person
--     name String
--     age Int Maybe
--     deriving Show
--   |]
--   
--   openConnection :: LogFunc -&gt; IO SqlBackend
--   openConnection logfn = do
--    conn &lt;- open "/home/sibi/test.db"
--    wrapConnection conn logfn
--   
--   main :: IO ()
--   main = do
--     runNoLoggingT $ runResourceT $ withSqlConn openConnection (\backend -&gt;
--                                         flip runSqlConn backend $ do
--                                           runMigration migrateAll
--                                           insert_ $ Person "John doe" $ Just 35
--                                           insert_ $ Person "Divya" $ Just 36
--                                           (pers :: [Entity Person]) &lt;- selectList [] []
--                                           liftIO $ print pers
--                                           return ()
--                                        )
--   </pre>
--   
--   On executing it, you get this output:
--   
--   <pre>
--   Migrating: CREATE TABLE "person"("id" INTEGER PRIMARY KEY,"name" VARCHAR NOT NULL,"age" INTEGER NULL)
--   [Entity {entityKey = PersonKey {unPersonKey = SqlBackendKey {unSqlBackendKey = 1}}, entityVal = Person {personName = "John doe", personAge = Just 35}},Entity {entityKey = PersonKey {unPersonKey = SqlBackendKey {unSqlBackendKey = 2}}, entityVal = Person {personName = "Hema", personAge = Just 36}}]
--   </pre>
withSqlConn :: forall backend m a. (MonadUnliftIO m, MonadLoggerIO m, BackendCompatible SqlBackend backend) => (LogFunc -> IO backend) -> (backend -> m a) -> m a
close' :: BackendCompatible SqlBackend backend => backend -> IO ()
withRawQuery :: forall (m :: Type -> Type) a. MonadIO m => Text -> [PersistValue] -> ConduitM [PersistValue] Void IO a -> ReaderT SqlBackend m a
toSqlKey :: ToBackendKey SqlBackend record => Int64 -> Key record
fromSqlKey :: ToBackendKey SqlBackend record => Key record -> Int64

-- | get the SQL string for the table that a PersistEntity represents
--   Useful for raw SQL queries
--   
--   Your backend may provide a more convenient tableName function which
--   does not operate in a Monad
getTableName :: forall record (m :: Type -> Type) backend. (PersistEntity record, BackendCompatible SqlBackend backend, Monad m) => record -> ReaderT backend m Text

-- | useful for a backend to implement tableName by adding escaping
tableDBName :: PersistEntity record => record -> EntityNameDB

-- | get the SQL string for the field that an EntityField represents Useful
--   for raw SQL queries
--   
--   Your backend may provide a more convenient fieldName function which
--   does not operate in a Monad
getFieldName :: forall record typ (m :: Type -> Type) backend. (PersistEntity record, PersistEntityBackend record ~ SqlBackend, BackendCompatible SqlBackend backend, Monad m) => EntityField record typ -> ReaderT backend m Text

-- | useful for a backend to implement fieldName by adding escaping
fieldDBName :: PersistEntity record => EntityField record typ -> FieldNameDB

-- | Used when determining how to prefix a column name in a <tt>WHERE</tt>
--   clause.
data FilterTablePrefix

-- | Prefix the column with the table name. This is useful if the column
--   name might be ambiguous.
PrefixTableName :: FilterTablePrefix

-- | Prefix the column name with the <tt>EXCLUDED</tt> keyword. This is
--   used with the Postgresql backend when doing <tt>ON CONFLICT DO
--   UPDATE</tt> clauses - see the documentation on <tt>upsertWhere</tt>
--   and <tt>upsertManyWhere</tt>.
PrefixExcluded :: FilterTablePrefix

-- | Render a <tt>[<a>Filter</a> record]</tt> into a <a>Text</a> value
--   suitable for inclusion into a SQL query.
filterClause :: PersistEntity val => Maybe FilterTablePrefix -> SqlBackend -> [Filter val] -> Text

-- | Render a <tt>[<a>Filter</a> record]</tt> into a <a>Text</a> value
--   suitable for inclusion into a SQL query, as well as the
--   <tt>[<a>PersistValue</a>]</tt> to properly fill in the <tt>?</tt>
--   place holders.
filterClauseWithVals :: PersistEntity val => Maybe FilterTablePrefix -> SqlBackend -> [Filter val] -> (Text, [PersistValue])

-- | Render a <tt>[<a>SelectOpt</a> record]</tt> made up *only* of
--   <a>Asc</a> and <a>Desc</a> constructors into a <a>Text</a> value
--   suitable for inclusion into a SQL query.
orderClause :: PersistEntity val => Maybe FilterTablePrefix -> SqlBackend -> [SelectOpt val] -> Text

-- | Generates sql for limit and offset for postgres, sqlite and mysql.
decorateSQLWithLimitOffset :: Text -> (Int, Int) -> Text -> Text

-- | An exception indicating that Persistent refused to run some unsafe
--   migrations. Contains a list of pairs where the Bool tracks whether the
--   migration was unsafe (True means unsafe), and the Sql is the sql
--   statement for the migration.
newtype PersistUnsafeMigrationException
PersistUnsafeMigrationException :: [(Bool, Sql)] -> PersistUnsafeMigrationException

-- | A <a>Migration</a> is a four level monad stack consisting of:
--   
--   <ul>
--   <li><tt><a>WriterT</a> [<a>Text</a>]</tt> representing a log of errors
--   in the migrations.</li>
--   <li><tt><a>WriterT</a> <a>CautiousMigration</a></tt> representing a
--   list of migrations to run, along with whether or not they are
--   safe.</li>
--   <li><tt><a>ReaderT</a> <a>SqlBackend</a></tt>, aka the
--   <a>SqlPersistT</a> transformer for database interop.</li>
--   <li><tt><a>IO</a></tt> for arbitrary IO.</li>
--   </ul>
type Migration = WriterT [Text] WriterT CautiousMigration ReaderT SqlBackend IO ()

-- | A list of SQL operations, marked with a safety flag. If the
--   <a>Bool</a> is <a>True</a>, then the operation is *unsafe* - it might
--   be destructive, or otherwise not idempotent. If the <a>Bool</a> is
--   <a>False</a>, then the operation is *safe*, and can be run repeatedly
--   without issues.
type CautiousMigration = [(Bool, Sql)]
type Sql = Text

-- | Given a <a>Migration</a>, this parses it and returns either a list of
--   errors associated with the migration or a list of migrations to do.
parseMigration :: forall (m :: Type -> Type). (HasCallStack, MonadIO m) => Migration -> ReaderT SqlBackend m (Either [Text] CautiousMigration)

-- | Like <a>parseMigration</a>, but instead of returning the value in an
--   <a>Either</a> value, it calls <a>error</a> on the error values.
parseMigration' :: forall (m :: Type -> Type). (HasCallStack, MonadIO m) => Migration -> ReaderT SqlBackend m CautiousMigration

-- | Prints a migration.
printMigration :: forall (m :: Type -> Type). (HasCallStack, MonadIO m) => Migration -> ReaderT SqlBackend m ()

-- | Convert a <a>Migration</a> to a list of <a>Text</a> values
--   corresponding to their <a>Sql</a> statements.
showMigration :: forall (m :: Type -> Type). (HasCallStack, MonadIO m) => Migration -> ReaderT SqlBackend m [Text]

-- | Return all of the <a>Sql</a> values associated with the given
--   migration. Calls <a>error</a> if there's a parse error on any
--   migration.
getMigration :: forall (m :: Type -> Type). (MonadIO m, HasCallStack) => Migration -> ReaderT SqlBackend m [Sql]

-- | Runs a migration. If the migration fails to parse or if any of the
--   migrations are unsafe, then this throws a
--   <a>PersistUnsafeMigrationException</a>.
runMigration :: forall (m :: Type -> Type). MonadIO m => Migration -> ReaderT SqlBackend m ()

-- | Same as <a>runMigration</a>, but does not report the individual
--   migrations on stderr. Instead it returns a list of the executed SQL
--   commands.
--   
--   This is a safer/more robust alternative to <a>runMigrationSilent</a>,
--   but may be less silent for some persistent implementations, most
--   notably persistent-postgresql
runMigrationQuiet :: forall (m :: Type -> Type). MonadIO m => Migration -> ReaderT SqlBackend m [Text]

-- | Same as <a>runMigration</a>, but returns a list of the SQL commands
--   executed instead of printing them to stderr.
--   
--   This function silences the migration by remapping <a>stderr</a>. As a
--   result, it is not thread-safe and can clobber output from other parts
--   of the program. This implementation method was chosen to also silence
--   postgresql migration output on stderr, but is not recommended!
runMigrationSilent :: forall (m :: Type -> Type). MonadUnliftIO m => Migration -> ReaderT SqlBackend m [Text]

-- | Like <a>runMigration</a>, but this will perform the unsafe database
--   migrations instead of erroring out.
runMigrationUnsafe :: forall (m :: Type -> Type). MonadIO m => Migration -> ReaderT SqlBackend m ()

-- | Same as <a>runMigrationUnsafe</a>, but returns a list of the SQL
--   commands executed instead of printing them to stderr.
runMigrationUnsafeQuiet :: forall (m :: Type -> Type). (HasCallStack, MonadIO m) => Migration -> ReaderT SqlBackend m [Text]

-- | Report multiple errors in a <a>Migration</a>.
reportErrors :: [Text] -> Migration

-- | Add a migration to the migration plan.
addMigration :: Bool -> Sql -> Migration

-- | Add a <a>CautiousMigration</a> (aka a <tt>[(<a>Bool</a>,
--   <a>Text</a>)]</tt>) to the migration plan.
addMigrations :: CautiousMigration -> Migration

-- | Run an action against the database during a migration. Can be useful
--   for eg creating Postgres extensions:
--   
--   <pre>
--   runSqlCommand $ <a>rawExecute</a> "CREATE EXTENSION IF NOT EXISTS "uuid-ossp";" []
--   </pre>
runSqlCommand :: SqlPersistT IO () -> Migration

-- | Commit the current transaction and begin a new one. This is used when
--   a transaction commit is required within the context of
--   <a>runSqlConn</a> (which brackets its provided action with a
--   transaction begin/commit pair).
transactionSave :: forall (m :: Type -> Type). MonadIO m => ReaderT SqlBackend m ()

-- | Commit the current transaction and begin a new one with the specified
--   isolation level.
transactionSaveWithIsolation :: forall (m :: Type -> Type). MonadIO m => IsolationLevel -> ReaderT SqlBackend m ()

-- | Roll back the current transaction and begin a new one. This rolls back
--   to the state of the last call to <a>transactionSave</a> or the
--   enclosing <a>runSqlConn</a> call.
transactionUndo :: forall (m :: Type -> Type). MonadIO m => ReaderT SqlBackend m ()

-- | Roll back the current transaction and begin a new one with the
--   specified isolation level.
transactionUndoWithIsolation :: forall (m :: Type -> Type). MonadIO m => IsolationLevel -> ReaderT SqlBackend m ()


-- | This module contain MySQL-specific functions.
module Database.Esqueleto.MySQL

-- | (<tt>random()</tt>) Split out into database specific modules because
--   MySQL uses `rand()`.
random_ :: (PersistField a, Num a) => SqlExpr (Value a)

-- | <tt>LOCK IN SHARE MODE</tt> syntax.
--   
--   Example:
--   
--   <pre>
--   <a>locking</a> <a>lockInShareMode</a>
--   </pre>
lockInShareMode :: LockingKind


-- | This module contain PostgreSQL-specific functions.
module Database.Esqueleto.PostgreSQL

-- | Aggregate mode
data AggMode

-- | ALL
AggModeAll :: AggMode

-- | DISTINCT
AggModeDistinct :: AggMode

-- | (<tt>array_agg</tt>) Concatenate distinct input values, including
--   <tt>NULL</tt>s, into an array.
arrayAggDistinct :: (PersistField a, PersistField [a]) => SqlExpr (Value a) -> SqlExpr (Value (Maybe [a]))
arrayAgg :: PersistField a => SqlExpr (Value a) -> SqlExpr (Value (Maybe [a]))
arrayAggWith :: AggMode -> SqlExpr (Value a) -> [OrderByClause] -> SqlExpr (Value (Maybe [a]))

-- | (<tt>array_remove</tt>) Remove all elements equal to the given value
--   from the array.
arrayRemove :: SqlExpr (Value [a]) -> SqlExpr (Value a) -> SqlExpr (Value [a])

-- | Remove <tt>NULL</tt> values from an array
arrayRemoveNull :: SqlExpr (Value [Maybe a]) -> SqlExpr (Value [a])

-- | (<tt>string_agg</tt>) Concatenate input values separated by a
--   delimiter.
stringAgg :: SqlString s => SqlExpr (Value s) -> SqlExpr (Value s) -> SqlExpr (Value (Maybe s))

-- | (<tt>string_agg</tt>) Concatenate input values separated by a
--   delimiter.
stringAggWith :: SqlString s => AggMode -> SqlExpr (Value s) -> SqlExpr (Value s) -> [OrderByClause] -> SqlExpr (Value (Maybe s))

-- | Coalesce an array with an empty default value
maybeArray :: (PersistField a, PersistField [a]) => SqlExpr (Value (Maybe [a])) -> SqlExpr (Value [a])

-- | (<tt>chr</tt>) Translate the given integer to a character. (Note the
--   result will depend on the character set of your database.)
chr :: SqlString s => SqlExpr (Value Int) -> SqlExpr (Value s)
now_ :: SqlExpr (Value UTCTime)

-- | (<tt>random()</tt>) Split out into database specific modules because
--   MySQL uses `rand()`.
random_ :: (PersistField a, Num a) => SqlExpr (Value a)

-- | Perform an <tt>upsert</tt> operation on the given record.
--   
--   If the record exists in the database already, then the updates will be
--   performed on that record. If the record does not exist, then the
--   provided record will be inserted.
--   
--   If you wish to provide an empty list of updates (ie "if the record
--   exists, do nothing"), then you will need to call <a>upsertMaybe</a>.
--   Postgres will not return anything if there are no modifications or
--   inserts made.
upsert :: forall (m :: Type -> Type) record. (MonadIO m, PersistEntity record, OnlyOneUniqueKey record, PersistRecordBackend record SqlBackend, IsPersistBackend (PersistEntityBackend record)) => record -> NonEmpty (SqlExpr (Entity record) -> SqlExpr Update) -> ReaderT SqlBackend m (Entity record)

-- | Like <a>upsert</a>, but permits an empty list of updates to be
--   performed.
--   
--   If no updates are provided and the record already was present in the
--   database, then this will return <a>Nothing</a>. If you want to fetch
--   the record out of the database, you can write:
--   
--   <pre>
--   mresult &lt;- upsertMaybe record []
--   case mresult of
--       Nothing -&gt;
--           <a>getBy</a> (<a>onlyUniqueP</a> record)
--       Just res -&gt;
--           pure (Just res)
--   </pre>
upsertMaybe :: forall (m :: Type -> Type) record. (MonadIO m, PersistEntity record, OnlyOneUniqueKey record, PersistRecordBackend record SqlBackend, IsPersistBackend (PersistEntityBackend record)) => record -> [SqlExpr (Entity record) -> SqlExpr Update] -> ReaderT SqlBackend m (Maybe (Entity record))
upsertBy :: forall (m :: Type -> Type) record. (MonadIO m, PersistEntity record, IsPersistBackend (PersistEntityBackend record), HasCallStack) => Unique record -> record -> NonEmpty (SqlExpr (Entity record) -> SqlExpr Update) -> ReaderT SqlBackend m (Entity record)

-- | Attempt to insert a <tt>record</tt> into the database. If the
--   <tt>record</tt> already exists for the given <tt><a>Unique</a>
--   record</tt>, then a list of updates will be performed.
--   
--   If you provide an empty list of updates, then this function will
--   return <a>Nothing</a> if the record already exists in the database.
upsertMaybeBy :: forall (m :: Type -> Type) record. (MonadIO m, PersistEntity record, IsPersistBackend (PersistEntityBackend record)) => Unique record -> record -> [SqlExpr (Entity record) -> SqlExpr Update] -> ReaderT SqlBackend m (Maybe (Entity record))

-- | Inserts into a table the results of a query similar to
--   <a>insertSelect</a> but allows to update values that violate a
--   constraint during insertions.
--   
--   Example of usage:
--   
--   <pre>
--   <tt>mkPersist</tt> <tt>sqlSettings</tt> [<tt>persistLowerCase</tt>|
--     Bar
--       num Int
--       deriving Eq Show
--     Foo
--       num Int
--       UniqueFoo num
--       deriving Eq Show
--   |]
--   
--   action = do
--       <a>insertSelectWithConflict</a>
--           UniqueFoo -- (UniqueFoo undefined) or (UniqueFoo anyNumber) would also work
--           (do
--               b &lt;- from $ table @Bar
--               return $ Foo &lt;# (b ^. BarNum)
--           )
--           (\current excluded -&gt;
--               [FooNum =. (current ^. FooNum) +. (excluded ^. FooNum)]
--           )
--   </pre>
--   
--   Inserts to table <tt>Foo</tt> all <tt>Bar.num</tt> values and in case
--   of conflict <tt>SomeFooUnique</tt>, the conflicting value is updated
--   to the current plus the excluded.
insertSelectWithConflict :: forall a (m :: Type -> Type) val backend. (FinalResult a, KnowResult a ~ Unique val, MonadIO m, PersistEntity val, SqlBackendCanWrite backend) => a -> SqlQuery (SqlExpr (Insertion val)) -> (SqlExpr (Entity val) -> SqlExpr (Entity val) -> [SqlExpr (Entity val) -> SqlExpr Update]) -> ReaderT backend m ()

-- | Same as <a>insertSelectWithConflict</a> but returns the number of rows
--   affected.
insertSelectWithConflictCount :: forall a val (m :: Type -> Type) backend. (FinalResult a, KnowResult a ~ Unique val, MonadIO m, PersistEntity val, SqlBackendCanWrite backend) => a -> SqlQuery (SqlExpr (Insertion val)) -> (SqlExpr (Entity val) -> SqlExpr (Entity val) -> [SqlExpr (Entity val) -> SqlExpr Update]) -> ReaderT backend m Int64

-- | <tt>NOWAIT</tt> syntax for postgres locking error will be thrown if
--   locked rows are attempted to be selected
noWait :: OnLockedBehavior

-- | default behaviour of postgres locks. will attempt to wait for locks to
--   expire
wait :: OnLockedBehavior

-- | `SKIP LOCKED` syntax for postgres locking locked rows will be skipped
skipLocked :: OnLockedBehavior

-- | `FOR UPDATE OF` syntax for postgres locking allows locking of specific
--   tables with an update lock in a view or join
forUpdateOf :: LockableEntity a => a -> OnLockedBehavior -> SqlQuery ()

-- | `FOR NO KEY UPDATE OF` syntax for postgres locking allows locking of
--   specific tables with a no key update lock in a view or join
forNoKeyUpdateOf :: LockableEntity a => a -> OnLockedBehavior -> SqlQuery ()

-- | <tt>FOR SHARE</tt> syntax for Postgres locking.
--   
--   Example use:
--   
--   <pre>
--   <a>locking</a> <a>forShare</a>
--   </pre>
forShare :: LockingKind

-- | `FOR SHARE OF` syntax for postgres locking allows locking of specific
--   tables with a share lock in a view or join
forShareOf :: LockableEntity a => a -> OnLockedBehavior -> SqlQuery ()

-- | `FOR KEY SHARE OF` syntax for postgres locking allows locking of
--   specific tables with a key share lock in a view or join
forKeyShareOf :: LockableEntity a => a -> OnLockedBehavior -> SqlQuery ()

-- | Allow aggregate functions to take a filter clause.
--   
--   Example of usage:
--   
--   <pre>
--   share [mkPersist sqlSettings] [persistLowerCase|
--     User
--       name Text
--       deriving Eq Show
--     Task
--       userId UserId
--       completed Bool
--       deriving Eq Show
--   |]
--   
--   select $ from $ (users <a>InnerJoin</a> tasks) -&gt; do
--     on $ users ^. UserId ==. tasks ^. TaskUserId
--     groupBy $ users ^. UserId
--     return
--      ( users ^. UserId
--      , count (tasks ^. TaskId) <a>filterWhere</a> (tasks ^. TaskCompleted ==. val True)
--      , count (tasks ^. TaskId) <a>filterWhere</a> (tasks ^. TaskCompleted ==. val False)
--      )
--   </pre>
filterWhere :: SqlExpr (Value a) -> SqlExpr (Value Bool) -> SqlExpr (Value a)

-- | Allows to use `VALUES (..)` in-memory set of values in RHS of
--   <tt>from</tt> expressions. Useful for JOIN's on known values which
--   also can be additionally preprocessed somehow on db side with usage of
--   inner PostgreSQL capabilities.
--   
--   Example of usage:
--   
--   <pre>
--   share [mkPersist sqlSettings] [persistLowerCase|
--     User
--       name Text
--       age Int
--       deriving Eq Show
--   
--   select $ do
--    bound :&amp; user &lt;- from $
--        values (   (val (10 :: Int), val ("ten" :: Text))
--              :| [ (val 20, val "twenty")
--                 , (val 30, val "thirty") ]
--              )
--        <a>InnerJoin</a> table User
--        <tt>on</tt> (((bound, _boundName) :&amp; user) -&gt; user^.UserAge &gt;=. bound)
--    groupBy bound
--    pure (bound, count @Int $ user^.UserName)
--   </pre>
values :: (ToSomeValues a, ToAliasReference a, ToAlias a) => NonEmpty a -> From a

-- | <tt>ILIKE</tt> operator (case-insensitive <tt>LIKE</tt>).
ilike :: SqlString s => SqlExpr (Value s) -> SqlExpr (Value s) -> SqlExpr (Value Bool)
infixr 2 `ilike`

-- | <tt>DISTINCT ON</tt>. Change the current <tt>SELECT</tt> into
--   <tt>SELECT DISTINCT ON (SqlExpressions)</tt>. For example:
--   
--   <pre>
--   select $ do
--     foo &lt;- <tt>from</tt> $ table @Foo
--     <a>distinctOn</a> [<a>don</a> (foo ^. FooName), <a>don</a> (foo ^. FooState)]
--     pure foo
--   </pre>
--   
--   You can also chain different calls to <a>distinctOn</a>. The above is
--   equivalent to:
--   
--   <pre>
--   select $ do
--     foo &lt;- <tt>from</tt> $ table @Foo
--     <a>distinctOn</a> [<a>don</a> (foo ^. FooName)]
--     <a>distinctOn</a> [<a>don</a> (foo ^. FooState)]
--     pure foo
--   </pre>
--   
--   Each call to <a>distinctOn</a> adds more SqlExpressions. Calls to
--   <a>distinctOn</a> override any calls to <a>distinct</a>.
--   
--   Note that PostgreSQL requires the SqlExpressions on <tt>DISTINCT
--   ON</tt> to be the first ones to appear on a <tt>ORDER BY</tt>. This is
--   not managed automatically by esqueleto, keeping its spirit of trying
--   to be close to raw SQL.
distinctOn :: [SqlExpr DistinctOn] -> SqlQuery ()

-- | A convenience function that calls both <a>distinctOn</a> and
--   <a>orderBy</a>. In other words,
--   
--   <pre>
--   <a>distinctOnOrderBy</a> [asc foo, desc bar, desc quux]
--   </pre>
--   
--   is the same as:
--   
--   <pre>
--   <a>distinctOn</a> [don foo, don  bar, don  quux]
--   <a>orderBy</a>  [asc foo, desc bar, desc quux]
--     ...
--   </pre>
distinctOnOrderBy :: [SqlExpr OrderBy] -> SqlQuery ()

-- | <tt>WITH</tt> <tt>MATERIALIZED</tt> clause is used to introduce a
--   <a>Common Table Expression (CTE)</a> with the MATERIALIZED keyword.
--   The MATERIALIZED keyword is only supported in PostgreSQL &gt;= version
--   12. In Esqueleto, CTEs should be used as a subquery memoization
--   tactic. PostgreSQL treats a materialized CTE as an optimization fence.
--   A materialized CTE is always fully calculated, and is not "inlined"
--   with other table joins. Without the MATERIALIZED keyword, PostgreSQL
--   &gt;= 12 may "inline" the CTE as though it was any other join. You
--   should always verify that using a materialized CTE will in fact
--   improve your performance over a regular subquery.
--   
--   <pre>
--   select $ do
--   cte &lt;- withMaterialized subQuery
--   cteResult &lt;- from cte
--   where_ $ cteResult ...
--   pure cteResult
--   </pre>
--   
--   For more information on materialized CTEs, see the PostgreSQL manual
--   documentation on <a>Common Table Expression Materialization</a>.
withMaterialized :: (ToAlias a, ToAliasReference a, SqlSelect a r) => SqlQuery a -> SqlQuery (From a)

-- | <tt>WITH</tt> <tt>NOT</tt> <tt>MATERIALIZED</tt> clause is used to
--   introduce a <a>Common Table Expression (CTE)</a> with the NOT
--   MATERIALIZED keywords. These are only supported in PostgreSQL &gt;=
--   version 12. In Esqueleto, CTEs should be used as a subquery
--   memoization tactic. PostgreSQL treats a materialized CTE as an
--   optimization fence. A MATERIALIZED CTE is always fully calculated, and
--   is not "inlined" with other table joins. Sometimes, this is
--   undesirable, so postgres provides the NOT MATERIALIZED modifier to
--   prevent this behavior, thus enabling it to possibly decide to treat
--   the CTE as any other join.
--   
--   Given the above, it is unlikely that this function will be useful, as
--   a normal join should be used instead, but is provided for
--   completeness.
--   
--   <pre>
--   select $ do
--   cte &lt;- withNotMaterialized subQuery
--   cteResult &lt;- from cte
--   where_ $ cteResult ...
--   pure cteResult
--   </pre>
--   
--   For more information on materialized CTEs, see the PostgreSQL manual
--   documentation on <a>Common Table Expression Materialization</a>.
withNotMaterialized :: (ToAlias a, ToAliasReference a, SqlSelect a r) => SqlQuery a -> SqlQuery (From a)

-- | Ascending order of this field or SqlExpression with nulls coming
--   first.
ascNullsFirst :: PersistField a => SqlExpr (Value a) -> SqlExpr OrderBy

-- | Ascending order of this field or SqlExpression with nulls coming last.
--   Note that this is the same as normal ascending ordering in Postgres,
--   but it has been included for completeness.
ascNullsLast :: PersistField a => SqlExpr (Value a) -> SqlExpr OrderBy

-- | Descending order of this field or SqlExpression with nulls coming
--   first. Note that this is the same as normal ascending ordering in
--   Postgres, but it has been included for completeness.
descNullsFirst :: PersistField a => SqlExpr (Value a) -> SqlExpr OrderBy

-- | Descending order of this field or SqlExpression with nulls coming
--   last.
descNullsLast :: PersistField a => SqlExpr (Value a) -> SqlExpr OrderBy

-- | (Internal) Create a custom aggregate functions with aggregate mode
--   
--   <i>Do</i> <i>not</i> use this function directly, instead define a new
--   function and give it a type (see <a>unsafeSqlBinOp</a>)
unsafeSqlAggregateFunction :: UnsafeSqlFunctionArgument a => Builder -> AggMode -> a -> [OrderByClause] -> SqlExpr (Value b)
instance GHC.Internal.Show.Show Database.Esqueleto.PostgreSQL.AggMode


-- | This module contains PostgreSQL-specific JSON functions.
--   
--   A couple of things to keep in mind about this module:
--   
--   <ul>
--   <li>The <tt>Type</tt> column in the PostgreSQL documentation tables
--   are the types of the right operand, the left is always
--   <tt>jsonb</tt>.</li>
--   <li>Since these operators can all take <tt>NULL</tt> values as their
--   input, and most can also output <tt>NULL</tt> values (even when the
--   inputs are guaranteed to not be NULL), all <a>JSONB</a> values are
--   wrapped in <a>Maybe</a>. This also makes it easier to chain them. (cf.
--   <a>JSONBExpr</a>) Just use the <a>just</a> function to lift any
--   non-<a>Maybe</a> JSONB values in case it doesn't type check.</li>
--   <li>As long as the previous operator's resulting value is a
--   <a>JSONBExpr</a>, any other JSON operator can be used to transform the
--   JSON further. (e.g. <tt>[1,2,3] -&gt; 1 @&gt; 2</tt>)</li>
--   </ul>
--   
--   <i>The PostgreSQL version the functions work with are included</i>
--   <i>in their description.</i>
module Database.Esqueleto.PostgreSQL.JSON

-- | Newtype wrapper around any type with a JSON representation.
newtype JSONB a
JSONB :: a -> JSONB a
[unJSONB] :: JSONB a -> a

-- | <a>SqlExpr</a> of a NULL-able <a>JSONB</a> value. Hence the
--   <a>Maybe</a>.
--   
--   Note: NULL here is a PostgreSQL NULL, not a JSON <a>null</a>
type JSONBExpr a = SqlExpr Value Maybe JSONB a

-- | Convenience function to lift a regular value into a <a>JSONB</a>
--   expression.
jsonbVal :: (FromJSON a, ToJSON a) => a -> JSONBExpr a

-- | Used with certain JSON operators.
--   
--   This data type has <a>Num</a> and <a>IsString</a> instances for ease
--   of use by using integer and string literals.
--   
--   <pre>
--   &gt;&gt;&gt; 3 :: JSONAccessor
--   JSONIndex 3
--   
--   &gt;&gt;&gt; -3 :: JSONAccessor
--   JSONIndex -3
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; "name" :: JSONAccessor
--   JSONKey "name"
--   </pre>
--   
--   NOTE: DO NOT USE ANY OF THE <a>Num</a> METHODS ON THIS TYPE!
data JSONAccessor
JSONIndex :: Int -> JSONAccessor
JSONKey :: Text -> JSONAccessor

-- | <i>Requires PostgreSQL version &gt;= 9.3</i>
--   
--   This function extracts the jsonb value from a JSON array or object,
--   depending on whether you use an <tt>int</tt> or a <tt>text</tt>. (cf.
--   <a>JSONAccessor</a>)
--   
--   As long as the left operand is <tt>jsonb</tt>, this function will not
--   throw an exception, but will return <tt>NULL</tt> when an <tt>int</tt>
--   is used on anything other than a JSON array, or a <tt>text</tt> is
--   used on anything other than a JSON object.
--   
--   <h3><b>PostgreSQL Documentation</b></h3>
--   
--   <pre>
--       | Type | Description                                |  Example                                         | Example Result
--   ----+------+--------------------------------------------+--------------------------------------------------+----------------
--    -&gt; | int  | Get JSON array element (indexed from zero) | '[{"a":"foo"},{"b":"bar"},{"c":"baz"}]'::json-&gt;2 | {"c":"baz"}
--    -&gt; | text | Get JSON object field by key               | '{"a": {"b":"foo"}}'::json-&gt;<tt>a</tt>                  | {"b":"foo"}
--   </pre>
(->.) :: JSONBExpr a -> JSONAccessor -> JSONBExpr b
infixl 6 ->.

-- | <i>Requires PostgreSQL version &gt;= 9.3</i>
--   
--   Identical to <a>-&gt;.</a>, but the resulting DB type is a
--   <tt>text</tt>, so it could be chained with anything that uses
--   <tt>text</tt>.
--   
--   <b>CAUTION: if the "scalar" JSON value <tt>null</tt> is the result</b>
--   <b>of this function, PostgreSQL will interpret it as a</b>
--   <b>PostgreSQL <tt>NULL</tt> value, and will therefore be
--   <a>Nothing</a></b> <b>instead of (Just "null")</b>
--   
--   <h3><b>PostgreSQL Documentation</b></h3>
--   
--   <pre>
--        | Type | Description                    |  Example                    | Example Result
--   -----+------+--------------------------------+-----------------------------+----------------
--    -&gt;&gt; | int  | Get JSON array element as text | '[1,2,3]'::json-&gt;&gt;2         | 3
--    -&gt;&gt; | text | Get JSON object field as text  | '{"a":1,"b":2}'::json-&gt;&gt;<tt>b</tt> | 2
--   </pre>
(->>.) :: JSONBExpr a -> JSONAccessor -> SqlExpr (Value (Maybe Text))
infixl 6 ->>.

-- | <i>Requires PostgreSQL version &gt;= 9.3</i>
--   
--   This operator can be used to select a JSON value from deep inside
--   another one. It only works on objects and arrays and will result in
--   <tt>NULL</tt> (<a>Nothing</a>) when encountering any other JSON type.
--   
--   The <a>Text</a>s used in the right operand list will always select an
--   object field, but can also select an index from a JSON array if that
--   text is parsable as an integer.
--   
--   Consider the following:
--   
--   <pre>
--   x ^. TestBody #&gt;. ["0","1"]
--   </pre>
--   
--   The following JSON values in the <tt>test</tt> table's <tt>body</tt>
--   column will be affected:
--   
--   <pre>
--    Values in column                     | Resulting value
--   --------------------------------------+----------------------------
--   {"0":{"1":"Got it!"}}                 | "Got it!"
--   {"0":[null,["Got it!","Even here!"]]} | ["Got it!", "Even here!"]
--   [{"1":"Got it again!"}]               | "Got it again!"
--   [[null,{"Wow":"so deep!"}]]           | {"Wow": "so deep!"}
--   false                                 | NULL
--   "nope"                                | NULL
--   3.14                                  | NULL
--   </pre>
--   
--   <h3><b>PostgreSQL Documentation</b></h3>
--   
--   <pre>
--        | Type   | Description                       |  Example                                   | Example Result
--   -----+--------+-----------------------------------+--------------------------------------------+----------------
--    #&gt;  | text[] | Get JSON object at specified path | '{"a": {"b":{"c": "foo"}}}'::json#&gt;'{a,b}' | {"c": "foo"}
--   </pre>
(#>.) :: JSONBExpr a -> [Text] -> JSONBExpr b
infixl 6 #>.

-- | <i>Requires PostgreSQL version &gt;= 9.3</i>
--   
--   This function is to <a>#&gt;.</a> as <a>-&gt;&gt;.</a> is to
--   <a>-&gt;.</a>
--   
--   <b>CAUTION: if the "scalar" JSON value <tt>null</tt> is the result</b>
--   <b>of this function, PostgreSQL will interpret it as a</b>
--   <b>PostgreSQL <tt>NULL</tt> value, and will therefore be
--   <a>Nothing</a></b> <b>instead of (Just "null")</b>
--   
--   <h3><b>PostgreSQL Documentation</b></h3>
--   
--   <pre>
--        | Type   | Description                               |  Example                                    | Example Result
--   -----+--------+-------------------------------------------+---------------------------------------------+----------------
--    #&gt;&gt; | text[] | Get JSON object at specified path as text | '{"a":[1,2,3],"b":[4,5,6]}'::json#&gt;&gt;'{a,2}' | 3
--   </pre>
(#>>.) :: JSONBExpr a -> [Text] -> SqlExpr (Value (Maybe Text))
infixl 6 #>>.

-- | <i>Requires PostgreSQL version &gt;= 9.4</i>
--   
--   This operator checks for the JSON value on the right to be a subset of
--   the JSON value on the left.
--   
--   Examples of the usage of this operator can be found in the
--   Database.Persist.Postgresql.JSON module.
--   
--   (here:
--   <a>https://hackage.haskell.org/package/persistent-postgresql-2.10.0/docs/Database-Persist-Postgresql-JSON.html</a>)
--   
--   <h3><b>PostgreSQL Documentation</b></h3>
--   
--   <pre>
--       | Type  | Description                                                 |  Example
--   ----+-------+-------------------------------------------------------------+---------------------------------------------
--    @&gt; | jsonb | Does the left JSON value contain within it the right value? | '{"a":1, "b":2}'::jsonb @&gt; '{"b":2}'::jsonb
--   </pre>
(@>.) :: JSONBExpr a -> JSONBExpr b -> SqlExpr (Value Bool)
infixl 6 @>.

-- | <i>Requires PostgreSQL version &gt;= 9.4</i>
--   
--   This operator works the same as <a>@&gt;.</a>, just with the arguments
--   flipped. So it checks for the JSON value on the left to be a subset of
--   JSON value on the right.
--   
--   Examples of the usage of this operator can be found in the
--   Database.Persist.Postgresql.JSON module.
--   
--   (here:
--   <a>https://hackage.haskell.org/package/persistent-postgresql-2.10.0/docs/Database-Persist-Postgresql-JSON.html</a>)
--   
--   <h3><b>PostgreSQL Documentation</b></h3>
--   
--   <pre>
--       | Type  | Description                                              |  Example
--   ----+-------+----------------------------------------------------------+---------------------------------------------
--    &lt;@ | jsonb | Is the left JSON value contained within the right value? | '{"b":2}'::jsonb &lt;@ '{"a":1, "b":2}'::jsonb
--   </pre>
(<@.) :: JSONBExpr a -> JSONBExpr b -> SqlExpr (Value Bool)
infixl 6 <@.

-- | <i>Requires PostgreSQL version &gt;= 9.4</i>
--   
--   This operator checks if the given text is a top-level member of the
--   JSON value on the left. This means a top-level field in an object, a
--   top-level string in an array or just a string value.
--   
--   Examples of the usage of this operator can be found in the
--   Database.Persist.Postgresql.JSON module.
--   
--   (here:
--   <a>https://hackage.haskell.org/package/persistent-postgresql-2.10.0/docs/Database-Persist-Postgresql-JSON.html</a>)
--   
--   <h3><b>PostgreSQL Documentation</b></h3>
--   
--   <pre>
--      | Type | Description                                                     |  Example
--   ---+------+-----------------------------------------------------------------+-------------------------------
--    ? | text | Does the string exist as a top-level key within the JSON value? | '{"a":1, "b":2}'::jsonb ? <tt>b</tt>
--   </pre>
(?.) :: JSONBExpr a -> Text -> SqlExpr (Value Bool)
infixl 6 ?.

-- | <i>Requires PostgreSQL version &gt;= 9.4</i>
--   
--   This operator checks if <b>ANY</b> of the given texts is a top-level
--   member of the JSON value on the left. This means any top-level field
--   in an object, any top-level string in an array or just a string value.
--   
--   Examples of the usage of this operator can be found in the
--   Database.Persist.Postgresql.JSON module.
--   
--   (here:
--   <a>https://hackage.haskell.org/package/persistent-postgresql-2.10.0/docs/Database-Persist-Postgresql-JSON.html</a>)
--   
--   <h3><b>PostgreSQL Documentation</b></h3>
--   
--   <pre>
--       | Type   | Description                                            |  Example
--   ----+--------+--------------------------------------------------------+---------------------------------------------------
--    ?| | text[] | Do any of these array strings exist as top-level keys? | '{"a":1, "b":2, "c":3}'::jsonb ?| array[<tt>b</tt>, <tt>c</tt>]
--   </pre>
(?|.) :: JSONBExpr a -> [Text] -> SqlExpr (Value Bool)
infixl 6 ?|.

-- | <i>Requires PostgreSQL version &gt;= 9.4</i>
--   
--   This operator checks if <b>ALL</b> of the given texts are top-level
--   members of the JSON value on the left. This means a top-level field in
--   an object, a top-level string in an array or just a string value.
--   
--   Examples of the usage of this operator can be found in the
--   Database.Persist.Postgresql.JSON module.
--   
--   (here:
--   <a>https://hackage.haskell.org/package/persistent-postgresql-2.10.0/docs/Database-Persist-Postgresql-JSON.html</a>)
--   
--   <h3><b>PostgreSQL Documentation</b></h3>
--   
--   <pre>
--       | Type   | Description                                            |  Example
--   ----+--------+--------------------------------------------------------+----------------------------------------
--    ?&amp; | text[] | Do all of these array strings exist as top-level keys? | '["a", "b"]'::jsonb ?&amp; array[<tt>a</tt>, <tt>b</tt>]
--   </pre>
(?&.) :: JSONBExpr a -> [Text] -> SqlExpr (Value Bool)
infixl 6 ?&.

-- | <i>Requires PostgreSQL version &gt;= 9.5</i>
--   
--   This operator can remove a key from an object or a string element from
--   an array when using text, and remove certain elements by index from an
--   array when using integers.
--   
--   Negative integers delete counting from the end of the array. (e.g.
--   <tt>-1</tt> being the last element, <tt>-2</tt> being the second to
--   last, etc.)
--   
--   <b>CAUTION: THIS FUNCTION THROWS AN EXCEPTION WHEN USED ON ANYTHING
--   OTHER</b> <b>THAN OBJECTS OR ARRAYS WHEN USING TEXT, AND ANYTHING
--   OTHER THAN ARRAYS</b> <b>WHEN USING INTEGERS!</b>
--   
--   <h3><b>Objects and arrays</b></h3>
--   
--   <pre>
--   {"a": 3.14}            - "a"         == {}
--   {"a": "b"}             - "b"         == {"a": "b"}
--   {"a": 3.14}            - "a"         == {}
--   {"a": 3.14, "c": true} - "a"         == {"c": true}
--   ["a", 2, "c"]          - "a"         == [2, "c"] -- can remove strings from arrays
--   [true, "b", 5]         - 0           == ["b", 5]
--   [true, "b", 5]         - 3           == [true, "b", 5]
--   [true, "b", 5]         - -1          == [true, "b"]
--   [true, "b", 5]         - -4          == [true, "b", 5]
--   []                     - 1           == []
--   {"1": true}            - 1           == ERROR: cannot delete from object using integer index
--   1                      - &lt;anything&gt;  == ERROR: cannot delete from scalar
--   "a"                    - &lt;anything&gt;  == ERROR: cannot delete from scalar
--   true                   - &lt;anything&gt;  == ERROR: cannot delete from scalar
--   null                   - &lt;anything&gt;  == ERROR: cannot delete from scalar
--   </pre>
--   
--   <h3><b>PostgreSQL Documentation</b></h3>
--   
--   <pre>
--      | Type    | Description                                                            |  Example
--   ---+---------+------------------------------------------------------------------------+-------------------------------------------------
--    - | text    | Delete key/value pair or string element from left operand.             | '{"a": "b"}'::jsonb - <tt>a</tt>
--      |         | Key/value pairs are matched based on their key value.                  |
--    - | integer | Delete the array element with specified index (Negative integers count | '["a", "b"]'::jsonb - 1
--      |         | from the end). Throws an error if top level container is not an array. |
--   </pre>
(-.) :: JSONBExpr a -> JSONAccessor -> JSONBExpr b
infixl 6 -.

-- | <i>Requires PostgreSQL version &gt;= 10</i>
--   
--   Removes a set of keys from an object, or string elements from an
--   array.
--   
--   This is the same operator internally as <a>-.</a>, but the option to
--   use a <tt>text array</tt>, instead of <tt>text</tt> or
--   <tt>integer</tt> was only added in version 10. That's why this
--   function is seperate from <a>-.</a>
--   
--   NOTE: The following is equivalent:
--   
--   <pre>
--   {some JSON expression} -. "a" -. "b"
--   </pre>
--   
--   is equivalent to
--   
--   <pre>
--   {some JSON expression} --. ["a","b"]
--   </pre>
--   
--   <h3><b>PostgreSQL Documentation</b></h3>
--   
--   <pre>
--      | Type    | Description                                                            |  Example
--   ---+---------+------------------------------------------------------------------------+-------------------------------------------------
--    - | text[]  | Delete multiple key/value pairs or string elements from left operand.  | '{"a": "b", "c": "d"}'::jsonb - '{a,c}'::text[]
--      |         | Key/value pairs are matched based on their key value.                  |
--   </pre>
(--.) :: JSONBExpr a -> [Text] -> JSONBExpr b
infixl 6 --.

-- | <i>Requires PostgreSQL version &gt;= 9.5</i>
--   
--   This operator can remove elements nested in an object.
--   
--   If a <a>Text</a> is not parsable as a number when selecting in an
--   array (even when halfway through the selection) an exception will be
--   thrown.
--   
--   Negative integers delete counting from the end of an array. (e.g.
--   <tt>-1</tt> being the last element, <tt>-2</tt> being the second to
--   last, etc.)
--   
--   <b>CAUTION: THIS FUNCTION THROWS AN EXCEPTION WHEN USED</b> <b>ON
--   ANYTHING OTHER THAN OBJECTS OR ARRAYS, AND WILL</b> <b>ALSO THROW WHEN
--   TRYING TO SELECT AN ARRAY ELEMENT WITH</b> <b>A NON-INTEGER TEXT</b>
--   
--   <h3><b>Objects</b></h3>
--   
--   <pre>
--   {"a": 3.14, "b": null}        #- []        == {"a": 3.14, "b": null}
--   {"a": 3.14, "b": null}        #- ["a"]     == {"b": null}
--   {"a": 3.14, "b": null}        #- ["a","b"] == {"a": 3.14, "b": null}
--   {"a": {"b":false}, "b": null} #- ["a","b"] == {"a": {}, "b": null}
--   </pre>
--   
--   <h3><b>Arrays</b></h3>
--   
--   <pre>
--   [true, {"b":null}, 5]       #- []            == [true, {"b":null}, 5]
--   [true, {"b":null}, 5]       #- ["0"]         == [{"b":null}, 5]
--   [true, {"b":null}, 5]       #- ["b"]         == ERROR: path element at position 1 is not an integer: "b"
--   [true, {"b":null}, 5]       #- ["1","b"]     == [true, {}, 5]
--   [true, {"b":null}, 5]       #- ["-2","b"]    == [true, {}, 5]
--   {"a": {"b":[false,4,null]}} #- ["a","b","2"] == {"a": {"b":[false,4]}}
--   {"a": {"b":[false,4,null]}} #- ["a","b","c"] == ERROR: path element at position 3 is not an integer: "c"
--   </pre>
--   
--   <h3><b>Other values</b></h3>
--   
--   <pre>
--   1    #- {anything} == ERROR: cannot delete from scalar
--   "a"  #- {anything} == ERROR: cannot delete from scalar
--   true #- {anything} == ERROR: cannot delete from scalar
--   null #- {anything} == ERROR: cannot delete from scalar
--   </pre>
--   
--   <h3><b>PostgreSQL Documentation</b></h3>
--   
--   <pre>
--       | Type   | Description                                             |  Example
--   ----+--------+---------------------------------------------------------+------------------------------------
--    #- | text[] | Delete the field or element with specified path         | '["a", {"b":1}]'::jsonb #- '{1,b}'
--       |        | (for JSON arrays, negative integers count from the end) |
--   </pre>
(#-.) :: JSONBExpr a -> [Text] -> JSONBExpr b
infixl 6 #-.

-- | <i>Requires PostgreSQL version &gt;= 9.5</i>
--   
--   This operator concatenates two JSON values. The behaviour is
--   self-evident when used on two arrays, but the behaviour on different
--   combinations of JSON values might behave unexpectedly.
--   
--   <b>CAUTION: THIS FUNCTION THROWS AN EXCEPTION WHEN CONCATENATING</b>
--   <b>A JSON OBJECT WITH A JSON SCALAR VALUE!</b>
--   
--   <h3><b>Arrays</b></h3>
--   
--   This operator is a standard concatenation function when used on
--   arrays:
--   
--   <pre>
--   [1,2]   || [2,3]   == [1,2,2,3]
--   []      || [1,2,3] == [1,2,3]
--   [1,2,3] || []      == [1,2,3]
--   </pre>
--   
--   <h3><b>Objects</b></h3>
--   
--   When concatenating JSON objects with other JSON objects, the fields
--   from the JSON object on the right are added to the JSON object on the
--   left. When concatenating a JSON object with a JSON array, the object
--   will be inserted into the array; either on the left or right,
--   depending on the position relative to the operator.
--   
--   When concatening an object with a scalar value, an exception is
--   thrown.
--   
--   <pre>
--   {"a": 3.14}                    || {"b": true}         == {"a": 3.14, "b": true}
--   {"a": "b"}                     || {"a": null}         == {"a": null}
--   {"a": {"b": true, "c": false}} || {"a": {"b": false}} == {"a": {"b": false}}
--   {"a": 3.14}                    || [1,null]            == [{"a": 3.14},1,null]
--   [1,null]                       || {"a": 3.14}         == [1,null,{"a": 3.14}]
--   1                              || {"a": 3.14}         == ERROR: invalid concatenation of jsonb objects
--   {"a": 3.14}                    || false               == ERROR: invalid concatenation of jsonb objects
--   </pre>
--   
--   <h3><b>Scalar values</b></h3>
--   
--   Scalar values can be thought of as being singleton arrays when used
--   with this operator. This rule does not apply when concatenating with
--   JSON objects.
--   
--   <pre>
--   1          || null       == [1,null]
--   true       || "a"        == [true,"a"]
--   [1,2]      || false      == [1,2,false]
--   null       || [1,"a"]    == [null,1,"a"]
--   {"a":3.14} || true       == ERROR: invalid concatenation of jsonb objects
--   3.14       || {"a":3.14} == ERROR: invalid concatenation of jsonb objects
--   {"a":3.14} || [true]     == [{"a":3.14},true]
--   [false]    || {"a":3.14} == [false,{"a":3.14}]
--   </pre>
--   
--   <h3><b>PostgreSQL Documentation</b></h3>
--   
--   <pre>
--       | Type  | Description                                         |  Example
--   ----+-------+-----------------------------------------------------+--------------------------------------------
--    || | jsonb | Concatenate two jsonb values into a new jsonb value | '["a", "b"]'::jsonb || '["c", "d"]'::jsonb
--   </pre>
--   
--   <i>Note: The <tt>||</tt> operator concatenates the elements at the top
--   level of</i> <i>each of its operands. It does not operate
--   recursively.</i>
--   
--   <i>For example, if both operands are objects with a common key field
--   name,</i> <i>the value of the field in the result will just be the
--   value from the right</i> <i>hand operand.</i>
(||.) :: JSONBExpr a -> JSONBExpr b -> JSONBExpr c
infixl 6 ||.

module Database.Esqueleto.Record

-- | Takes the name of a Haskell record type and creates a variant of that
--   record prefixed with <tt>Sql</tt> which can be used in esqueleto
--   expressions. This reduces the amount of pattern matching on large
--   tuples required to interact with data extracted with esqueleto.
--   
--   Note that because the input record and the <tt>Sql</tt>-prefixed
--   record share field names, the <tt>{-# LANGUAGE DuplicateRecordFields
--   #-}</tt> extension is required in modules that use
--   <a>deriveEsqueletoRecord</a>. Additionally, the <tt>{-# LANGUAGE
--   TypeApplications #-}</tt> extension is required for some of the
--   generated code.
--   
--   Given the following record:
--   
--   <pre>
--   data MyRecord = MyRecord
--     { myName    :: <a>Text</a>
--     , myAge     :: <a>Maybe</a> <a>Int</a>
--     , myUser    :: <a>Entity</a> User
--     , myAddress :: <a>Maybe</a> (<a>Entity</a> Address)
--     }
--   </pre>
--   
--   <tt>$(<a>deriveEsqueletoRecord</a> ''MyRecord)</tt> will generate
--   roughly the following code:
--   
--   <pre>
--   data SqlMyRecord =
--     SqlMyRecord { myName    :: <a>SqlExpr</a> (<a>Value</a> Text)
--                 , myAge     :: <a>SqlExpr</a> (<a>Value</a> (<a>Maybe</a> Int))
--                 , myUser    :: <a>SqlExpr</a> (<a>Entity</a> User)
--                 , myAddress :: <a>SqlExpr</a> (<a>Maybe</a> (<a>Entity</a> Address))
--                 }
--   
--   instance <a>SqlSelect</a> SqlMyRecord MyRecord where
--     <a>sqlSelectCols</a>
--       identInfo
--       SqlMyRecord { myName    = myName
--                   , myAge     = myAge
--                   , myUser    = myUser
--                   , myAddress = myAddress
--                   } =
--       <a>sqlSelectCols</a> identInfo (myName :&amp; myAge :&amp; myUser :&amp; myAddress)
--   
--     <a>sqlSelectColCount</a> _ =
--       <a>sqlSelectColCount</a>
--         (<a>Proxy</a> @(   (<a>SqlExpr</a> (<a>Value</a> Text))
--                  :&amp; (<a>SqlExpr</a> (<a>Value</a> (<a>Maybe</a> Int)))
--                  :&amp; (<a>SqlExpr</a> (<a>Entity</a> User))
--                  :&amp; (<a>SqlExpr</a> (<a>Maybe</a> (<a>Entity</a> Address)))))
--   
--     <a>sqlSelectProcessRow</a> columns =
--       <a>first</a> ((<a>fromString</a> "Failed to parse MyRecord: ") &lt;&gt;)
--             (<a>evalStateT</a> process columns)
--       where
--         process = do
--           <a>Value</a> myName &lt;- <a>takeColumns</a> @(<a>SqlExpr</a> (<a>Value</a> Text))
--           <a>Value</a> myAge  &lt;- <a>takeColumns</a> @(<a>SqlExpr</a> (<a>Value</a> (<a>Maybe</a> Int)))
--           myUser       &lt;- <a>takeColumns</a> @(<a>SqlExpr</a> (<a>Entity</a> User))
--           myAddress    &lt;- <a>takeColumns</a> @(<a>SqlExpr</a> (<a>Maybe</a> (<a>Entity</a> Address)))
--           <a>pure</a> MyRecord { myName = myName
--                         , myAge = myAge
--                         , myUser = myUser
--                         , myAddress = myAddress
--                         }
--   </pre>
--   
--   Then, we could write a selection function to use the record in
--   queries:
--   
--   <pre>
--   getMyRecord :: <a>SqlPersistT</a> <a>IO</a> [MyRecord]
--   getMyRecord = <a>select</a> myRecordQuery
--   
--   myRecordQuery :: <a>SqlQuery</a> SqlMyRecord
--   myRecordQuery = do
--     user <a>:&amp;</a> address &lt;- <a>from</a> <a>$</a>
--       <a>table</a> @User
--         `<a>leftJoin</a>`
--         <a>table</a> @Address
--         `<a>on</a>` (do \(user <a>:&amp;</a> address) -&gt; user <a>^.</a> #address <a>==.</a> address <a>?.</a> #id)
--     <a>pure</a>
--       SqlMyRecord
--         { myName = <a>castString</a> <a>$</a> user <a>^.</a> #firstName
--         , myAge = <a>val</a> 10
--         , myUser = user
--         , myAddress = address
--         }
--   </pre>
deriveEsqueletoRecord :: Name -> Q [Dec]

-- | Takes the name of a Haskell record type and creates a variant of that
--   record based on the supplied settings which can be used in esqueleto
--   expressions. This reduces the amount of pattern matching on large
--   tuples required to interact with data extracted with esqueleto.
--   
--   This is a variant of <a>deriveEsqueletoRecord</a> which allows you to
--   avoid the use of <tt>{-# LANGUAGE DuplicateRecordFields #-}</tt>, by
--   configuring the <a>DeriveEsqueletoRecordSettings</a> used to generate
--   the SQL record.
deriveEsqueletoRecordWith :: DeriveEsqueletoRecordSettings -> Name -> Q [Dec]

-- | Codegen settings for <a>deriveEsqueletoRecordWith</a>.
data DeriveEsqueletoRecordSettings
DeriveEsqueletoRecordSettings :: (String -> String) -> (String -> String) -> (String -> String) -> (String -> String) -> DeriveEsqueletoRecordSettings

-- | Function applied to the Haskell record's type name and constructor
--   name to produce the SQL record's type name and constructor name.
[sqlNameModifier] :: DeriveEsqueletoRecordSettings -> String -> String

-- | Function applied to the Haskell record's type name and constructor
--   name to produce the <a>ToMaybe</a> record's type name and constructor
--   name.
[sqlMaybeNameModifier] :: DeriveEsqueletoRecordSettings -> String -> String

-- | Function applied to the Haskell record's field names to produce the
--   SQL record's field names.
[sqlFieldModifier] :: DeriveEsqueletoRecordSettings -> String -> String

-- | Function applied to the Haskell record's field names to produce the
--   <a>ToMaybe</a> SQL record's field names.
[sqlMaybeFieldModifier] :: DeriveEsqueletoRecordSettings -> String -> String

-- | The default codegen settings for <a>deriveEsqueletoRecord</a>.
--   
--   These defaults will cause you to require <tt>{-# LANGUAGE
--   DuplicateRecordFields #-}</tt> in certain cases (see
--   <a>deriveEsqueletoRecord</a>.) If you don't want to do this, change
--   the value of <a>sqlFieldModifier</a> so the field names of the
--   generated SQL record different from those of the Haskell record.
defaultDeriveEsqueletoRecordSettings :: DeriveEsqueletoRecordSettings

-- | Statefully parse some number of columns from a list of
--   <a>PersistValue</a>s, where the number of columns to parse is
--   determined by <a>sqlSelectColCount</a> for <tt>a</tt>.
--   
--   This is used to implement <a>sqlSelectProcessRow</a> for records
--   created with <a>deriveEsqueletoRecord</a>.
takeColumns :: SqlSelect a b => StateT [PersistValue] (Either Text) b

-- | Statefully parse some number of columns from a list of
--   <a>PersistValue</a>s, where the number of columns to parse is
--   determined by <a>sqlSelectColCount</a> for <tt>a</tt>.
--   
--   This is used to implement <a>sqlSelectProcessRow</a> for records
--   created with <a>deriveEsqueletoRecord</a>.
takeMaybeColumns :: SqlSelect a (ToMaybeT b) => StateT [PersistValue] (Either Text) (ToMaybeT b)


-- | This module contain SQLite-specific functions.
module Database.Esqueleto.SQLite

-- | (<tt>random()</tt>) Split out into database specific modules because
--   MySQL uses `rand()`.
--   
--   <i>Since: 2.6.0</i>
random_ :: (PersistField a, Num a) => SqlExpr (Value a)
