{-# LANGUAGE CPP #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeApplications #-}
{-# language DerivingStrategies, GeneralizedNewtypeDeriving #-}

{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE InstanceSigs #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}

{-# OPTIONS_GHC -fno-warn-redundant-constraints #-}

-- | This is an internal module, anything exported by this module
-- may change without a major version bump.  Please use only
-- "Database.Esqueleto" 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 where

import Control.Applicative ((<|>))
import Control.Arrow (first, (***))
import Control.Exception (Exception, throw, throwIO)
import Control.Monad (MonadPlus(..), guard, void)
import Control.Monad.IO.Class (MonadIO(..))
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Resource (MonadResource, release)
import Data.Acquire (Acquire, allocateAcquire, with)
import Data.Int (Int64)
import Data.List (intersperse)
import Data.List.NonEmpty (NonEmpty(..))
import qualified Data.List.NonEmpty as NEL
import qualified Data.Maybe as Maybe
#if __GLASGOW_HASKELL__ < 804
import Data.Semigroup
#endif
import qualified Control.Monad.Trans.Reader as R
import qualified Control.Monad.Trans.State as S
import qualified Control.Monad.Trans.Writer as W
import qualified Data.ByteString as B
import Data.Coerce (coerce)
import qualified Data.Conduit as C
import qualified Data.Conduit.List as CL
import qualified Data.HashSet as HS
import Data.Kind (Type)
import qualified Data.List as List
import qualified Data.Map.Strict as Map
import qualified Data.Monoid as Monoid
import Data.Proxy (Proxy(..))
import Data.Set (Set)
import qualified Data.Set as Set
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Builder as TLB
import Data.Typeable (Typeable)
import Database.Esqueleto.Internal.ExprParser (TableAccess(..), parseOnExpr)
import Database.Esqueleto.Internal.PersistentImport
import Database.Persist (EntityNameDB(..), FieldNameDB(..), SymbolToField(..))
import qualified Database.Persist
import Database.Persist.Sql.Util
       ( entityColumnCount
       , isIdField
       , keyAndEntityColumnNames
       , parseEntityValues
       )
import Database.Persist.SqlBackend
import GHC.Records
import GHC.TypeLits
import Text.Blaze.Html (Html)

-- | (Internal) Start a 'from' query with an entity. 'from'
-- does two kinds of magic using 'fromStart', 'fromJoin' and
-- 'fromFinish':
--
--   1.  The simple but tedious magic of allowing tuples to be
--   used.
--
--   2.  The more advanced magic of creating @JOIN@s.  The
--   @JOIN@ is processed from right to left.  The rightmost
--   entity of the @JOIN@ is created with 'fromStart'.  Each
--   @JOIN@ step is then translated into a call to 'fromJoin'.
--   In the end, 'fromFinish' is called to materialize the
--   @JOIN@.
fromStart
    :: forall a.
    ( PersistEntity a
    , BackendCompatible SqlBackend (PersistEntityBackend a)
    )
    => SqlQuery (PreprocessedFrom (SqlExpr (Entity a)))
fromStart :: forall a.
(PersistEntity a,
 BackendCompatible SqlBackend (PersistEntityBackend a)) =>
SqlQuery (PreprocessedFrom (SqlExpr (Entity a)))
fromStart = do
    let ed :: EntityDef
ed = forall record (proxy :: * -> *).
PersistEntity record =>
proxy record -> EntityDef
entityDef (forall {k} (t :: k). Proxy t
Proxy :: Proxy a)
    Ident
ident <- DBName -> SqlQuery Ident
newIdentFor (coerce :: forall a b. Coercible a b => a -> b
coerce forall a b. (a -> b) -> a -> b
$ EntityDef -> EntityNameDB
getEntityDBName EntityDef
ed)
    let ret :: SqlExpr (Entity a)
ret = forall ent. PersistEntity ent => Ident -> SqlExpr (Entity ent)
unsafeSqlEntity Ident
ident
        f' :: FromClause
f' = Ident -> EntityDef -> FromClause
FromStart Ident
ident EntityDef
ed
    forall (m :: * -> *) a. Monad m => a -> m a
return (forall a. a -> FromClause -> PreprocessedFrom a
PreprocessedFrom SqlExpr (Entity a)
ret FromClause
f')

-- | Copied from @persistent@
newtype DBName = DBName { DBName -> Text
unDBName :: T.Text }

-- | (Internal) Same as 'fromStart', but entity may be missing.
fromStartMaybe
    :: ( PersistEntity a
       , BackendCompatible SqlBackend (PersistEntityBackend a)
       )
    => SqlQuery (PreprocessedFrom (SqlExpr (Maybe (Entity a))))
fromStartMaybe :: forall a.
(PersistEntity a,
 BackendCompatible SqlBackend (PersistEntityBackend a)) =>
SqlQuery (PreprocessedFrom (SqlExpr (Maybe (Entity a))))
fromStartMaybe = forall a.
PreprocessedFrom (SqlExpr (Entity a))
-> PreprocessedFrom (SqlExpr (Maybe (Entity a)))
maybelize forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> forall a.
(PersistEntity a,
 BackendCompatible SqlBackend (PersistEntityBackend a)) =>
SqlQuery (PreprocessedFrom (SqlExpr (Entity a)))
fromStart
  where
    maybelize
        :: PreprocessedFrom (SqlExpr (Entity a))
        -> PreprocessedFrom (SqlExpr (Maybe (Entity a)))
    maybelize :: forall a.
PreprocessedFrom (SqlExpr (Entity a))
-> PreprocessedFrom (SqlExpr (Maybe (Entity a)))
maybelize (PreprocessedFrom SqlExpr (Entity a)
e FromClause
f') = forall a. a -> FromClause -> PreprocessedFrom a
PreprocessedFrom (coerce :: forall a b. Coercible a b => a -> b
coerce SqlExpr (Entity a)
e) FromClause
f'

-- | (Internal) Do a @JOIN@.
fromJoin
    :: IsJoinKind join
    => PreprocessedFrom a
    -> PreprocessedFrom b
    -> SqlQuery (PreprocessedFrom (join a b))
fromJoin :: forall (join :: * -> * -> *) a b.
IsJoinKind join =>
PreprocessedFrom a
-> PreprocessedFrom b -> SqlQuery (PreprocessedFrom (join a b))
fromJoin (PreprocessedFrom a
lhsRet FromClause
lhsFrom)
         (PreprocessedFrom b
rhsRet FromClause
rhsFrom) = forall a.
WriterT SideData (StateT IdentState Identity) a -> SqlQuery a
Q forall a b. (a -> b) -> a -> b
$ do
    let ret :: join a b
ret = forall (join :: * -> * -> *) a b.
IsJoinKind join =>
a -> b -> join a b
smartJoin a
lhsRet b
rhsRet
        from' :: FromClause
from' =
            FromClause
-> JoinKind
-> FromClause
-> Maybe (SqlExpr (Value Bool))
-> FromClause
FromJoin
                FromClause
lhsFrom             -- LHS
                (forall (join :: * -> * -> *) a b.
IsJoinKind join =>
join a b -> JoinKind
reifyJoinKind join a b
ret) -- JOIN
                FromClause
rhsFrom             -- RHS
                forall a. Maybe a
Nothing             -- ON
    forall (m :: * -> *) a. Monad m => a -> m a
return (forall a. a -> FromClause -> PreprocessedFrom a
PreprocessedFrom join a b
ret FromClause
from')

-- | (Internal) Finish a @JOIN@.
fromFinish
  :: PreprocessedFrom a
  -> SqlQuery a
fromFinish :: forall a. PreprocessedFrom a -> SqlQuery a
fromFinish (PreprocessedFrom a
ret FromClause
f') = forall a.
WriterT SideData (StateT IdentState Identity) a -> SqlQuery a
Q forall a b. (a -> b) -> a -> b
$ do
    forall (m :: * -> *) w. Monad m => w -> WriterT w m ()
W.tell forall a. Monoid a => a
mempty { sdFromClause :: [FromClause]
sdFromClause = [FromClause
f'] }
    forall (m :: * -> *) a. Monad m => a -> m a
return a
ret

-- | @WHERE@ clause: restrict the query's result.
where_ :: SqlExpr (Value Bool) -> SqlQuery ()
where_ :: SqlExpr (Value Bool) -> SqlQuery ()
where_ SqlExpr (Value Bool)
expr = forall a.
WriterT SideData (StateT IdentState Identity) a -> SqlQuery a
Q forall a b. (a -> b) -> a -> b
$ forall (m :: * -> *) w. Monad m => w -> WriterT w m ()
W.tell forall a. Monoid a => a
mempty { sdWhereClause :: WhereClause
sdWhereClause = SqlExpr (Value Bool) -> WhereClause
Where SqlExpr (Value Bool)
expr }

-- | An @ON@ clause, useful to describe how two tables are related. Cross joins
-- and tuple-joins do not need an 'on' clause, but 'InnerJoin' and the various
-- outer joins do.
--
-- "Database.Esqueleto.Experimental" in version 4.0.0.0 of the library. The
-- @Experimental@ 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 'on' clause (or include too many!) then a runtime
-- exception will be thrown.
--
-- As an example, consider this simple join:
--
-- @
-- 'select' $
-- 'from' $ \\(foo `'InnerJoin`` bar) -> do
--   'on' (foo '^.' FooId '==.' bar '^.' BarFooId)
--   ...
-- @
--
-- We need to specify the clause for joining the two columns together. If we had
-- this:
--
-- @
-- 'select' $
-- 'from' $ \\(foo `'CrossJoin`` bar) -> do
--   ...
-- @
--
-- Then we can safely omit the 'on' clause, because the cross join will make
-- pairs of all records possible.
--
-- You can do multiple 'on' clauses in a query. This query joins three tables,
-- and has two 'on' clauses:
--
-- @
-- 'select' $
-- 'from' $ \\(foo `'InnerJoin`` bar `'InnerJoin`` baz) -> do
--   'on' (baz '^.' BazId '==.' bar '^.' BarBazId)
--   'on' (foo '^.' FooId '==.' bar '^.' BarFooId)
--   ...
-- @
--
-- Old versions of esqueleto required that you provide the 'on' clauses in
-- reverse order. This restriction has been lifted - you can now provide 'on'
-- clauses in any order, and the SQL should work itself out. The above query is
-- now totally equivalent to this:
--
-- @
-- 'select' $
-- 'from' $ \\(foo `'InnerJoin`` bar `'InnerJoin`` baz) -> do
--   'on' (foo '^.' FooId '==.' bar '^.' BarFooId)
--   'on' (baz '^.' BazId '==.' bar '^.' BarBazId)
--   ...
-- @
on :: SqlExpr (Value Bool) -> SqlQuery ()
on :: SqlExpr (Value Bool) -> SqlQuery ()
on SqlExpr (Value Bool)
expr = forall a.
WriterT SideData (StateT IdentState Identity) a -> SqlQuery a
Q forall a b. (a -> b) -> a -> b
$ forall (m :: * -> *) w. Monad m => w -> WriterT w m ()
W.tell forall a. Monoid a => a
mempty { sdFromClause :: [FromClause]
sdFromClause = [SqlExpr (Value Bool) -> FromClause
OnClause SqlExpr (Value Bool)
expr] }

-- | @GROUP BY@ clause. You can enclose multiple columns
-- in a tuple.
--
-- @
-- select $ 'from' \\(foo `'InnerJoin`` bar) -> do
--   'on' (foo '^.' FooBarId '==.' bar '^.' BarId)
--   'groupBy' (bar '^.' BarId, bar '^.' BarName)
--   return (bar '^.' BarId, bar '^.' BarName, countRows)
-- @
--
-- With groupBy you can sort by aggregate functions, like so
-- (we used @let@ to restrict the more general 'countRows' to
-- @SqlSqlExpr (Value Int)@ to avoid ambiguity---the second use of
-- 'countRows' has its type restricted by the @:: Int@ below):
--
-- @
-- r \<- select $ 'from' \\(foo `'InnerJoin`` bar) -> do
--   'on' (foo '^.' FooBarId '==.' bar '^.' BarId)
--   'groupBy' $ bar '^.' BarName
--   let countRows' = 'countRows'
--   'orderBy' ['asc' countRows']
--   return (bar '^.' BarName, countRows')
-- forM_ r $ \\('Value' name, 'Value' count) -> do
--   print name
--   print (count :: Int)
-- @
--
-- === Need more columns?
--
-- The 'ToSomeValues' class is defined for 'SqlExpr' and tuples of 'SqlExpr'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 'groupBy' call like this:
--
-- @
-- groupBy (e0, e1, e2, e3, e4, e5, e6, e7)
-- @
--
-- This is the biggest you can get with a single tuple. However, you can easily
-- nest the tuples to add more:
--
-- @
-- groupBy ((e0, e1, e2, e3, e4, e5, e6, e7), e8, e9)
-- @
groupBy :: (ToSomeValues a) => a -> SqlQuery ()
groupBy :: forall a. ToSomeValues a => a -> SqlQuery ()
groupBy a
expr = forall a.
WriterT SideData (StateT IdentState Identity) a -> SqlQuery a
Q forall a b. (a -> b) -> a -> b
$ forall (m :: * -> *) w. Monad m => w -> WriterT w m ()
W.tell forall a. Monoid a => a
mempty { sdGroupByClause :: GroupByClause
sdGroupByClause = [SomeValue] -> GroupByClause
GroupBy forall a b. (a -> b) -> a -> b
$ forall a. ToSomeValues a => a -> [SomeValue]
toSomeValues a
expr }

-- | An alias for 'groupBy' that avoids conflict with the term from "Data.List"
-- 'Data.List.groupBy'.
--
-- @since 3.5.10.0
groupBy_ :: (ToSomeValues a) => a -> SqlQuery ()
groupBy_ :: forall a. ToSomeValues a => a -> SqlQuery ()
groupBy_  = forall a. ToSomeValues a => a -> SqlQuery ()
groupBy

-- | @ORDER BY@ clause. See also 'asc' and 'desc'.
--
-- Multiple calls to 'orderBy' get concatenated on the final
-- query, including 'distinctOnOrderBy'.
orderBy :: [SqlExpr OrderBy] -> SqlQuery ()
orderBy :: [SqlExpr OrderBy] -> SqlQuery ()
orderBy [SqlExpr OrderBy]
exprs = forall a.
WriterT SideData (StateT IdentState Identity) a -> SqlQuery a
Q forall a b. (a -> b) -> a -> b
$ forall (m :: * -> *) w. Monad m => w -> WriterT w m ()
W.tell forall a. Monoid a => a
mempty { sdOrderByClause :: [SqlExpr OrderBy]
sdOrderByClause = [SqlExpr OrderBy]
exprs }

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

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

orderByExpr :: TLB.Builder -> SqlExpr (Value a) -> SqlExpr OrderBy
orderByExpr :: forall a. Builder -> SqlExpr (Value a) -> SqlExpr OrderBy
orderByExpr Builder
orderByType (ERaw SqlExprMeta
m NeedParens -> IdentInfo -> (Builder, [PersistValue])
f)
  | Just IdentInfo -> [Builder]
fields <- SqlExprMeta -> Maybe (IdentInfo -> [Builder])
sqlExprMetaCompositeFields SqlExprMeta
m =
        forall a.
SqlExprMeta
-> (NeedParens -> IdentInfo -> (Builder, [PersistValue]))
-> SqlExpr a
ERaw SqlExprMeta
noMeta forall a b. (a -> b) -> a -> b
$ \NeedParens
_ IdentInfo
info ->
            let fs :: [Builder]
fs = IdentInfo -> [Builder]
fields IdentInfo
info
                vals :: [[a]]
vals = forall a. a -> [a]
repeat []
            in forall a. Monoid a => [(Builder, a)] -> (Builder, a)
uncommas' forall a b. (a -> b) -> a -> b
$ forall a b. [a] -> [b] -> [(a, b)]
zip (forall a b. (a -> b) -> [a] -> [b]
map (forall a. Semigroup a => a -> a -> a
<> Builder
orderByType) [Builder]
fs) forall {a}. [[a]]
vals
  | Bool
otherwise =
      forall a.
SqlExprMeta
-> (NeedParens -> IdentInfo -> (Builder, [PersistValue]))
-> SqlExpr a
ERaw SqlExprMeta
noMeta forall a b. (a -> b) -> a -> b
$ \NeedParens
_ IdentInfo
info ->
          forall (a :: * -> * -> *) b c d.
Arrow a =>
a b c -> a (b, d) (c, d)
first (forall a. Semigroup a => a -> a -> a
<> Builder
orderByType) forall a b. (a -> b) -> a -> b
$ NeedParens -> IdentInfo -> (Builder, [PersistValue])
f NeedParens
Never IdentInfo
info

-- | @LIMIT@.  Limit the number of returned rows.
limit :: Int64 -> SqlQuery ()
limit :: Int64 -> SqlQuery ()
limit  Int64
n = forall a.
WriterT SideData (StateT IdentState Identity) a -> SqlQuery a
Q forall a b. (a -> b) -> a -> b
$ forall (m :: * -> *) w. Monad m => w -> WriterT w m ()
W.tell forall a. Monoid a => a
mempty { sdLimitClause :: LimitClause
sdLimitClause = Maybe Int64 -> Maybe Int64 -> LimitClause
Limit (forall a. a -> Maybe a
Just Int64
n) forall a. Maybe a
Nothing  }

-- | @OFFSET@.  Usually used with 'limit'.
offset :: Int64 -> SqlQuery ()
offset :: Int64 -> SqlQuery ()
offset Int64
n = forall a.
WriterT SideData (StateT IdentState Identity) a -> SqlQuery a
Q forall a b. (a -> b) -> a -> b
$ forall (m :: * -> *) w. Monad m => w -> WriterT w m ()
W.tell forall a. Monoid a => a
mempty { sdLimitClause :: LimitClause
sdLimitClause = Maybe Int64 -> Maybe Int64 -> LimitClause
Limit forall a. Maybe a
Nothing  (forall a. a -> Maybe a
Just Int64
n) }

-- | @DISTINCT@.  Change the current @SELECT@ into @SELECT
-- DISTINCT@.  For example:
--
-- @
-- select $ distinct $
--   'from' \\foo -> do
--   ...
-- @
--
-- Note that this also has the same effect:
--
-- @
-- select $
--   'from' \\foo -> do
--   distinct (return ())
--   ...
-- @
--
-- @since 2.2.4
distinct :: SqlQuery a -> SqlQuery a
distinct :: forall a. SqlQuery a -> SqlQuery a
distinct SqlQuery a
act = forall a.
WriterT SideData (StateT IdentState Identity) a -> SqlQuery a
Q (forall (m :: * -> *) w. Monad m => w -> WriterT w m ()
W.tell forall a. Monoid a => a
mempty { sdDistinctClause :: DistinctClause
sdDistinctClause = DistinctClause
DistinctStandard }) forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> SqlQuery a
act

-- | @DISTINCT ON@.  Change the current @SELECT@ into
-- @SELECT DISTINCT ON (SqlExpressions)@.  For example:
--
-- @
-- select $
--   'from' \\foo ->
--   'distinctOn' ['don' (foo ^. FooName), 'don' (foo ^. FooState)] $ do
--   ...
-- @
--
-- You can also chain different calls to 'distinctOn'.  The
-- above is equivalent to:
--
-- @
-- select $
--   'from' \\foo ->
--   'distinctOn' ['don' (foo ^. FooName)] $
--   'distinctOn' ['don' (foo ^. FooState)] $ do
--   ...
-- @
--
-- Each call to 'distinctOn' adds more SqlExpressions.  Calls to
-- 'distinctOn' override any calls to 'distinct'.
--
-- Note that PostgreSQL requires the SqlExpressions on @DISTINCT
-- ON@ to be the first ones to appear on a @ORDER BY@.  This is
-- not managed automatically by esqueleto, keeping its spirit
-- of trying to be close to raw SQL.
--
-- Supported by PostgreSQL only.
--
-- @since 2.2.4
distinctOn :: [SqlExpr DistinctOn] -> SqlQuery a -> SqlQuery a
distinctOn :: forall a. [SqlExpr DistinctOn] -> SqlQuery a -> SqlQuery a
distinctOn [SqlExpr DistinctOn]
exprs SqlQuery a
act = forall a.
WriterT SideData (StateT IdentState Identity) a -> SqlQuery a
Q (forall (m :: * -> *) w. Monad m => w -> WriterT w m ()
W.tell forall a. Monoid a => a
mempty { sdDistinctClause :: DistinctClause
sdDistinctClause = [SqlExpr DistinctOn] -> DistinctClause
DistinctOn [SqlExpr DistinctOn]
exprs }) forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> SqlQuery a
act

-- | Erase an SqlExpression's type so that it's suitable to
-- be used by 'distinctOn'.
--
-- @since 2.2.4
don :: SqlExpr (Value a) -> SqlExpr DistinctOn
don :: forall a. SqlExpr (Value a) -> SqlExpr DistinctOn
don = coerce :: forall a b. Coercible a b => a -> b
coerce

-- | A convenience function that calls both 'distinctOn' and
-- 'orderBy'.  In other words,
--
-- @
-- 'distinctOnOrderBy' [asc foo, desc bar, desc quux] $ do
--   ...
-- @
--
-- is the same as:
--
-- @
-- 'distinctOn' [don foo, don  bar, don  quux] $ do
--   'orderBy'  [asc foo, desc bar, desc quux]
--   ...
-- @
--
-- @since 2.2.4
distinctOnOrderBy :: [SqlExpr OrderBy] -> SqlQuery a -> SqlQuery a
distinctOnOrderBy :: forall a. [SqlExpr OrderBy] -> SqlQuery a -> SqlQuery a
distinctOnOrderBy [SqlExpr OrderBy]
exprs SqlQuery a
act =
    forall a. [SqlExpr DistinctOn] -> SqlQuery a -> SqlQuery a
distinctOn (SqlExpr OrderBy -> SqlExpr DistinctOn
toDistinctOn forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> [SqlExpr OrderBy]
exprs) forall a b. (a -> b) -> a -> b
$ do
        [SqlExpr OrderBy] -> SqlQuery ()
orderBy [SqlExpr OrderBy]
exprs
        SqlQuery a
act
  where
    toDistinctOn :: SqlExpr OrderBy -> SqlExpr DistinctOn
    toDistinctOn :: SqlExpr OrderBy -> SqlExpr DistinctOn
toDistinctOn (ERaw SqlExprMeta
m NeedParens -> IdentInfo -> (Builder, [PersistValue])
f) = forall a.
SqlExprMeta
-> (NeedParens -> IdentInfo -> (Builder, [PersistValue]))
-> SqlExpr a
ERaw SqlExprMeta
m forall a b. (a -> b) -> a -> b
$ \NeedParens
p IdentInfo
info ->
        let (Builder
b, [PersistValue]
vals) = NeedParens -> IdentInfo -> (Builder, [PersistValue])
f NeedParens
p IdentInfo
info
        in  ( Text -> Builder
TLB.fromLazyText
              forall a b. (a -> b) -> a -> b
$ Text -> Text -> Text -> Text
TL.replace Text
" DESC" Text
""
              forall a b. (a -> b) -> a -> b
$ Text -> Text -> Text -> Text
TL.replace Text
" ASC" Text
""
              forall a b. (a -> b) -> a -> b
$ Builder -> Text
TLB.toLazyText Builder
b
            , [PersistValue]
vals )

-- | @ORDER BY random()@ clause.
--
-- @since 1.3.10
rand :: SqlExpr OrderBy
rand :: SqlExpr OrderBy
rand = forall a.
SqlExprMeta
-> (NeedParens -> IdentInfo -> (Builder, [PersistValue]))
-> SqlExpr a
ERaw SqlExprMeta
noMeta forall a b. (a -> b) -> a -> b
$ \NeedParens
_ IdentInfo
_ -> (Builder
"RANDOM()", [])

-- | @HAVING@.
--
-- @since 1.2.2
having :: SqlExpr (Value Bool) -> SqlQuery ()
having :: SqlExpr (Value Bool) -> SqlQuery ()
having SqlExpr (Value Bool)
expr = forall a.
WriterT SideData (StateT IdentState Identity) a -> SqlQuery a
Q forall a b. (a -> b) -> a -> b
$ forall (m :: * -> *) w. Monad m => w -> WriterT w m ()
W.tell forall a. Monoid a => a
mempty { sdHavingClause :: WhereClause
sdHavingClause = SqlExpr (Value Bool) -> WhereClause
Where SqlExpr (Value Bool)
expr }

-- | Add a locking clause to the query.  Please read
-- 'LockingKind' documentation and your RDBMS manual.
-- Unsafe since not all locking clauses are implemented for every RDBMS
--
-- If multiple calls to 'locking' are made on the same query,
-- the last one is used.
--
-- @since 2.2.7
locking :: LockingKind -> SqlQuery ()
locking :: LockingKind -> SqlQuery ()
locking LockingKind
kind = LockingClause -> SqlQuery ()
putLocking forall a b. (a -> b) -> a -> b
$ LockingKind -> LockingClause
LegacyLockingClause LockingKind
kind

-- | Helper to add a any type of locking clause to a query
--
-- @since 3.5.9.0
putLocking :: LockingClause -> SqlQuery ()
putLocking :: LockingClause -> SqlQuery ()
putLocking LockingClause
clause = forall a.
WriterT SideData (StateT IdentState Identity) a -> SqlQuery a
Q forall a b. (a -> b) -> a -> b
$ forall (m :: * -> *) w. Monad m => w -> WriterT w m ()
W.tell forall a. Monoid a => a
mempty { sdLockingClause :: LockingClause
sdLockingClause = LockingClause
clause }

{-#
  DEPRECATED
    sub_select
    "sub_select \n \
sub_select is an unsafe function to use. If used with a SqlQuery that \n \
returns 0 results, then it may return NULL despite not mentioning Maybe \n \
in the return type. If it returns more than 1 result, then it will throw a \n \
SQL error.\n\n Instead, consider using one of the following alternatives: \n \
- subSelect: attaches a LIMIT 1 and the Maybe return type, totally safe.  \n \
- subSelectMaybe: Attaches a LIMIT 1, useful for a query that already \n \
  has a Maybe in the return type. \n \
- subSelectCount: Performs a count of the query - this is always safe. \n \
- subSelectUnsafe: Performs no checks or guarantees. Safe to use with \n \
  countRows and friends."
  #-}
-- | Execute a subquery @SELECT@ in an SqlExpression.  Returns a
-- simple value so should be used only when the @SELECT@ query
-- is guaranteed to return just one row.
--
-- Deprecated in 3.2.0.
sub_select :: PersistField a => SqlQuery (SqlExpr (Value a)) -> SqlExpr (Value a)
sub_select :: forall a.
PersistField a =>
SqlQuery (SqlExpr (Value a)) -> SqlExpr (Value a)
sub_select         = forall a.
PersistField a =>
Mode -> SqlQuery (SqlExpr (Value a)) -> SqlExpr (Value a)
sub Mode
SELECT

-- | Execute a subquery @SELECT@ in a 'SqlExpr'. The query passed to this
-- function will only return a single result - it has a @LIMIT 1@ passed in to
-- the query to make it safe, and the return type is 'Maybe' to indicate that
-- the subquery might result in 0 rows.
--
-- If you find yourself writing @'joinV' . 'subSelect'@, then consider using
-- 'subSelectMaybe'.
--
-- If you're performing a 'countRows', then you can use 'subSelectCount' 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 'subSelectUnsafe', along with a comment explaining why it is safe.
--
-- @since 3.2.0
subSelect
  :: PersistField a
  => SqlQuery (SqlExpr (Value a))
  -> SqlExpr (Value (Maybe a))
subSelect :: forall a.
PersistField a =>
SqlQuery (SqlExpr (Value a)) -> SqlExpr (Value (Maybe a))
subSelect SqlQuery (SqlExpr (Value a))
query = forall typ. SqlExpr (Value typ) -> SqlExpr (Value (Maybe typ))
just (forall a.
PersistField a =>
SqlQuery (SqlExpr (Value a)) -> SqlExpr (Value a)
subSelectUnsafe (SqlQuery (SqlExpr (Value a))
query forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* Int64 -> SqlQuery ()
limit Int64
1))

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

-- | Performs a @COUNT@ of the given query in a @subSelect@ manner. This is
-- always guaranteed to return a result value, and is completely safe.
--
-- @since 3.2.0
subSelectCount
    :: (Num a, PersistField a)
    => SqlQuery ignored
    -> SqlExpr (Value a)
subSelectCount :: forall a ignored.
(Num a, PersistField a) =>
SqlQuery ignored -> SqlExpr (Value a)
subSelectCount SqlQuery ignored
query =
    forall a.
PersistField a =>
SqlQuery (SqlExpr (Value a)) -> SqlExpr (Value a)
subSelectUnsafe forall a b. (a -> b) -> a -> b
$ do
        ignored
_ <- SqlQuery ignored
query
        forall (f :: * -> *) a. Applicative f => a -> f a
pure forall a. Num a => SqlExpr (Value a)
countRows

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

-- | 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:
--
-- @
-- User
--   profile ProfileId
--
-- Profile
--   name    Text
-- @
--
-- The following query will return the name of the user.
--
-- @
-- getUserWithName =
--     'select' $
--     'from' $ \user ->
--     'pure' (user, 'subSelectForeign' user UserProfile (^. ProfileName)
-- @
--
-- @since 3.2.0
subSelectForeign
    ::
    ( BackendCompatible SqlBackend (PersistEntityBackend val1)
    , PersistEntity val1, PersistEntity val2, PersistField a
    )
    => SqlExpr (Entity val2)
    -- ^ An expression representing the table you have access to now.
    -> EntityField val2 (Key val1)
    -- ^ The foreign key field on the table.
    -> (SqlExpr (Entity val1) -> SqlExpr (Value a))
    -- ^ A function to extract a value from the foreign reference table.
    -> SqlExpr (Value a)
subSelectForeign :: forall val1 val2 a.
(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)
subSelectForeign SqlExpr (Entity val2)
expr EntityField val2 (Key val1)
foreignKey SqlExpr (Entity val1) -> SqlExpr (Value a)
k =
    forall a.
PersistField a =>
SqlQuery (SqlExpr (Value a)) -> SqlExpr (Value a)
subSelectUnsafe forall a b. (a -> b) -> a -> b
$
    forall a b. From a => (a -> SqlQuery b) -> SqlQuery b
from forall a b. (a -> b) -> a -> b
$ \SqlExpr (Entity val1)
table -> do
    SqlExpr (Value Bool) -> SqlQuery ()
where_ forall a b. (a -> b) -> a -> b
$ SqlExpr (Entity val2)
expr forall typ val.
(PersistEntity val, PersistField typ) =>
SqlExpr (Entity val) -> EntityField val typ -> SqlExpr (Value typ)
^. EntityField val2 (Key val1)
foreignKey forall typ.
PersistField typ =>
SqlExpr (Value typ) -> SqlExpr (Value typ) -> SqlExpr (Value Bool)
==. SqlExpr (Entity val1)
table forall typ val.
(PersistEntity val, PersistField typ) =>
SqlExpr (Entity val) -> EntityField val typ -> SqlExpr (Value typ)
^. forall record.
PersistEntity record =>
EntityField record (Key record)
persistIdField
    forall (f :: * -> *) a. Applicative f => a -> f a
pure (SqlExpr (Entity val1) -> SqlExpr (Value a)
k SqlExpr (Entity val1)
table)

-- | Execute a subquery @SELECT@ in a 'SqlExpr'. This function is unsafe,
-- because it can throw runtime exceptions in two cases:
--
-- 1. If the query passed has 0 result rows, then it will return a @NULL@ value.
--    The @persistent@ parsing operations will fail on an unexpected @NULL@.
-- 2. 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".
--
-- This function is safe if you guarantee that exactly one row will be returned,
-- or if the result already has a 'Maybe' type for some reason.
--
-- For variants with the safety encoded already, see 'subSelect' and
-- 'subSelectMaybe'. For the most common safe use of this, see 'subSelectCount'.
--
-- @since 3.2.0
subSelectUnsafe :: PersistField a => SqlQuery (SqlExpr (Value a)) -> SqlExpr (Value a)
subSelectUnsafe :: forall a.
PersistField a =>
SqlQuery (SqlExpr (Value a)) -> SqlExpr (Value a)
subSelectUnsafe = forall a.
PersistField a =>
Mode -> SqlQuery (SqlExpr (Value a)) -> SqlExpr (Value a)
sub Mode
SELECT

-- | Project a field of an entity.
(^.) :: forall typ val . (PersistEntity val, PersistField typ)
    => SqlExpr (Entity val)
    -> EntityField val typ
    -> SqlExpr (Value typ)
ERaw SqlExprMeta
m NeedParens -> IdentInfo -> (Builder, [PersistValue])
f ^. :: forall typ val.
(PersistEntity val, PersistField typ) =>
SqlExpr (Entity val) -> EntityField val typ -> SqlExpr (Value typ)
^. EntityField val typ
field
    | forall record typ.
PersistEntity record =>
EntityField record typ -> Bool
isIdField EntityField val typ
field = SqlExpr (Value typ)
idFieldValue
    | Just Ident
alias <- SqlExprMeta -> Maybe Ident
sqlExprMetaAlias SqlExprMeta
m =
        forall a.
SqlExprMeta
-> (NeedParens -> IdentInfo -> (Builder, [PersistValue]))
-> SqlExpr a
ERaw SqlExprMeta
noMeta forall a b. (a -> b) -> a -> b
$ \NeedParens
_ IdentInfo
info ->
            NeedParens -> IdentInfo -> (Builder, [PersistValue])
f NeedParens
Never IdentInfo
info forall a. Semigroup a => a -> a -> a
<> (Builder
"." forall a. Semigroup a => a -> a -> a
<> IdentInfo -> Ident -> Builder
useIdent IdentInfo
info (Ident -> FieldDef -> Ident
aliasedEntityColumnIdent Ident
alias FieldDef
fieldDef), [])
    | Bool
otherwise = forall a.
SqlExprMeta
-> (NeedParens -> IdentInfo -> (Builder, [PersistValue]))
-> SqlExpr a
ERaw SqlExprMeta
noMeta forall a b. (a -> b) -> a -> b
$ \NeedParens
_ IdentInfo
info -> (IdentInfo -> FieldDef -> Builder
dot IdentInfo
info forall a b. (a -> b) -> a -> b
$ forall record typ.
PersistEntity record =>
EntityField record typ -> FieldDef
persistFieldDef EntityField val typ
field, [])
  where
    fieldDef :: FieldDef
fieldDef =
        if forall record typ.
PersistEntity record =>
EntityField record typ -> Bool
isIdField EntityField val typ
field then
            -- TODO what about composite natural keys in a join this will ignore them
            forall a. NonEmpty a -> a
NEL.head forall a b. (a -> b) -> a -> b
$ EntityDef -> NonEmpty FieldDef
getEntityKeyFields EntityDef
ed
        else
            forall record typ.
PersistEntity record =>
EntityField record typ -> FieldDef
persistFieldDef EntityField val typ
field
    idFieldValue :: SqlExpr (Value typ)
idFieldValue =
        case EntityDef -> NonEmpty FieldDef
getEntityKeyFields EntityDef
ed of
            FieldDef
idField :| [] ->
                forall a.
SqlExprMeta
-> (NeedParens -> IdentInfo -> (Builder, [PersistValue]))
-> SqlExpr a
ERaw SqlExprMeta
noMeta forall a b. (a -> b) -> a -> b
$ \NeedParens
_ IdentInfo
info -> (IdentInfo -> FieldDef -> Builder
dot IdentInfo
info FieldDef
idField, [])

            NonEmpty FieldDef
idFields ->
                let renderedFields :: IdentInfo -> [Builder]
renderedFields IdentInfo
info = IdentInfo -> FieldDef -> Builder
dot IdentInfo
info forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> forall a. NonEmpty a -> [a]
NEL.toList NonEmpty FieldDef
idFields
                in forall a.
SqlExprMeta
-> (NeedParens -> IdentInfo -> (Builder, [PersistValue]))
-> SqlExpr a
ERaw SqlExprMeta
noMeta{ sqlExprMetaCompositeFields :: Maybe (IdentInfo -> [Builder])
sqlExprMetaCompositeFields = forall a. a -> Maybe a
Just IdentInfo -> [Builder]
renderedFields} forall a b. (a -> b) -> a -> b
$
                    \NeedParens
p IdentInfo
info -> (NeedParens -> Builder -> Builder
parensM NeedParens
p forall a b. (a -> b) -> a -> b
$ [Builder] -> Builder
uncommas forall a b. (a -> b) -> a -> b
$ IdentInfo -> [Builder]
renderedFields IdentInfo
info, [])

    ed :: EntityDef
ed = forall record (proxy :: * -> *).
PersistEntity record =>
proxy record -> EntityDef
entityDef forall a b. (a -> b) -> a -> b
$ forall a. Proxy (SqlExpr (Entity a)) -> Proxy a
getEntityVal (forall {k} (t :: k). Proxy t
Proxy :: Proxy (SqlExpr (Entity val)))

    dot :: IdentInfo -> FieldDef -> Builder
dot IdentInfo
info FieldDef
fieldDef' =
        IdentInfo -> Builder
sourceIdent IdentInfo
info forall a. Semigroup a => a -> a -> a
<> Builder
"." forall a. Semigroup a => a -> a -> a
<> Builder
fieldIdent
      where
        sourceIdent :: IdentInfo -> Builder
sourceIdent = forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap forall a b. (a, b) -> a
fst forall a b. (a -> b) -> a -> b
$ NeedParens -> IdentInfo -> (Builder, [PersistValue])
f NeedParens
Never
        fieldIdent :: Builder
fieldIdent
            | Just Ident
baseI <- SqlExprMeta -> Maybe Ident
sqlExprMetaAlias SqlExprMeta
m =
                IdentInfo -> Ident -> Builder
useIdent IdentInfo
info forall a b. (a -> b) -> a -> b
$ Ident -> FieldDef -> Ident
aliasedEntityColumnIdent Ident
baseI FieldDef
fieldDef'
            | Bool
otherwise =
                IdentInfo -> DBName -> Builder
fromDBName IdentInfo
info (coerce :: forall a b. Coercible a b => a -> b
coerce forall a b. (a -> b) -> a -> b
$ FieldDef -> FieldNameDB
fieldDB FieldDef
fieldDef')

-- | 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
withNonNull :: forall typ a.
PersistField typ =>
SqlExpr (Value (Maybe typ))
-> (SqlExpr (Value typ) -> SqlQuery a) -> SqlQuery a
withNonNull SqlExpr (Value (Maybe typ))
field SqlExpr (Value typ) -> SqlQuery a
f = do
    SqlExpr (Value Bool) -> SqlQuery ()
where_ forall a b. (a -> b) -> a -> b
$ SqlExpr (Value Bool) -> SqlExpr (Value Bool)
not_ forall a b. (a -> b) -> a -> b
$ forall typ.
PersistField typ =>
SqlExpr (Value (Maybe typ)) -> SqlExpr (Value Bool)
isNothing SqlExpr (Value (Maybe typ))
field
    SqlExpr (Value typ) -> SqlQuery a
f forall a b. (a -> b) -> a -> b
$ forall a b. SqlExpr (Value a) -> SqlExpr (Value b)
veryUnsafeCoerceSqlExprValue SqlExpr (Value (Maybe typ))
field

-- | Project a field of an entity that may be null.
(?.) :: ( PersistEntity val , PersistField typ)
    => SqlExpr (Maybe (Entity val))
    -> EntityField val typ
    -> SqlExpr (Value (Maybe typ))
ERaw SqlExprMeta
m NeedParens -> IdentInfo -> (Builder, [PersistValue])
f ?. :: forall val typ.
(PersistEntity val, PersistField typ) =>
SqlExpr (Maybe (Entity val))
-> EntityField val typ -> SqlExpr (Value (Maybe typ))
?. EntityField val typ
field = forall typ. SqlExpr (Value typ) -> SqlExpr (Value (Maybe typ))
just (forall a.
SqlExprMeta
-> (NeedParens -> IdentInfo -> (Builder, [PersistValue]))
-> SqlExpr a
ERaw SqlExprMeta
m NeedParens -> IdentInfo -> (Builder, [PersistValue])
f forall typ val.
(PersistEntity val, PersistField typ) =>
SqlExpr (Entity val) -> EntityField val typ -> SqlExpr (Value typ)
^. EntityField val typ
field)

-- | Lift a constant value from Haskell-land to the query.
val  :: PersistField typ => typ -> SqlExpr (Value typ)
val :: forall typ. PersistField typ => typ -> SqlExpr (Value typ)
val typ
v = forall a.
SqlExprMeta
-> (NeedParens -> IdentInfo -> (Builder, [PersistValue]))
-> SqlExpr a
ERaw SqlExprMeta
noMeta forall a b. (a -> b) -> a -> b
$ \NeedParens
_ IdentInfo
_ -> (Builder
"?", [forall a. PersistField a => a -> PersistValue
toPersistValue typ
v])

-- | @IS NULL@ comparison.
--
-- For @IS NOT NULL@, you can negate this with 'not_', as in @not_ (isNothing (person ^. PersonAge))@
--
-- Warning: Persistent and Esqueleto have different behavior for @!= Nothing@:
--
-- +----------------+----------------------------------+---------------+
-- |                | Haskell                          | SQL           |
-- +================+==================================+===============+
-- | __Persistent__ | @'Database.Persist.!=.' Nothing@ | @IS NOT NULL@ |
-- +----------------+----------------------------------+---------------+
-- | __Esqueleto__  | @'!=.' Nothing@                  | @!= NULL@     |
-- +----------------+----------------------------------+---------------+
--
-- In SQL, @= NULL@ and @!= NULL@ return NULL instead of true or false. For this reason, you very likely do not want to use @'!=.' Nothing@ in Esqueleto.
-- You may find these @hlint@ rules helpful to enforce this:
--
-- > - 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}
isNothing :: PersistField typ => SqlExpr (Value (Maybe typ)) -> SqlExpr (Value Bool)
isNothing :: forall typ.
PersistField typ =>
SqlExpr (Value (Maybe typ)) -> SqlExpr (Value Bool)
isNothing SqlExpr (Value (Maybe typ))
v =
    case SqlExpr (Value (Maybe typ))
v of
        ERaw SqlExprMeta
m NeedParens -> IdentInfo -> (Builder, [PersistValue])
f ->
            case SqlExprMeta -> Maybe (IdentInfo -> [Builder])
sqlExprMetaCompositeFields SqlExprMeta
m of
                Just IdentInfo -> [Builder]
fields ->
                    forall a.
SqlExprMeta
-> (NeedParens -> IdentInfo -> (Builder, [PersistValue]))
-> SqlExpr a
ERaw SqlExprMeta
noMeta forall a b. (a -> b) -> a -> b
$ \NeedParens
p IdentInfo
info ->
                        forall (a :: * -> * -> *) b c d.
Arrow a =>
a b c -> a (b, d) (c, d)
first (NeedParens -> Builder -> Builder
parensM NeedParens
p) forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a b c. (a -> b -> c) -> b -> a -> c
flip (,) [] forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Builder -> [Builder] -> Builder
intersperseB Builder
" AND " forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a b. (a -> b) -> [a] -> [b]
map (forall a. Semigroup a => a -> a -> a
<> Builder
" IS NULL")) forall a b. (a -> b) -> a -> b
$ IdentInfo -> [Builder]
fields IdentInfo
info
                Maybe (IdentInfo -> [Builder])
Nothing ->
                    forall a.
SqlExprMeta
-> (NeedParens -> IdentInfo -> (Builder, [PersistValue]))
-> SqlExpr a
ERaw SqlExprMeta
noMeta forall a b. (a -> b) -> a -> b
$ \NeedParens
p IdentInfo
info ->
                        forall (a :: * -> * -> *) b c d.
Arrow a =>
a b c -> a (b, d) (c, d)
first (NeedParens -> Builder -> Builder
parensM NeedParens
p) forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a. (Builder, a) -> (Builder, a)
isNullExpr forall a b. (a -> b) -> a -> b
$ NeedParens -> IdentInfo -> (Builder, [PersistValue])
f NeedParens
Never IdentInfo
info
  where
    isNullExpr :: (TLB.Builder, a) -> (TLB.Builder, a)
    isNullExpr :: forall a. (Builder, a) -> (Builder, a)
isNullExpr = forall (a :: * -> * -> *) b c d.
Arrow a =>
a b c -> a (b, d) (c, d)
first ((forall a. Semigroup a => a -> a -> a
<> Builder
" IS NULL"))

-- | An alias for 'isNothing' that avoids clashing with the function from
-- "Data.Maybe" 'Data.Maybe.isNothing'.
--
-- @since 3.5.10.0
isNothing_ :: PersistField typ => SqlExpr (Value (Maybe typ)) -> SqlExpr (Value Bool)
isNothing_ :: forall typ.
PersistField typ =>
SqlExpr (Value (Maybe typ)) -> SqlExpr (Value Bool)
isNothing_ = forall typ.
PersistField typ =>
SqlExpr (Value (Maybe typ)) -> SqlExpr (Value Bool)
isNothing

-- | Analogous to 'Just', promotes a value of type @typ@ into
-- one of type @Maybe typ@.  It should hold that @'val' . Just
-- === just . 'val'@.
just :: SqlExpr (Value typ) -> SqlExpr (Value (Maybe typ))
just :: forall typ. SqlExpr (Value typ) -> SqlExpr (Value (Maybe typ))
just = forall a b. SqlExpr (Value a) -> SqlExpr (Value b)
veryUnsafeCoerceSqlExprValue

-- | @NULL@ value.
nothing :: SqlExpr (Value (Maybe typ))
nothing :: forall typ. SqlExpr (Value (Maybe typ))
nothing = forall a. Builder -> SqlExpr (Value a)
unsafeSqlValue Builder
"NULL"

-- | Join nested 'Maybe's in a 'Value' into one. This is useful when
-- calling aggregate functions on nullable fields.
joinV :: SqlExpr (Value (Maybe (Maybe typ))) -> SqlExpr (Value (Maybe typ))
joinV :: forall typ.
SqlExpr (Value (Maybe (Maybe typ))) -> SqlExpr (Value (Maybe typ))
joinV = forall a b. SqlExpr (Value a) -> SqlExpr (Value b)
veryUnsafeCoerceSqlExprValue


countHelper :: Num a => TLB.Builder -> TLB.Builder -> SqlExpr (Value typ) -> SqlExpr (Value a)
countHelper :: forall a typ.
Num a =>
Builder -> Builder -> SqlExpr (Value typ) -> SqlExpr (Value a)
countHelper Builder
open Builder
close SqlExpr (Value typ)
v =
    case SqlExpr (Value typ)
v of
        ERaw SqlExprMeta
meta NeedParens -> IdentInfo -> (Builder, [PersistValue])
f ->
            if SqlExprMeta -> Bool
hasCompositeKeyMeta SqlExprMeta
meta then
                forall a. Num a => SqlExpr (Value a)
countRows
            else
                forall a.
(IdentInfo -> (Builder, [PersistValue])) -> SqlExpr (Value a)
countRawSql (NeedParens -> IdentInfo -> (Builder, [PersistValue])
f NeedParens
Never)
  where
    countRawSql :: (IdentInfo -> (TLB.Builder, [PersistValue])) -> SqlExpr (Value a)
    countRawSql :: forall a.
(IdentInfo -> (Builder, [PersistValue])) -> SqlExpr (Value a)
countRawSql IdentInfo -> (Builder, [PersistValue])
x = forall a.
SqlExprMeta
-> (NeedParens -> IdentInfo -> (Builder, [PersistValue]))
-> SqlExpr a
ERaw SqlExprMeta
noMeta forall a b. (a -> b) -> a -> b
$ \NeedParens
_ -> forall (a :: * -> * -> *) b c d.
Arrow a =>
a b c -> a (b, d) (c, d)
first (\Builder
b -> Builder
"COUNT" forall a. Semigroup a => a -> a -> a
<> Builder
open forall a. Semigroup a => a -> a -> a
<> Builder -> Builder
parens Builder
b forall a. Semigroup a => a -> a -> a
<> Builder
close) forall b c a. (b -> c) -> (a -> b) -> a -> c
. IdentInfo -> (Builder, [PersistValue])
x

-- | @COUNT(*)@ value.
countRows :: Num a => SqlExpr (Value a)
countRows :: forall a. Num a => SqlExpr (Value a)
countRows = forall a. Builder -> SqlExpr (Value a)
unsafeSqlValue Builder
"COUNT(*)"

-- | @COUNT@.
count :: Num a => SqlExpr (Value typ) -> SqlExpr (Value a)
count :: forall a typ. Num a => SqlExpr (Value typ) -> SqlExpr (Value a)
count = forall a typ.
Num a =>
Builder -> Builder -> SqlExpr (Value typ) -> SqlExpr (Value a)
countHelper Builder
""           Builder
""

-- | @COUNT(DISTINCT x)@.
--
-- @since 2.4.1
countDistinct :: Num a => SqlExpr (Value typ) -> SqlExpr (Value a)
countDistinct :: forall a typ. Num a => SqlExpr (Value typ) -> SqlExpr (Value a)
countDistinct = forall a typ.
Num a =>
Builder -> Builder -> SqlExpr (Value typ) -> SqlExpr (Value a)
countHelper Builder
"(DISTINCT " Builder
")"

not_ :: SqlExpr (Value Bool) -> SqlExpr (Value Bool)
not_ :: SqlExpr (Value Bool) -> SqlExpr (Value Bool)
not_ SqlExpr (Value Bool)
v = forall a.
SqlExprMeta
-> (NeedParens -> IdentInfo -> (Builder, [PersistValue]))
-> SqlExpr a
ERaw SqlExprMeta
noMeta forall a b. (a -> b) -> a -> b
$ \NeedParens
p IdentInfo
info -> forall (a :: * -> * -> *) b c d.
Arrow a =>
a b c -> a (b, d) (c, d)
first (Builder
"NOT " forall a. Semigroup a => a -> a -> a
<>) forall a b. (a -> b) -> a -> b
$ NeedParens -> IdentInfo -> (Builder, [PersistValue])
x NeedParens
p IdentInfo
info
  where
    x :: NeedParens -> IdentInfo -> (Builder, [PersistValue])
x NeedParens
p IdentInfo
info =
        case SqlExpr (Value Bool)
v of
            ERaw SqlExprMeta
m NeedParens -> IdentInfo -> (Builder, [PersistValue])
f ->
                if SqlExprMeta -> Bool
hasCompositeKeyMeta SqlExprMeta
m then
                    forall a e. Exception e => e -> a
throw (UnexpectedValueError -> EsqueletoError
CompositeKeyErr UnexpectedValueError
NotError)
                else
                    let (Builder
b, [PersistValue]
vals) = NeedParens -> IdentInfo -> (Builder, [PersistValue])
f NeedParens
Never IdentInfo
info
                    in (NeedParens -> Builder -> Builder
parensM NeedParens
p Builder
b, [PersistValue]
vals)

(==.) :: PersistField typ => SqlExpr (Value typ) -> SqlExpr (Value typ) -> SqlExpr (Value Bool)
==. :: forall typ.
PersistField typ =>
SqlExpr (Value typ) -> SqlExpr (Value typ) -> SqlExpr (Value Bool)
(==.) = forall a b c.
Builder
-> Builder
-> SqlExpr (Value a)
-> SqlExpr (Value b)
-> SqlExpr (Value c)
unsafeSqlBinOpComposite Builder
" = " Builder
" AND "

(>=.) :: PersistField typ => SqlExpr (Value typ) -> SqlExpr (Value typ) -> SqlExpr (Value Bool)
>=. :: forall typ.
PersistField typ =>
SqlExpr (Value typ) -> SqlExpr (Value typ) -> SqlExpr (Value Bool)
(>=.) = forall a b c.
Builder
-> SqlExpr (Value a) -> SqlExpr (Value b) -> SqlExpr (Value c)
unsafeSqlBinOp Builder
" >= "

(>.)  :: PersistField typ => SqlExpr (Value typ) -> SqlExpr (Value typ) -> SqlExpr (Value Bool)
>. :: forall typ.
PersistField typ =>
SqlExpr (Value typ) -> SqlExpr (Value typ) -> SqlExpr (Value Bool)
(>.)  = forall a b c.
Builder
-> SqlExpr (Value a) -> SqlExpr (Value b) -> SqlExpr (Value c)
unsafeSqlBinOp Builder
" > "

(<=.) :: PersistField typ => SqlExpr (Value typ) -> SqlExpr (Value typ) -> SqlExpr (Value Bool)
<=. :: forall typ.
PersistField typ =>
SqlExpr (Value typ) -> SqlExpr (Value typ) -> SqlExpr (Value Bool)
(<=.) = forall a b c.
Builder
-> SqlExpr (Value a) -> SqlExpr (Value b) -> SqlExpr (Value c)
unsafeSqlBinOp Builder
" <= "

(<.)  :: PersistField typ => SqlExpr (Value typ) -> SqlExpr (Value typ) -> SqlExpr (Value Bool)
<. :: forall typ.
PersistField typ =>
SqlExpr (Value typ) -> SqlExpr (Value typ) -> SqlExpr (Value Bool)
(<.)  = forall a b c.
Builder
-> SqlExpr (Value a) -> SqlExpr (Value b) -> SqlExpr (Value c)
unsafeSqlBinOp Builder
" < "
(!=.) :: PersistField typ => SqlExpr (Value typ) -> SqlExpr (Value typ) -> SqlExpr (Value Bool)
!=. :: forall typ.
PersistField typ =>
SqlExpr (Value typ) -> SqlExpr (Value typ) -> SqlExpr (Value Bool)
(!=.) = forall a b c.
Builder
-> Builder
-> SqlExpr (Value a)
-> SqlExpr (Value b)
-> SqlExpr (Value c)
unsafeSqlBinOpComposite Builder
" != " Builder
" OR "

(&&.) :: SqlExpr (Value Bool) -> SqlExpr (Value Bool) -> SqlExpr (Value Bool)
&&. :: SqlExpr (Value Bool)
-> SqlExpr (Value Bool) -> SqlExpr (Value Bool)
(&&.) = forall a b c.
Builder
-> SqlExpr (Value a) -> SqlExpr (Value b) -> SqlExpr (Value c)
unsafeSqlBinOp Builder
" AND "

(||.) :: SqlExpr (Value Bool) -> SqlExpr (Value Bool) -> SqlExpr (Value Bool)
||. :: SqlExpr (Value Bool)
-> SqlExpr (Value Bool) -> SqlExpr (Value Bool)
(||.) = forall a b c.
Builder
-> SqlExpr (Value a) -> SqlExpr (Value b) -> SqlExpr (Value c)
unsafeSqlBinOp Builder
" OR "

(+.)  :: PersistField a => SqlExpr (Value a) -> SqlExpr (Value a) -> SqlExpr (Value a)
+. :: forall a.
PersistField a =>
SqlExpr (Value a) -> SqlExpr (Value a) -> SqlExpr (Value a)
(+.)  = forall a b c.
Builder
-> SqlExpr (Value a) -> SqlExpr (Value b) -> SqlExpr (Value c)
unsafeSqlBinOp Builder
" + "

(-.)  :: PersistField a => SqlExpr (Value a) -> SqlExpr (Value a) -> SqlExpr (Value a)
-. :: forall a.
PersistField a =>
SqlExpr (Value a) -> SqlExpr (Value a) -> SqlExpr (Value a)
(-.)  = forall a b c.
Builder
-> SqlExpr (Value a) -> SqlExpr (Value b) -> SqlExpr (Value c)
unsafeSqlBinOp Builder
" - "

(/.)  :: PersistField a => SqlExpr (Value a) -> SqlExpr (Value a) -> SqlExpr (Value a)
/. :: forall a.
PersistField a =>
SqlExpr (Value a) -> SqlExpr (Value a) -> SqlExpr (Value a)
(/.)  = forall a b c.
Builder
-> SqlExpr (Value a) -> SqlExpr (Value b) -> SqlExpr (Value c)
unsafeSqlBinOp Builder
" / "

(*.)  :: PersistField a => SqlExpr (Value a) -> SqlExpr (Value a) -> SqlExpr (Value a)
*. :: forall a.
PersistField a =>
SqlExpr (Value a) -> SqlExpr (Value a) -> SqlExpr (Value a)
(*.)  = forall a b c.
Builder
-> SqlExpr (Value a) -> SqlExpr (Value b) -> SqlExpr (Value c)
unsafeSqlBinOp Builder
" * "

-- | @BETWEEN@.
--
-- @since: 3.1.0
between :: PersistField a => SqlExpr (Value a) -> (SqlExpr (Value a), SqlExpr (Value a)) -> SqlExpr (Value Bool)
SqlExpr (Value a)
a between :: forall a.
PersistField a =>
SqlExpr (Value a)
-> (SqlExpr (Value a), SqlExpr (Value a)) -> SqlExpr (Value Bool)
`between` (SqlExpr (Value a)
b, SqlExpr (Value a)
c) = SqlExpr (Value a)
a forall typ.
PersistField typ =>
SqlExpr (Value typ) -> SqlExpr (Value typ) -> SqlExpr (Value Bool)
>=. SqlExpr (Value a)
b SqlExpr (Value Bool)
-> SqlExpr (Value Bool) -> SqlExpr (Value Bool)
&&. SqlExpr (Value a)
a forall typ.
PersistField typ =>
SqlExpr (Value typ) -> SqlExpr (Value typ) -> SqlExpr (Value Bool)
<=. SqlExpr (Value a)
c

random_  :: (PersistField a, Num a) => SqlExpr (Value a)
random_ :: forall a. (PersistField a, Num a) => SqlExpr (Value a)
random_  = forall a. Builder -> SqlExpr (Value a)
unsafeSqlValue Builder
"RANDOM()"

round_   :: (PersistField a, Num a, PersistField b, Num b) => SqlExpr (Value a) -> SqlExpr (Value b)
round_ :: forall a b.
(PersistField a, Num a, PersistField b, Num b) =>
SqlExpr (Value a) -> SqlExpr (Value b)
round_   = forall a b.
UnsafeSqlFunctionArgument a =>
Builder -> a -> SqlExpr (Value b)
unsafeSqlFunction Builder
"ROUND"

ceiling_ :: (PersistField a, Num a, PersistField b, Num b) => SqlExpr (Value a) -> SqlExpr (Value b)
ceiling_ :: forall a b.
(PersistField a, Num a, PersistField b, Num b) =>
SqlExpr (Value a) -> SqlExpr (Value b)
ceiling_ = forall a b.
UnsafeSqlFunctionArgument a =>
Builder -> a -> SqlExpr (Value b)
unsafeSqlFunction Builder
"CEILING"

floor_   :: (PersistField a, Num a, PersistField b, Num b) => SqlExpr (Value a) -> SqlExpr (Value b)
floor_ :: forall a b.
(PersistField a, Num a, PersistField b, Num b) =>
SqlExpr (Value a) -> SqlExpr (Value b)
floor_   = forall a b.
UnsafeSqlFunctionArgument a =>
Builder -> a -> SqlExpr (Value b)
unsafeSqlFunction Builder
"FLOOR"

sum_     :: (PersistField a, PersistField b) => SqlExpr (Value a) -> SqlExpr (Value (Maybe b))
sum_ :: forall a b.
(PersistField a, PersistField b) =>
SqlExpr (Value a) -> SqlExpr (Value (Maybe b))
sum_     = forall a b.
UnsafeSqlFunctionArgument a =>
Builder -> a -> SqlExpr (Value b)
unsafeSqlFunction Builder
"SUM"
min_     :: (PersistField a) => SqlExpr (Value a) -> SqlExpr (Value (Maybe a))
min_ :: forall a.
PersistField a =>
SqlExpr (Value a) -> SqlExpr (Value (Maybe a))
min_     = forall a b.
UnsafeSqlFunctionArgument a =>
Builder -> a -> SqlExpr (Value b)
unsafeSqlFunction Builder
"MIN"
max_     :: (PersistField a) => SqlExpr (Value a) -> SqlExpr (Value (Maybe a))
max_ :: forall a.
PersistField a =>
SqlExpr (Value a) -> SqlExpr (Value (Maybe a))
max_     = forall a b.
UnsafeSqlFunctionArgument a =>
Builder -> a -> SqlExpr (Value b)
unsafeSqlFunction Builder
"MAX"
avg_     :: (PersistField a, PersistField b) => SqlExpr (Value a) -> SqlExpr (Value (Maybe b))
avg_ :: forall a b.
(PersistField a, PersistField b) =>
SqlExpr (Value a) -> SqlExpr (Value (Maybe b))
avg_     = forall a b.
UnsafeSqlFunctionArgument a =>
Builder -> a -> SqlExpr (Value b)
unsafeSqlFunction Builder
"AVG"

-- | 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.
--
-- /Caveat/: Trying to use @castNum@ from @Double@ to @Int@
-- will not result in an integer, the original fractional
-- number will still be used!  Use 'round_', 'ceiling_' or
-- 'floor_' instead.
--
-- /Safety/: This operation is mostly safe due to the 'Num'
-- 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 @persistent@
-- not being able to parse it.
--
-- @since 2.2.9
castNum :: (Num a, Num b) => SqlExpr (Value a) -> SqlExpr (Value b)
castNum :: forall a b.
(Num a, Num b) =>
SqlExpr (Value a) -> SqlExpr (Value b)
castNum  = forall a b. SqlExpr (Value a) -> SqlExpr (Value b)
veryUnsafeCoerceSqlExprValue

-- | Same as 'castNum', but for nullable values.
--
-- @since 2.2.9
castNumM :: (Num a, Num b) => SqlExpr (Value (Maybe a)) -> SqlExpr (Value (Maybe b))
castNumM :: forall a b.
(Num a, Num b) =>
SqlExpr (Value (Maybe a)) -> SqlExpr (Value (Maybe b))
castNumM = forall a b. SqlExpr (Value a) -> SqlExpr (Value b)
veryUnsafeCoerceSqlExprValue

-- | @COALESCE@ 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.
--
-- @since 1.4.3
coalesce :: PersistField a => [SqlExpr (Value (Maybe a))] -> SqlExpr (Value (Maybe a))
coalesce :: forall a.
PersistField a =>
[SqlExpr (Value (Maybe a))] -> SqlExpr (Value (Maybe a))
coalesce              = forall a b.
UnsafeSqlFunctionArgument a =>
Builder -> a -> SqlExpr (Value b)
unsafeSqlFunctionParens Builder
"COALESCE"

-- | Like @coalesce@, but takes a non-nullable SqlExpression
-- placed at the end of the SqlExpression list, which guarantees
-- a non-NULL result.
--
-- @since 1.4.3
coalesceDefault :: PersistField a => [SqlExpr (Value (Maybe a))] -> SqlExpr (Value a) -> SqlExpr (Value a)
coalesceDefault :: forall a.
PersistField a =>
[SqlExpr (Value (Maybe a))]
-> SqlExpr (Value a) -> SqlExpr (Value a)
coalesceDefault [SqlExpr (Value (Maybe a))]
exprs = forall a b.
UnsafeSqlFunctionArgument a =>
Builder -> a -> SqlExpr (Value b)
unsafeSqlFunctionParens Builder
"COALESCE" forall b c a. (b -> c) -> (a -> b) -> a -> c
. ([SqlExpr (Value (Maybe a))]
exprs forall a. [a] -> [a] -> [a]
++) forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall (m :: * -> *) a. Monad m => a -> m a
return forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall typ. SqlExpr (Value typ) -> SqlExpr (Value (Maybe typ))
just

-- | @LOWER@ function.
lower_ :: SqlString s => SqlExpr (Value s) -> SqlExpr (Value s)
lower_ :: forall s. SqlString s => SqlExpr (Value s) -> SqlExpr (Value s)
lower_  = forall a b.
UnsafeSqlFunctionArgument a =>
Builder -> a -> SqlExpr (Value b)
unsafeSqlFunction Builder
"LOWER"

-- | @UPPER@ function.
-- @since 3.3.0
upper_ :: SqlString s => SqlExpr (Value s) -> SqlExpr (Value s)
upper_ :: forall s. SqlString s => SqlExpr (Value s) -> SqlExpr (Value s)
upper_  = forall a b.
UnsafeSqlFunctionArgument a =>
Builder -> a -> SqlExpr (Value b)
unsafeSqlFunction Builder
"UPPER"

-- | @TRIM@ function.
-- @since 3.3.0
trim_ :: SqlString s => SqlExpr (Value s) -> SqlExpr (Value s)
trim_ :: forall s. SqlString s => SqlExpr (Value s) -> SqlExpr (Value s)
trim_  = forall a b.
UnsafeSqlFunctionArgument a =>
Builder -> a -> SqlExpr (Value b)
unsafeSqlFunction Builder
"TRIM"

-- | @RTRIM@ function.
-- @since 3.3.0
rtrim_ :: SqlString s => SqlExpr (Value s) -> SqlExpr (Value s)
rtrim_ :: forall s. SqlString s => SqlExpr (Value s) -> SqlExpr (Value s)
rtrim_  = forall a b.
UnsafeSqlFunctionArgument a =>
Builder -> a -> SqlExpr (Value b)
unsafeSqlFunction Builder
"RTRIM"

-- | @LTRIM@ function.
-- @since 3.3.0
ltrim_ :: SqlString s => SqlExpr (Value s) -> SqlExpr (Value s)
ltrim_ :: forall s. SqlString s => SqlExpr (Value s) -> SqlExpr (Value s)
ltrim_  = forall a b.
UnsafeSqlFunctionArgument a =>
Builder -> a -> SqlExpr (Value b)
unsafeSqlFunction Builder
"LTRIM"

-- | @LENGTH@ function.
-- @since 3.3.0
length_ :: (SqlString s, Num a) => SqlExpr (Value s) -> SqlExpr (Value a)
length_ :: forall s a.
(SqlString s, Num a) =>
SqlExpr (Value s) -> SqlExpr (Value a)
length_ = forall a b.
UnsafeSqlFunctionArgument a =>
Builder -> a -> SqlExpr (Value b)
unsafeSqlFunction Builder
"LENGTH"

-- | @LEFT@ function.
-- @since 3.3.0
left_ :: (SqlString s, Num a) => (SqlExpr (Value s), SqlExpr (Value a)) -> SqlExpr (Value s)
left_ :: forall s a.
(SqlString s, Num a) =>
(SqlExpr (Value s), SqlExpr (Value a)) -> SqlExpr (Value s)
left_ = forall a b.
UnsafeSqlFunctionArgument a =>
Builder -> a -> SqlExpr (Value b)
unsafeSqlFunction Builder
"LEFT"

-- | @RIGHT@ function.
-- @since 3.3.0
right_ :: (SqlString s, Num a) => (SqlExpr (Value s), SqlExpr (Value a)) -> SqlExpr (Value s)
right_ :: forall s a.
(SqlString s, Num a) =>
(SqlExpr (Value s), SqlExpr (Value a)) -> SqlExpr (Value s)
right_ = forall a b.
UnsafeSqlFunctionArgument a =>
Builder -> a -> SqlExpr (Value b)
unsafeSqlFunction Builder
"RIGHT"

-- | @LIKE@ operator.
like :: SqlString s => SqlExpr (Value s) -> SqlExpr (Value s) -> SqlExpr (Value Bool)
like :: forall s.
SqlString s =>
SqlExpr (Value s) -> SqlExpr (Value s) -> SqlExpr (Value Bool)
like    = forall a b c.
Builder
-> SqlExpr (Value a) -> SqlExpr (Value b) -> SqlExpr (Value c)
unsafeSqlBinOp    Builder
" LIKE "

-- | @ILIKE@ operator (case-insensitive @LIKE@).
--
-- Supported by PostgreSQL only.
--
-- @since 2.2.3
ilike :: SqlString s => SqlExpr (Value s) -> SqlExpr (Value s) -> SqlExpr (Value Bool)
ilike :: forall s.
SqlString s =>
SqlExpr (Value s) -> SqlExpr (Value s) -> SqlExpr (Value Bool)
ilike   = forall a b c.
Builder
-> SqlExpr (Value a) -> SqlExpr (Value b) -> SqlExpr (Value c)
unsafeSqlBinOp    Builder
" ILIKE "

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

-- | The @CONCAT@ function with a variable number of
-- parameters.  Supported by MySQL and PostgreSQL.
concat_ :: SqlString s => [SqlExpr (Value s)] -> SqlExpr (Value s)
concat_ :: forall s. SqlString s => [SqlExpr (Value s)] -> SqlExpr (Value s)
concat_ = forall a b.
UnsafeSqlFunctionArgument a =>
Builder -> a -> SqlExpr (Value b)
unsafeSqlFunction Builder
"CONCAT"

-- | The @||@ string concatenation operator (named after
-- Haskell's '++' in order to avoid naming clash with '||.').
-- Supported by SQLite and PostgreSQL.
(++.) :: SqlString s => SqlExpr (Value s) -> SqlExpr (Value s) -> SqlExpr (Value s)
++. :: forall s.
SqlString s =>
SqlExpr (Value s) -> SqlExpr (Value s) -> SqlExpr (Value s)
(++.)   = forall a b c.
Builder
-> SqlExpr (Value a) -> SqlExpr (Value b) -> SqlExpr (Value c)
unsafeSqlBinOp    Builder
" || "

-- | Cast a string type into 'Text'.  This function
-- is very useful if you want to use @newtype@s, or if you want
-- to apply functions such as 'like' to strings of different
-- types.
--
-- /Safety:/ This is a slightly unsafe function, especially if
-- you have defined your own instances of 'SqlString'.  Also,
-- since 'Maybe' is an instance of 'SqlString', 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)
castString :: forall s r.
(SqlString s, SqlString r) =>
SqlExpr (Value s) -> SqlExpr (Value r)
castString = forall a b. SqlExpr (Value a) -> SqlExpr (Value b)
veryUnsafeCoerceSqlExprValue

-- | Execute a subquery @SELECT@ in an SqlExpression.  Returns a
-- list of values.
subList_select :: PersistField a => SqlQuery (SqlExpr (Value a)) -> SqlExpr (ValueList a)
subList_select :: forall a.
PersistField a =>
SqlQuery (SqlExpr (Value a)) -> SqlExpr (ValueList a)
subList_select SqlQuery (SqlExpr (Value a))
query = forall a.
SqlExprMeta
-> (NeedParens -> IdentInfo -> (Builder, [PersistValue]))
-> SqlExpr a
ERaw SqlExprMeta
noMeta forall a b. (a -> b) -> a -> b
$ \NeedParens
_ IdentInfo
info -> forall (a :: * -> * -> *) b c d.
Arrow a =>
a b c -> a (b, d) (c, d)
first Builder -> Builder
parens forall a b. (a -> b) -> a -> b
$ forall a r backend.
(SqlSelect a r, BackendCompatible SqlBackend backend) =>
Mode
-> (backend, IdentState) -> SqlQuery a -> (Builder, [PersistValue])
toRawSql Mode
SELECT IdentInfo
info SqlQuery (SqlExpr (Value a))
query


-- | Lift a list of constant value from Haskell-land to the query.
valList :: PersistField typ => [typ] -> SqlExpr (ValueList typ)
valList :: forall typ. PersistField typ => [typ] -> SqlExpr (ValueList typ)
valList []   = forall a.
SqlExprMeta
-> (NeedParens -> IdentInfo -> (Builder, [PersistValue]))
-> SqlExpr a
ERaw SqlExprMeta
noMeta forall a b. (a -> b) -> a -> b
$ \NeedParens
_ IdentInfo
_ -> (Builder
"()", [])
valList [typ]
vals = forall a.
SqlExprMeta
-> (NeedParens -> IdentInfo -> (Builder, [PersistValue]))
-> SqlExpr a
ERaw SqlExprMeta
noMeta forall a b. (a -> b) -> a -> b
$ \NeedParens
p -> forall a b. a -> b -> a
const (NeedParens -> Builder -> Builder
parensM NeedParens
p ([Builder] -> Builder
uncommas (Builder
"?" forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ [typ]
vals)), forall a b. (a -> b) -> [a] -> [b]
map forall a. PersistField a => a -> PersistValue
toPersistValue [typ]
vals )

-- | Same as 'just' but for 'ValueList'.  Most of the time you
-- won't need it, though, because you can use 'just' from
-- inside 'subList_select' or 'Just' from inside 'valList'.
--
-- @since 2.2.12
justList :: SqlExpr (ValueList typ) -> SqlExpr (ValueList (Maybe typ))
justList :: forall typ.
SqlExpr (ValueList typ) -> SqlExpr (ValueList (Maybe typ))
justList (ERaw SqlExprMeta
m NeedParens -> IdentInfo -> (Builder, [PersistValue])
f) = forall a.
SqlExprMeta
-> (NeedParens -> IdentInfo -> (Builder, [PersistValue]))
-> SqlExpr a
ERaw SqlExprMeta
m NeedParens -> IdentInfo -> (Builder, [PersistValue])
f

-- | @IN@ operator. For example if you want to select all @Person@s by a list
-- of IDs:
--
-- @
-- SELECT *
-- FROM Person
-- WHERE Person.id IN (?)
-- @
--
-- In @esqueleto@, we may write the same query above as:
--
-- @
-- select $
-- 'from' $ \\person -> do
-- 'where_' $ person '^.' PersonId `'in_`` 'valList' personIds
-- return person
-- @
--
-- Where @personIds@ is of type @[Key Person]@.
in_ :: PersistField typ => SqlExpr (Value typ) -> SqlExpr (ValueList typ) -> SqlExpr (Value Bool)
(ERaw SqlExprMeta
_ NeedParens -> IdentInfo -> (Builder, [PersistValue])
v) in_ :: forall typ.
PersistField typ =>
SqlExpr (Value typ)
-> SqlExpr (ValueList typ) -> SqlExpr (Value Bool)
`in_` (ERaw SqlExprMeta
_ NeedParens -> IdentInfo -> (Builder, [PersistValue])
list) =
    forall a.
SqlExprMeta
-> (NeedParens -> IdentInfo -> (Builder, [PersistValue]))
-> SqlExpr a
ERaw SqlExprMeta
noMeta forall a b. (a -> b) -> a -> b
$ \NeedParens
_ IdentInfo
info ->
        let (Builder
b1, [PersistValue]
vals1) = NeedParens -> IdentInfo -> (Builder, [PersistValue])
v NeedParens
Parens IdentInfo
info
            (Builder
b2, [PersistValue]
vals2) = NeedParens -> IdentInfo -> (Builder, [PersistValue])
list NeedParens
Parens IdentInfo
info
        in
        if Builder
b2 forall a. Eq a => a -> a -> Bool
== Builder
"()" then
            (Builder
"FALSE", [])
        else
            (Builder
b1 forall a. Semigroup a => a -> a -> a
<> Builder
" IN " forall a. Semigroup a => a -> a -> a
<> Builder
b2, [PersistValue]
vals1 forall a. Semigroup a => a -> a -> a
<> [PersistValue]
vals2)

-- | @NOT IN@ operator.
notIn :: PersistField typ => SqlExpr (Value typ) -> SqlExpr (ValueList typ) -> SqlExpr (Value Bool)
(ERaw SqlExprMeta
_ NeedParens -> IdentInfo -> (Builder, [PersistValue])
v) notIn :: forall typ.
PersistField typ =>
SqlExpr (Value typ)
-> SqlExpr (ValueList typ) -> SqlExpr (Value Bool)
`notIn` (ERaw SqlExprMeta
_ NeedParens -> IdentInfo -> (Builder, [PersistValue])
list) =
    forall a.
SqlExprMeta
-> (NeedParens -> IdentInfo -> (Builder, [PersistValue]))
-> SqlExpr a
ERaw SqlExprMeta
noMeta forall a b. (a -> b) -> a -> b
$ \NeedParens
_ IdentInfo
info ->
        let (Builder
b1, [PersistValue]
vals1) = NeedParens -> IdentInfo -> (Builder, [PersistValue])
v NeedParens
Parens IdentInfo
info
            (Builder
b2, [PersistValue]
vals2) = NeedParens -> IdentInfo -> (Builder, [PersistValue])
list NeedParens
Parens IdentInfo
info
        in
        if Builder
b2 forall a. Eq a => a -> a -> Bool
== Builder
"()" then
            (Builder
"TRUE", [])
        else
            (Builder
b1 forall a. Semigroup a => a -> a -> a
<> Builder
" NOT IN " forall a. Semigroup a => a -> a -> a
<> Builder
b2, [PersistValue]
vals1 forall a. Semigroup a => a -> a -> a
<> [PersistValue]
vals2)

-- | @EXISTS@ operator.  For example:
--
-- @
-- select $
-- 'from' $ \\person -> do
-- 'where_' $ 'exists' $
--          'from' $ \\post -> do
--          'where_' (post '^.' BlogPostAuthorId '==.' person '^.' PersonId)
-- return person
-- @
exists :: SqlQuery () -> SqlExpr (Value Bool)
exists :: SqlQuery () -> SqlExpr (Value Bool)
exists SqlQuery ()
q = forall a.
SqlExprMeta
-> (NeedParens -> IdentInfo -> (Builder, [PersistValue]))
-> SqlExpr a
ERaw SqlExprMeta
noMeta forall a b. (a -> b) -> a -> b
$ \NeedParens
p IdentInfo
info ->
    let ERaw SqlExprMeta
_ NeedParens -> IdentInfo -> (Builder, [PersistValue])
f = SqlQuery () -> SqlExpr (Value Bool)
existsHelper SqlQuery ()
q
        (Builder
b, [PersistValue]
vals) = NeedParens -> IdentInfo -> (Builder, [PersistValue])
f NeedParens
Never IdentInfo
info
    in ( NeedParens -> Builder -> Builder
parensM NeedParens
p forall a b. (a -> b) -> a -> b
$ Builder
"EXISTS " forall a. Semigroup a => a -> a -> a
<> Builder
b, [PersistValue]
vals)

-- | @NOT EXISTS@ operator.
notExists :: SqlQuery () -> SqlExpr (Value Bool)
notExists :: SqlQuery () -> SqlExpr (Value Bool)
notExists SqlQuery ()
q = forall a.
SqlExprMeta
-> (NeedParens -> IdentInfo -> (Builder, [PersistValue]))
-> SqlExpr a
ERaw SqlExprMeta
noMeta forall a b. (a -> b) -> a -> b
$ \NeedParens
p IdentInfo
info ->
    let ERaw SqlExprMeta
_ NeedParens -> IdentInfo -> (Builder, [PersistValue])
f = SqlQuery () -> SqlExpr (Value Bool)
existsHelper SqlQuery ()
q
        (Builder
b, [PersistValue]
vals) = NeedParens -> IdentInfo -> (Builder, [PersistValue])
f NeedParens
Never IdentInfo
info
    in ( NeedParens -> Builder -> Builder
parensM NeedParens
p forall a b. (a -> b) -> a -> b
$ Builder
"NOT EXISTS " forall a. Semigroup a => a -> a -> a
<> Builder
b, [PersistValue]
vals)

-- | @SET@ clause used on @UPDATE@s.  Note that while it's not
-- a type error to use this function on a @SELECT@, it will
-- most certainly result in a runtime error.
set :: PersistEntity val => SqlExpr (Entity val) -> [SqlExpr (Entity val) -> SqlExpr Update] -> SqlQuery ()
set :: forall val.
PersistEntity val =>
SqlExpr (Entity val)
-> [SqlExpr (Entity val) -> SqlExpr Update] -> SqlQuery ()
set SqlExpr (Entity val)
ent [SqlExpr (Entity val) -> SqlExpr Update]
upds = forall a.
WriterT SideData (StateT IdentState Identity) a -> SqlQuery a
Q forall a b. (a -> b) -> a -> b
$ forall (m :: * -> *) w. Monad m => w -> WriterT w m ()
W.tell forall a. Monoid a => a
mempty { sdSetClause :: [SetClause]
sdSetClause = forall a b. (a -> b) -> [a] -> [b]
map (SqlExpr (Entity val) -> SqlExpr Update) -> SetClause
apply [SqlExpr (Entity val) -> SqlExpr Update]
upds }
  where
    apply :: (SqlExpr (Entity val) -> SqlExpr Update) -> SetClause
apply SqlExpr (Entity val) -> SqlExpr Update
f = SqlExpr Update -> SetClause
SetClause (SqlExpr (Entity val) -> SqlExpr Update
f SqlExpr (Entity val)
ent)

(=.)  :: (PersistEntity val, PersistField typ) => EntityField val typ -> SqlExpr (Value typ) -> (SqlExpr (Entity val) -> SqlExpr Update )
EntityField val typ
field  =. :: forall val typ.
(PersistEntity val, PersistField typ) =>
EntityField val typ
-> SqlExpr (Value typ) -> SqlExpr (Entity val) -> SqlExpr Update
=. SqlExpr (Value typ)
expr = forall val typ.
(PersistEntity val, PersistField typ) =>
EntityField val typ
-> (SqlExpr (Entity val) -> SqlExpr (Value typ))
-> SqlExpr (Entity val)
-> SqlExpr Update
setAux EntityField val typ
field (forall a b. a -> b -> a
const SqlExpr (Value typ)
expr)

(+=.) :: (PersistEntity val, PersistField a) => EntityField val a -> SqlExpr (Value a) -> (SqlExpr (Entity val) -> SqlExpr Update)
EntityField val a
field +=. :: forall val typ.
(PersistEntity val, PersistField typ) =>
EntityField val typ
-> SqlExpr (Value typ) -> SqlExpr (Entity val) -> SqlExpr Update
+=. SqlExpr (Value a)
expr = forall val typ.
(PersistEntity val, PersistField typ) =>
EntityField val typ
-> (SqlExpr (Entity val) -> SqlExpr (Value typ))
-> SqlExpr (Entity val)
-> SqlExpr Update
setAux EntityField val a
field (\SqlExpr (Entity val)
ent -> SqlExpr (Entity val)
ent forall typ val.
(PersistEntity val, PersistField typ) =>
SqlExpr (Entity val) -> EntityField val typ -> SqlExpr (Value typ)
^. EntityField val a
field forall a.
PersistField a =>
SqlExpr (Value a) -> SqlExpr (Value a) -> SqlExpr (Value a)
+. SqlExpr (Value a)
expr)

(-=.) :: (PersistEntity val, PersistField a) => EntityField val a -> SqlExpr (Value a) -> (SqlExpr (Entity val) -> SqlExpr Update)
EntityField val a
field -=. :: forall val typ.
(PersistEntity val, PersistField typ) =>
EntityField val typ
-> SqlExpr (Value typ) -> SqlExpr (Entity val) -> SqlExpr Update
-=. SqlExpr (Value a)
expr = forall val typ.
(PersistEntity val, PersistField typ) =>
EntityField val typ
-> (SqlExpr (Entity val) -> SqlExpr (Value typ))
-> SqlExpr (Entity val)
-> SqlExpr Update
setAux EntityField val a
field (\SqlExpr (Entity val)
ent -> SqlExpr (Entity val)
ent forall typ val.
(PersistEntity val, PersistField typ) =>
SqlExpr (Entity val) -> EntityField val typ -> SqlExpr (Value typ)
^. EntityField val a
field forall a.
PersistField a =>
SqlExpr (Value a) -> SqlExpr (Value a) -> SqlExpr (Value a)
-. SqlExpr (Value a)
expr)

(*=.) :: (PersistEntity val, PersistField a) => EntityField val a -> SqlExpr (Value a) -> (SqlExpr (Entity val) -> SqlExpr Update)
EntityField val a
field *=. :: forall val typ.
(PersistEntity val, PersistField typ) =>
EntityField val typ
-> SqlExpr (Value typ) -> SqlExpr (Entity val) -> SqlExpr Update
*=. SqlExpr (Value a)
expr = forall val typ.
(PersistEntity val, PersistField typ) =>
EntityField val typ
-> (SqlExpr (Entity val) -> SqlExpr (Value typ))
-> SqlExpr (Entity val)
-> SqlExpr Update
setAux EntityField val a
field (\SqlExpr (Entity val)
ent -> SqlExpr (Entity val)
ent forall typ val.
(PersistEntity val, PersistField typ) =>
SqlExpr (Entity val) -> EntityField val typ -> SqlExpr (Value typ)
^. EntityField val a
field forall a.
PersistField a =>
SqlExpr (Value a) -> SqlExpr (Value a) -> SqlExpr (Value a)
*. SqlExpr (Value a)
expr)

(/=.) :: (PersistEntity val, PersistField a) => EntityField val a -> SqlExpr (Value a) -> (SqlExpr (Entity val) -> SqlExpr Update)
EntityField val a
field /=. :: forall val typ.
(PersistEntity val, PersistField typ) =>
EntityField val typ
-> SqlExpr (Value typ) -> SqlExpr (Entity val) -> SqlExpr Update
/=. SqlExpr (Value a)
expr = forall val typ.
(PersistEntity val, PersistField typ) =>
EntityField val typ
-> (SqlExpr (Entity val) -> SqlExpr (Value typ))
-> SqlExpr (Entity val)
-> SqlExpr Update
setAux EntityField val a
field (\SqlExpr (Entity val)
ent -> SqlExpr (Entity val)
ent forall typ val.
(PersistEntity val, PersistField typ) =>
SqlExpr (Entity val) -> EntityField val typ -> SqlExpr (Value typ)
^. EntityField val a
field forall a.
PersistField a =>
SqlExpr (Value a) -> SqlExpr (Value a) -> SqlExpr (Value a)
/. SqlExpr (Value a)
expr)

-- | Apply a 'PersistField' constructor to @SqlExpr Value@ arguments.
(<#) :: (a -> b) -> SqlExpr (Value a) -> SqlExpr (Insertion b)
<# :: forall a b. (a -> b) -> SqlExpr (Value a) -> SqlExpr (Insertion b)
(<#) a -> b
_ (ERaw SqlExprMeta
_ NeedParens -> IdentInfo -> (Builder, [PersistValue])
f)        = forall a.
SqlExprMeta
-> (NeedParens -> IdentInfo -> (Builder, [PersistValue]))
-> SqlExpr a
ERaw SqlExprMeta
noMeta NeedParens -> IdentInfo -> (Builder, [PersistValue])
f

-- | Apply extra @SqlExpr Value@ arguments to a 'PersistField' constructor
(<&>) :: SqlExpr (Insertion (a -> b)) -> SqlExpr (Value a) -> SqlExpr (Insertion b)
(ERaw SqlExprMeta
_ NeedParens -> IdentInfo -> (Builder, [PersistValue])
f) <&> :: forall a b.
SqlExpr (Insertion (a -> b))
-> SqlExpr (Value a) -> SqlExpr (Insertion b)
<&> (ERaw SqlExprMeta
_ NeedParens -> IdentInfo -> (Builder, [PersistValue])
g) =
    forall a.
SqlExprMeta
-> (NeedParens -> IdentInfo -> (Builder, [PersistValue]))
-> SqlExpr a
ERaw SqlExprMeta
noMeta forall a b. (a -> b) -> a -> b
$ \NeedParens
_ IdentInfo
info ->
        let (Builder
fb, [PersistValue]
fv) = NeedParens -> IdentInfo -> (Builder, [PersistValue])
f NeedParens
Never IdentInfo
info
            (Builder
gb, [PersistValue]
gv) = NeedParens -> IdentInfo -> (Builder, [PersistValue])
g NeedParens
Never IdentInfo
info
        in (Builder
fb forall a. Semigroup a => a -> a -> a
<> Builder
", " forall a. Semigroup a => a -> a -> a
<> Builder
gb, [PersistValue]
fv forall a. [a] -> [a] -> [a]
++ [PersistValue]
gv)

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

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

{-# DEPRECATED random_ "Since 2.6.0: `random_` is not uniform across all databases! Please use a specific one such as 'Database.Esqueleto.PostgreSQL.random_', 'Database.Esqueleto.MySQL.random_', or 'Database.Esqueleto.SQLite.random_'" #-}

{-# DEPRECATED rand "Since 2.6.0: `rand` ordering function is not uniform across all databases! To avoid accidental partiality it will be removed in the next major version." #-}

-- Fixity declarations
infixl 9 ^.
infixl 7 *., /.
infixl 6 +., -.
infixr 5 ++.
infix  4 ==., >=., >., <=., <., !=.
infixr 3 &&., =., +=., -=., *=., /=.
infixr 2 ||., `like`, `ilike`
infixl 2 `InnerJoin`, `CrossJoin`, `LeftOuterJoin`, `RightOuterJoin`, `FullOuterJoin`

-- | Syntax sugar for 'case_'.
--
-- @since 2.1.2
when_ :: expr (Value Bool) -> () -> expr a -> (expr (Value Bool), expr a)
when_ :: forall (expr :: * -> *) a.
expr (Value Bool) -> () -> expr a -> (expr (Value Bool), expr a)
when_ expr (Value Bool)
cond ()
_ expr a
expr = (expr (Value Bool)
cond, expr a
expr)

-- | Syntax sugar for 'case_'.
--
-- @since 2.1.2
then_ :: ()
then_ :: ()
then_ = ()

-- | Syntax sugar for 'case_'.
--
-- @since 2.1.2
else_ :: expr a -> expr a
else_ :: forall (expr :: * -> *) a. expr a -> expr a
else_ = forall a. a -> a
id

-- | A single value (as opposed to a whole entity).  You may use
-- @('^.')@ or @('?.')@ to get a 'Value' from an 'Entity'.
newtype Value a = Value { forall a. Value a -> a
unValue :: a } deriving (Value a -> Value a -> Bool
forall a. Eq a => Value a -> Value a -> Bool
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: Value a -> Value a -> Bool
$c/= :: forall a. Eq a => Value a -> Value a -> Bool
== :: Value a -> Value a -> Bool
$c== :: forall a. Eq a => Value a -> Value a -> Bool
Eq, Value a -> Value a -> Bool
Value a -> Value a -> Ordering
Value a -> Value a -> Value a
forall a.
Eq a
-> (a -> a -> Ordering)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> a)
-> (a -> a -> a)
-> Ord a
forall {a}. Ord a => Eq (Value a)
forall a. Ord a => Value a -> Value a -> Bool
forall a. Ord a => Value a -> Value a -> Ordering
forall a. Ord a => Value a -> Value a -> Value a
min :: Value a -> Value a -> Value a
$cmin :: forall a. Ord a => Value a -> Value a -> Value a
max :: Value a -> Value a -> Value a
$cmax :: forall a. Ord a => Value a -> Value a -> Value a
>= :: Value a -> Value a -> Bool
$c>= :: forall a. Ord a => Value a -> Value a -> Bool
> :: Value a -> Value a -> Bool
$c> :: forall a. Ord a => Value a -> Value a -> Bool
<= :: Value a -> Value a -> Bool
$c<= :: forall a. Ord a => Value a -> Value a -> Bool
< :: Value a -> Value a -> Bool
$c< :: forall a. Ord a => Value a -> Value a -> Bool
compare :: Value a -> Value a -> Ordering
$ccompare :: forall a. Ord a => Value a -> Value a -> Ordering
Ord, Int -> Value a -> ShowS
forall a. Show a => Int -> Value a -> ShowS
forall a. Show a => [Value a] -> ShowS
forall a. Show a => Value a -> String
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [Value a] -> ShowS
$cshowList :: forall a. Show a => [Value a] -> ShowS
show :: Value a -> String
$cshow :: forall a. Show a => Value a -> String
showsPrec :: Int -> Value a -> ShowS
$cshowsPrec :: forall a. Show a => Int -> Value a -> ShowS
Show, Typeable)

-- | @since 1.4.4
instance Functor Value where
    fmap :: forall a b. (a -> b) -> Value a -> Value b
fmap a -> b
f (Value a
a) = forall a. a -> Value a
Value (a -> b
f a
a)

instance Applicative Value where
  <*> :: forall a b. Value (a -> b) -> Value a -> Value b
(<*>) (Value a -> b
f) (Value a
a) = forall a. a -> Value a
Value (a -> b
f a
a)
  pure :: forall a. a -> Value a
pure = forall a. a -> Value a
Value

instance Monad Value where
  >>= :: forall a b. Value a -> (a -> Value b) -> Value b
(>>=) Value a
x a -> Value b
f = forall a. Value a -> a
valueJoin forall a b. (a -> b) -> a -> b
$ forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap a -> Value b
f Value a
x
    where valueJoin :: Value a -> a
valueJoin (Value a
v) = a
v

-- | A list of single values.  There's a limited set of functions
-- able to work with this data type (such as 'subList_select',
-- 'valList', 'in_' and 'exists').
newtype ValueList a = ValueList a deriving (ValueList a -> ValueList a -> Bool
forall a. Eq a => ValueList a -> ValueList a -> Bool
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: ValueList a -> ValueList a -> Bool
$c/= :: forall a. Eq a => ValueList a -> ValueList a -> Bool
== :: ValueList a -> ValueList a -> Bool
$c== :: forall a. Eq a => ValueList a -> ValueList a -> Bool
Eq, ValueList a -> ValueList a -> Bool
ValueList a -> ValueList a -> Ordering
ValueList a -> ValueList a -> ValueList a
forall a.
Eq a
-> (a -> a -> Ordering)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> a)
-> (a -> a -> a)
-> Ord a
forall {a}. Ord a => Eq (ValueList a)
forall a. Ord a => ValueList a -> ValueList a -> Bool
forall a. Ord a => ValueList a -> ValueList a -> Ordering
forall a. Ord a => ValueList a -> ValueList a -> ValueList a
min :: ValueList a -> ValueList a -> ValueList a
$cmin :: forall a. Ord a => ValueList a -> ValueList a -> ValueList a
max :: ValueList a -> ValueList a -> ValueList a
$cmax :: forall a. Ord a => ValueList a -> ValueList a -> ValueList a
>= :: ValueList a -> ValueList a -> Bool
$c>= :: forall a. Ord a => ValueList a -> ValueList a -> Bool
> :: ValueList a -> ValueList a -> Bool
$c> :: forall a. Ord a => ValueList a -> ValueList a -> Bool
<= :: ValueList a -> ValueList a -> Bool
$c<= :: forall a. Ord a => ValueList a -> ValueList a -> Bool
< :: ValueList a -> ValueList a -> Bool
$c< :: forall a. Ord a => ValueList a -> ValueList a -> Bool
compare :: ValueList a -> ValueList a -> Ordering
$ccompare :: forall a. Ord a => ValueList a -> ValueList a -> Ordering
Ord, Int -> ValueList a -> ShowS
forall a. Show a => Int -> ValueList a -> ShowS
forall a. Show a => [ValueList a] -> ShowS
forall a. Show a => ValueList a -> String
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [ValueList a] -> ShowS
$cshowList :: forall a. Show a => [ValueList a] -> ShowS
show :: ValueList a -> String
$cshow :: forall a. Show a => ValueList a -> String
showsPrec :: Int -> ValueList a -> ShowS
$cshowsPrec :: forall a. Show a => Int -> ValueList a -> ShowS
Show, Typeable)

-- | A wrapper type for for any @expr (Value a)@ for all a.
data SomeValue where
    SomeValue :: 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 'groupBy' can take tuples, like
-- @'groupBy' (foo '^.' FooId, foo '^.' FooName, foo '^.' FooType)@.
class ToSomeValues a where
    toSomeValues :: a -> [SomeValue]

instance
    ( ToSomeValues a
    , ToSomeValues b
    )
  =>
    ToSomeValues (a, b)
  where
    toSomeValues :: (a, b) -> [SomeValue]
toSomeValues (a
a,b
b) = forall a. ToSomeValues a => a -> [SomeValue]
toSomeValues a
a forall a. [a] -> [a] -> [a]
++ forall a. ToSomeValues a => a -> [SomeValue]
toSomeValues b
b

instance
    ( ToSomeValues a
    , ToSomeValues b
    , ToSomeValues c
    )
  =>
    ToSomeValues (a, b, c)
  where
    toSomeValues :: (a, b, c) -> [SomeValue]
toSomeValues (a
a,b
b,c
c) = forall a. ToSomeValues a => a -> [SomeValue]
toSomeValues a
a forall a. [a] -> [a] -> [a]
++ forall a. ToSomeValues a => a -> [SomeValue]
toSomeValues b
b forall a. [a] -> [a] -> [a]
++ forall a. ToSomeValues a => a -> [SomeValue]
toSomeValues c
c

instance
    ( ToSomeValues a
    , ToSomeValues b
    , ToSomeValues c
    , ToSomeValues d
    )
  =>
    ToSomeValues (a, b, c, d)
  where
    toSomeValues :: (a, b, c, d) -> [SomeValue]
toSomeValues (a
a,b
b,c
c,d
d) =
        forall a. ToSomeValues a => a -> [SomeValue]
toSomeValues a
a forall a. [a] -> [a] -> [a]
++ forall a. ToSomeValues a => a -> [SomeValue]
toSomeValues b
b forall a. [a] -> [a] -> [a]
++ forall a. ToSomeValues a => a -> [SomeValue]
toSomeValues c
c forall a. [a] -> [a] -> [a]
++ forall a. ToSomeValues a => a -> [SomeValue]
toSomeValues d
d

instance
    ( ToSomeValues a
    , ToSomeValues b
    , ToSomeValues c
    , ToSomeValues d
    , ToSomeValues e
    )
  =>
    ToSomeValues (a, b, c, d, e)
  where
    toSomeValues :: (a, b, c, d, e) -> [SomeValue]
toSomeValues (a
a,b
b,c
c,d
d,e
e) = forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat
        [ forall a. ToSomeValues a => a -> [SomeValue]
toSomeValues a
a, forall a. ToSomeValues a => a -> [SomeValue]
toSomeValues b
b, forall a. ToSomeValues a => a -> [SomeValue]
toSomeValues c
c , forall a. ToSomeValues a => a -> [SomeValue]
toSomeValues d
d
        , forall a. ToSomeValues a => a -> [SomeValue]
toSomeValues e
e
        ]

instance
    ( ToSomeValues a
    , ToSomeValues b
    , ToSomeValues c
    , ToSomeValues d
    , ToSomeValues e
    , ToSomeValues f
    )
  =>
    ToSomeValues (a, b, c, d, e, f)
  where
    toSomeValues :: (a, b, c, d, e, f) -> [SomeValue]
toSomeValues (a
a,b
b,c
c,d
d,e
e,f
f) = forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat
        [ forall a. ToSomeValues a => a -> [SomeValue]
toSomeValues a
a, forall a. ToSomeValues a => a -> [SomeValue]
toSomeValues b
b, forall a. ToSomeValues a => a -> [SomeValue]
toSomeValues c
c, forall a. ToSomeValues a => a -> [SomeValue]
toSomeValues d
d
        , forall a. ToSomeValues a => a -> [SomeValue]
toSomeValues e
e , forall a. ToSomeValues a => a -> [SomeValue]
toSomeValues f
f
        ]

instance
    ( ToSomeValues a
    , ToSomeValues b
    , ToSomeValues c
    , ToSomeValues d
    , ToSomeValues e
    , ToSomeValues f
    , ToSomeValues g
    )
  =>
    ToSomeValues (a, b, c, d, e, f, g)
  where
    toSomeValues :: (a, b, c, d, e, f, g) -> [SomeValue]
toSomeValues (a
a,b
b,c
c,d
d,e
e,f
f,g
g) = forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat
        [ forall a. ToSomeValues a => a -> [SomeValue]
toSomeValues a
a,  forall a. ToSomeValues a => a -> [SomeValue]
toSomeValues b
b, forall a. ToSomeValues a => a -> [SomeValue]
toSomeValues c
c,  forall a. ToSomeValues a => a -> [SomeValue]
toSomeValues d
d
        , forall a. ToSomeValues a => a -> [SomeValue]
toSomeValues e
e,  forall a. ToSomeValues a => a -> [SomeValue]
toSomeValues f
f, forall a. ToSomeValues a => a -> [SomeValue]
toSomeValues g
g
        ]

instance
    ( ToSomeValues a
    , ToSomeValues b
    , ToSomeValues c
    , ToSomeValues d
    , ToSomeValues e
    , ToSomeValues f
    , ToSomeValues g
    , ToSomeValues h
    )
  =>
    ToSomeValues (a, b, c, d, e, f, g, h)
  where
    toSomeValues :: (a, b, c, d, e, f, g, h) -> [SomeValue]
toSomeValues (a
a,b
b,c
c,d
d,e
e,f
f,g
g,h
h) = forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat
        [ forall a. ToSomeValues a => a -> [SomeValue]
toSomeValues a
a, forall a. ToSomeValues a => a -> [SomeValue]
toSomeValues b
b, forall a. ToSomeValues a => a -> [SomeValue]
toSomeValues c
c, forall a. ToSomeValues a => a -> [SomeValue]
toSomeValues d
d
        , forall a. ToSomeValues a => a -> [SomeValue]
toSomeValues e
e, forall a. ToSomeValues a => a -> [SomeValue]
toSomeValues f
f, forall a. ToSomeValues a => a -> [SomeValue]
toSomeValues g
g, forall a. ToSomeValues a => a -> [SomeValue]
toSomeValues h
h
        ]

type family KnowResult a where
    KnowResult (i -> o) = KnowResult o
    KnowResult a = a

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

instance FinalResult (Unique val) where
  finalR :: Unique val -> KnowResult (Unique val)
finalR = forall a. a -> a
id

instance (FinalResult b) => FinalResult (a -> b) where
  finalR :: (a -> b) -> KnowResult (a -> b)
finalR a -> b
f = forall a. FinalResult a => a -> KnowResult a
finalR (a -> b
f forall a. HasCallStack => a
undefined)

-- | Convert a constructor for a 'Unique' key on a record to the 'UniqueDef'
-- 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.
--
-- @since 3.1.3
toUniqueDef
    :: forall a val.
    ( KnowResult a ~ Unique val
    , PersistEntity val
    , FinalResult a
    )
    => a
    -> UniqueDef
toUniqueDef :: forall a val.
(KnowResult a ~ Unique val, PersistEntity val, FinalResult a) =>
a -> UniqueDef
toUniqueDef a
uniqueConstructor = UniqueDef
uniqueDef
  where
    proxy :: Proxy val
    proxy :: Proxy val
proxy = forall {k} (t :: k). Proxy t
Proxy
    unique :: Unique val
    unique :: Unique val
unique = forall a. FinalResult a => a -> KnowResult a
finalR a
uniqueConstructor
    -- there must be a better way to get the constrain name from a unique, make this not a list search
    filterF :: UniqueDef -> Bool
filterF = forall a. Eq a => a -> a -> Bool
(==) (forall record.
PersistEntity record =>
Unique record -> NonEmpty (FieldNameHS, FieldNameDB)
persistUniqueToFieldNames Unique val
unique) forall b c a. (b -> c) -> (a -> b) -> a -> c
. UniqueDef -> NonEmpty (FieldNameHS, FieldNameDB)
uniqueFields
    uniqueDef :: UniqueDef
uniqueDef = forall a. [a] -> a
head forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a. (a -> Bool) -> [a] -> [a]
filter UniqueDef -> Bool
filterF forall b c a. (b -> c) -> (a -> b) -> a -> c
. EntityDef -> [UniqueDef]
getEntityUniques forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall record (proxy :: * -> *).
PersistEntity record =>
proxy record -> EntityDef
entityDef forall a b. (a -> b) -> a -> b
$ Proxy val
proxy

-- | Render updates to be use in a SET clause for a given sql backend.
--
-- @since 3.1.3
renderUpdates
    :: (BackendCompatible SqlBackend backend)
    => backend
    -> [SqlExpr (Entity val) -> SqlExpr Update]
    -> (TLB.Builder, [PersistValue])
renderUpdates :: forall backend val.
BackendCompatible SqlBackend backend =>
backend
-> [SqlExpr (Entity val) -> SqlExpr Update]
-> (Builder, [PersistValue])
renderUpdates backend
conn = forall a. Monoid a => [(Builder, a)] -> (Builder, a)
uncommas' forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap forall val.
(SqlExpr (Entity val) -> SqlExpr Update)
-> [(Builder, [PersistValue])]
renderUpdate
  where
    mk :: SqlExpr Update -> [(TLB.Builder, [PersistValue])]
    mk :: SqlExpr Update -> [(Builder, [PersistValue])]
mk (ERaw SqlExprMeta
_ NeedParens -> IdentInfo -> (Builder, [PersistValue])
f)             = [NeedParens -> IdentInfo -> (Builder, [PersistValue])
f NeedParens
Never IdentInfo
info]

    renderUpdate :: (SqlExpr (Entity val) -> SqlExpr Update) -> [(TLB.Builder, [PersistValue])]
    renderUpdate :: forall val.
(SqlExpr (Entity val) -> SqlExpr Update)
-> [(Builder, [PersistValue])]
renderUpdate SqlExpr (Entity val) -> SqlExpr Update
f = SqlExpr Update -> [(Builder, [PersistValue])]
mk (SqlExpr (Entity val) -> SqlExpr Update
f forall a. HasCallStack => a
undefined) -- second parameter of f is always unused
    info :: IdentInfo
info = (forall sup sub. BackendCompatible sup sub => sub -> sup
projectBackend backend
conn, IdentState
initialIdentState)

-- | Data type that represents an @INNER JOIN@ (see 'LeftOuterJoin' for an example).
data InnerJoin a b = a `InnerJoin` b

-- | Data type that represents a @CROSS JOIN@ (see 'LeftOuterJoin' for an example).
data CrossJoin a b = a `CrossJoin` b

-- | Data type that represents a @LEFT OUTER JOIN@. For example,
--
-- @
-- select $
-- 'from' $ \\(person `'LeftOuterJoin`` pet) ->
--   ...
-- @
--
-- is translated into
--
-- @
-- SELECT ...
-- FROM Person LEFT OUTER JOIN Pet
-- ...
-- @
--
-- See also: 'from'.
data LeftOuterJoin a b = a `LeftOuterJoin` b

-- | Data type that represents a @RIGHT OUTER JOIN@ (see 'LeftOuterJoin' for an example).
data RightOuterJoin a b = a `RightOuterJoin` b

-- | Data type that represents a @FULL OUTER JOIN@ (see 'LeftOuterJoin' for an example).
data FullOuterJoin a b = a `FullOuterJoin` b


-- | (Internal) A kind of @JOIN@.
data JoinKind
    = InnerJoinKind      -- ^ @INNER JOIN@
    | CrossJoinKind      -- ^ @CROSS JOIN@
    | LeftOuterJoinKind  -- ^ @LEFT OUTER JOIN@
    | RightOuterJoinKind -- ^ @RIGHT OUTER JOIN@
    | FullOuterJoinKind  -- ^ @FULL OUTER JOIN@
    deriving (JoinKind -> JoinKind -> Bool
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: JoinKind -> JoinKind -> Bool
$c/= :: JoinKind -> JoinKind -> Bool
== :: JoinKind -> JoinKind -> Bool
$c== :: JoinKind -> JoinKind -> Bool
Eq, Int -> JoinKind -> ShowS
[JoinKind] -> ShowS
JoinKind -> String
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [JoinKind] -> ShowS
$cshowList :: [JoinKind] -> ShowS
show :: JoinKind -> String
$cshow :: JoinKind -> String
showsPrec :: Int -> JoinKind -> ShowS
$cshowsPrec :: Int -> JoinKind -> ShowS
Show)


-- | (Internal) Functions that operate on types (that should be)
-- of kind 'JoinKind'.
class IsJoinKind join where
    -- | (Internal) @smartJoin a b@ is a @JOIN@ of the correct kind.
    smartJoin :: a -> b -> join a b
    -- | (Internal) Reify a @JoinKind@ from a @JOIN@.  This
    -- function is non-strict.
    reifyJoinKind :: join a b -> JoinKind

instance IsJoinKind InnerJoin where
    smartJoin :: forall a b. a -> b -> InnerJoin a b
smartJoin a
a b
b = a
a forall a b. a -> b -> InnerJoin a b
`InnerJoin` b
b
    reifyJoinKind :: forall a b. InnerJoin a b -> JoinKind
reifyJoinKind InnerJoin a b
_ = JoinKind
InnerJoinKind
instance IsJoinKind CrossJoin where
    smartJoin :: forall a b. a -> b -> CrossJoin a b
smartJoin a
a b
b = a
a forall a b. a -> b -> CrossJoin a b
`CrossJoin` b
b
    reifyJoinKind :: forall a b. CrossJoin a b -> JoinKind
reifyJoinKind CrossJoin a b
_ = JoinKind
CrossJoinKind
instance IsJoinKind LeftOuterJoin where
    smartJoin :: forall a b. a -> b -> LeftOuterJoin a b
smartJoin a
a b
b = a
a forall a b. a -> b -> LeftOuterJoin a b
`LeftOuterJoin` b
b
    reifyJoinKind :: forall a b. LeftOuterJoin a b -> JoinKind
reifyJoinKind LeftOuterJoin a b
_ = JoinKind
LeftOuterJoinKind
instance IsJoinKind RightOuterJoin where
    smartJoin :: forall a b. a -> b -> RightOuterJoin a b
smartJoin a
a b
b = a
a forall a b. a -> b -> RightOuterJoin a b
`RightOuterJoin` b
b
    reifyJoinKind :: forall a b. RightOuterJoin a b -> JoinKind
reifyJoinKind RightOuterJoin a b
_ = JoinKind
RightOuterJoinKind
instance IsJoinKind FullOuterJoin where
    smartJoin :: forall a b. a -> b -> FullOuterJoin a b
smartJoin a
a b
b = a
a forall a b. a -> b -> FullOuterJoin a b
`FullOuterJoin` b
b
    reifyJoinKind :: forall a b. FullOuterJoin a b -> JoinKind
reifyJoinKind FullOuterJoin a b
_ = JoinKind
FullOuterJoinKind


-- | Exception thrown whenever 'on' is used to create an @ON@
-- clause but no matching @JOIN@ is found.
data OnClauseWithoutMatchingJoinException =
    OnClauseWithoutMatchingJoinException String
    deriving (OnClauseWithoutMatchingJoinException
-> OnClauseWithoutMatchingJoinException -> Bool
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: OnClauseWithoutMatchingJoinException
-> OnClauseWithoutMatchingJoinException -> Bool
$c/= :: OnClauseWithoutMatchingJoinException
-> OnClauseWithoutMatchingJoinException -> Bool
== :: OnClauseWithoutMatchingJoinException
-> OnClauseWithoutMatchingJoinException -> Bool
$c== :: OnClauseWithoutMatchingJoinException
-> OnClauseWithoutMatchingJoinException -> Bool
Eq, Eq OnClauseWithoutMatchingJoinException
OnClauseWithoutMatchingJoinException
-> OnClauseWithoutMatchingJoinException -> Bool
OnClauseWithoutMatchingJoinException
-> OnClauseWithoutMatchingJoinException -> Ordering
OnClauseWithoutMatchingJoinException
-> OnClauseWithoutMatchingJoinException
-> OnClauseWithoutMatchingJoinException
forall a.
Eq a
-> (a -> a -> Ordering)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> a)
-> (a -> a -> a)
-> Ord a
min :: OnClauseWithoutMatchingJoinException
-> OnClauseWithoutMatchingJoinException
-> OnClauseWithoutMatchingJoinException
$cmin :: OnClauseWithoutMatchingJoinException
-> OnClauseWithoutMatchingJoinException
-> OnClauseWithoutMatchingJoinException
max :: OnClauseWithoutMatchingJoinException
-> OnClauseWithoutMatchingJoinException
-> OnClauseWithoutMatchingJoinException
$cmax :: OnClauseWithoutMatchingJoinException
-> OnClauseWithoutMatchingJoinException
-> OnClauseWithoutMatchingJoinException
>= :: OnClauseWithoutMatchingJoinException
-> OnClauseWithoutMatchingJoinException -> Bool
$c>= :: OnClauseWithoutMatchingJoinException
-> OnClauseWithoutMatchingJoinException -> Bool
> :: OnClauseWithoutMatchingJoinException
-> OnClauseWithoutMatchingJoinException -> Bool
$c> :: OnClauseWithoutMatchingJoinException
-> OnClauseWithoutMatchingJoinException -> Bool
<= :: OnClauseWithoutMatchingJoinException
-> OnClauseWithoutMatchingJoinException -> Bool
$c<= :: OnClauseWithoutMatchingJoinException
-> OnClauseWithoutMatchingJoinException -> Bool
< :: OnClauseWithoutMatchingJoinException
-> OnClauseWithoutMatchingJoinException -> Bool
$c< :: OnClauseWithoutMatchingJoinException
-> OnClauseWithoutMatchingJoinException -> Bool
compare :: OnClauseWithoutMatchingJoinException
-> OnClauseWithoutMatchingJoinException -> Ordering
$ccompare :: OnClauseWithoutMatchingJoinException
-> OnClauseWithoutMatchingJoinException -> Ordering
Ord, Int -> OnClauseWithoutMatchingJoinException -> ShowS
[OnClauseWithoutMatchingJoinException] -> ShowS
OnClauseWithoutMatchingJoinException -> String
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [OnClauseWithoutMatchingJoinException] -> ShowS
$cshowList :: [OnClauseWithoutMatchingJoinException] -> ShowS
show :: OnClauseWithoutMatchingJoinException -> String
$cshow :: OnClauseWithoutMatchingJoinException -> String
showsPrec :: Int -> OnClauseWithoutMatchingJoinException -> ShowS
$cshowsPrec :: Int -> OnClauseWithoutMatchingJoinException -> ShowS
Show, Typeable)

instance Exception OnClauseWithoutMatchingJoinException

-- | Phantom type used by 'orderBy', 'asc' and 'desc'.
data OrderBy

-- | Phantom type used by 'distinctOn' and 'don'.
data DistinctOn

-- | Phantom type for a @SET@ operation on an entity of the given
-- type (see 'set' and '(=.)').
data Update

-- | Phantom type used by 'insertSelect'.
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:
--
-- @
-- a :& b :& c == ((a :& b) :& c)
-- @
--
-- See the examples at the beginning of this module to see how this
-- operator is used in 'JOIN' operations.
data (:&) a b = a :& b
    deriving ((a :& b) -> (a :& b) -> Bool
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
forall a b. (Eq a, Eq b) => (a :& b) -> (a :& b) -> Bool
/= :: (a :& b) -> (a :& b) -> Bool
$c/= :: forall a b. (Eq a, Eq b) => (a :& b) -> (a :& b) -> Bool
== :: (a :& b) -> (a :& b) -> Bool
$c== :: forall a b. (Eq a, Eq b) => (a :& b) -> (a :& b) -> Bool
Eq, Int -> (a :& b) -> ShowS
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
forall a b. (Show a, Show b) => Int -> (a :& b) -> ShowS
forall a b. (Show a, Show b) => [a :& b] -> ShowS
forall a b. (Show a, Show b) => (a :& b) -> String
showList :: [a :& b] -> ShowS
$cshowList :: forall a b. (Show a, Show b) => [a :& b] -> ShowS
show :: (a :& b) -> String
$cshow :: forall a b. (Show a, Show b) => (a :& b) -> String
showsPrec :: Int -> (a :& b) -> ShowS
$cshowsPrec :: forall a b. (Show a, Show b) => Int -> (a :& b) -> ShowS
Show)
infixl 2 :&

-- | Different kinds of locking clauses supported by 'locking'.
--
-- Note that each RDBMS has different locking support.  The
-- constructors of this datatype specify only the /syntax/ of the
-- locking mechanism, not its /semantics/.  For example, even
-- though both MySQL and PostgreSQL support 'ForUpdate', there
-- are no guarantees that they will behave the same.
--
-- @since 2.2.7
data LockingKind
    = ForUpdate
      -- ^ @FOR UPDATE@ syntax.  Supported by MySQL, Oracle and
      -- PostgreSQL.
      --
      -- @since 2.2.7
    | ForUpdateSkipLocked
      -- ^ @FOR UPDATE SKIP LOCKED@ syntax.  Supported by MySQL, Oracle and
      -- PostgreSQL.
      --
      -- @since 2.2.7
    | ForShare
      -- ^ @FOR SHARE@ syntax.  Supported by PostgreSQL.
      --
      -- @since 2.2.7
    | LockInShareMode
      -- ^ @LOCK IN SHARE MODE@ syntax.  Supported by MySQL.
      --
      -- @since 2.2.7

-- | Postgres specific locking, used only internally
--
-- @since 3.5.9.0
data PostgresLockingKind =
    PostgresLockingKind
        {
          PostgresLockingKind -> PostgresRowLevelLockStrength
postgresRowLevelLockStrength :: PostgresRowLevelLockStrength
        , PostgresLockingKind -> Maybe LockingOfClause
postgresLockingOfClause :: Maybe LockingOfClause
        , PostgresLockingKind -> OnLockedBehavior
postgresOnLockedBehavior :: OnLockedBehavior
        }

-- Arranged in order of lock strength
data PostgresRowLevelLockStrength =
    PostgresForUpdate
    | PostgresForShare
  deriving (Eq PostgresRowLevelLockStrength
PostgresRowLevelLockStrength
-> PostgresRowLevelLockStrength -> Bool
PostgresRowLevelLockStrength
-> PostgresRowLevelLockStrength -> Ordering
PostgresRowLevelLockStrength
-> PostgresRowLevelLockStrength -> PostgresRowLevelLockStrength
forall a.
Eq a
-> (a -> a -> Ordering)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> a)
-> (a -> a -> a)
-> Ord a
min :: PostgresRowLevelLockStrength
-> PostgresRowLevelLockStrength -> PostgresRowLevelLockStrength
$cmin :: PostgresRowLevelLockStrength
-> PostgresRowLevelLockStrength -> PostgresRowLevelLockStrength
max :: PostgresRowLevelLockStrength
-> PostgresRowLevelLockStrength -> PostgresRowLevelLockStrength
$cmax :: PostgresRowLevelLockStrength
-> PostgresRowLevelLockStrength -> PostgresRowLevelLockStrength
>= :: PostgresRowLevelLockStrength
-> PostgresRowLevelLockStrength -> Bool
$c>= :: PostgresRowLevelLockStrength
-> PostgresRowLevelLockStrength -> Bool
> :: PostgresRowLevelLockStrength
-> PostgresRowLevelLockStrength -> Bool
$c> :: PostgresRowLevelLockStrength
-> PostgresRowLevelLockStrength -> Bool
<= :: PostgresRowLevelLockStrength
-> PostgresRowLevelLockStrength -> Bool
$c<= :: PostgresRowLevelLockStrength
-> PostgresRowLevelLockStrength -> Bool
< :: PostgresRowLevelLockStrength
-> PostgresRowLevelLockStrength -> Bool
$c< :: PostgresRowLevelLockStrength
-> PostgresRowLevelLockStrength -> Bool
compare :: PostgresRowLevelLockStrength
-> PostgresRowLevelLockStrength -> Ordering
$ccompare :: PostgresRowLevelLockStrength
-> PostgresRowLevelLockStrength -> Ordering
Ord, PostgresRowLevelLockStrength
-> PostgresRowLevelLockStrength -> Bool
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: PostgresRowLevelLockStrength
-> PostgresRowLevelLockStrength -> Bool
$c/= :: PostgresRowLevelLockStrength
-> PostgresRowLevelLockStrength -> Bool
== :: PostgresRowLevelLockStrength
-> PostgresRowLevelLockStrength -> Bool
$c== :: PostgresRowLevelLockStrength
-> PostgresRowLevelLockStrength -> Bool
Eq)

data LockingOfClause where
    LockingOfClause :: LockableEntity a => a -> LockingOfClause

data OnLockedBehavior =
    NoWait
    -- ^ @NOWAIT@ syntax locking behaviour.
    --  query excutes immediately failing on locked rows
    --
    -- @since 3.5.9.0
      | SkipLocked
    -- ^ @SKIP LOCKED@ syntax locking behaviour.
    --  query skips locked rows
    --
    -- @since 3.5.9.0
      | Wait
    -- ^ default locking behaviour.
    --  query will wait on locked rows
    --
    -- @since 3.5.9.0
      deriving (Eq OnLockedBehavior
OnLockedBehavior -> OnLockedBehavior -> Bool
OnLockedBehavior -> OnLockedBehavior -> Ordering
OnLockedBehavior -> OnLockedBehavior -> OnLockedBehavior
forall a.
Eq a
-> (a -> a -> Ordering)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> a)
-> (a -> a -> a)
-> Ord a
min :: OnLockedBehavior -> OnLockedBehavior -> OnLockedBehavior
$cmin :: OnLockedBehavior -> OnLockedBehavior -> OnLockedBehavior
max :: OnLockedBehavior -> OnLockedBehavior -> OnLockedBehavior
$cmax :: OnLockedBehavior -> OnLockedBehavior -> OnLockedBehavior
>= :: OnLockedBehavior -> OnLockedBehavior -> Bool
$c>= :: OnLockedBehavior -> OnLockedBehavior -> Bool
> :: OnLockedBehavior -> OnLockedBehavior -> Bool
$c> :: OnLockedBehavior -> OnLockedBehavior -> Bool
<= :: OnLockedBehavior -> OnLockedBehavior -> Bool
$c<= :: OnLockedBehavior -> OnLockedBehavior -> Bool
< :: OnLockedBehavior -> OnLockedBehavior -> Bool
$c< :: OnLockedBehavior -> OnLockedBehavior -> Bool
compare :: OnLockedBehavior -> OnLockedBehavior -> Ordering
$ccompare :: OnLockedBehavior -> OnLockedBehavior -> Ordering
Ord, OnLockedBehavior -> OnLockedBehavior -> Bool
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: OnLockedBehavior -> OnLockedBehavior -> Bool
$c/= :: OnLockedBehavior -> OnLockedBehavior -> Bool
== :: OnLockedBehavior -> OnLockedBehavior -> Bool
$c== :: OnLockedBehavior -> OnLockedBehavior -> Bool
Eq, Int -> OnLockedBehavior -> ShowS
[OnLockedBehavior] -> ShowS
OnLockedBehavior -> String
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [OnLockedBehavior] -> ShowS
$cshowList :: [OnLockedBehavior] -> ShowS
show :: OnLockedBehavior -> String
$cshow :: OnLockedBehavior -> String
showsPrec :: Int -> OnLockedBehavior -> ShowS
$cshowsPrec :: Int -> OnLockedBehavior -> ShowS
Show)


-- | Lockable entity
--
-- Example use:
--
-- @
-- select $ do
--     (p :& bp) <- from $
--         table @Person
--         `innerJoin` table @BlogPost
--             `on` do
--                 \(p :& bp) -> p ^. PersonId ==. b ^. BlogPostAuthorId
--     forUpdateOf (p :& b) skipLocked
--     return p
-- @
class LockableEntity a where
    flattenLockableEntity :: a -> NonEmpty LockableSqlExpr

makeLockableEntity :: LockableEntity a => IdentInfo -> a -> (TLB.Builder, [PersistValue])
makeLockableEntity :: forall a.
LockableEntity a =>
IdentInfo -> a -> (Builder, [PersistValue])
makeLockableEntity IdentInfo
info a
lockableEntity =
    forall a. Monoid a => [(Builder, a)] -> (Builder, a)
uncommas' forall a b. (a -> b) -> a -> b
$ forall a. Set a -> [a]
Set.toList forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a. Ord a => [a] -> Set a
Set.fromList forall a b. (a -> b) -> a -> b
$ (\(LockableSqlExpr (ERaw SqlExprMeta
_ NeedParens -> IdentInfo -> (Builder, [PersistValue])
f)) -> NeedParens -> IdentInfo -> (Builder, [PersistValue])
f NeedParens
Never IdentInfo
info) forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> forall a. NonEmpty a -> [a]
NEL.toList (forall a. LockableEntity a => a -> NonEmpty LockableSqlExpr
flattenLockableEntity a
lockableEntity)

instance PersistEntity val => LockableEntity (SqlExpr (Entity val)) where
    flattenLockableEntity :: SqlExpr (Entity val) -> NonEmpty LockableSqlExpr
flattenLockableEntity SqlExpr (Entity val)
e = forall a. PersistEntity a => SqlExpr (Entity a) -> LockableSqlExpr
LockableSqlExpr SqlExpr (Entity val)
e forall a. a -> [a] -> NonEmpty a
:| []

instance (LockableEntity a, LockableEntity b) => LockableEntity (a :& b) where
    flattenLockableEntity :: (a :& b) -> NonEmpty LockableSqlExpr
flattenLockableEntity (a
a :& b
b) = forall a. LockableEntity a => a -> NonEmpty LockableSqlExpr
flattenLockableEntity a
a forall a. Semigroup a => a -> a -> a
<> forall a. LockableEntity a => a -> NonEmpty LockableSqlExpr
flattenLockableEntity b
b

data LockableSqlExpr where
    LockableSqlExpr :: 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 @newtype@, feel free to make
-- it an instance of this class.
--
-- @since 2.4.0
class PersistField a => SqlString a where

-- | @since 2.3.0
instance (a ~ Char) => SqlString [a] where

-- | @since 2.3.0
instance SqlString T.Text where

-- | @since 2.3.0
instance SqlString TL.Text where

-- | @since 2.3.0
instance SqlString B.ByteString where

-- | @since 2.3.0
instance SqlString Html where

-- | @since 2.4.0
instance SqlString a => SqlString (Maybe a) where

-- | Class that enables one to use 'toBaseId' to convert an entity's
-- key on a query into another (cf. 'toBaseId').
class ToBaseId ent where
    -- | e.g. @type BaseEnt MyBase = MyChild@
    type BaseEnt ent :: Type
    -- | 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 :: Key (BaseEnt ent) -> Key ent


-- | @FROM@ clause: bring entities into scope.
--
-- Note that this function will be replaced by the one in
-- "Database.Esqueleto.Experimental" in version 4.0.0.0 of the library. The
-- @Experimental@ 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 @from@ with the
-- following types:
--
--  * @expr (Entity val)@, which brings a single entity into
--  scope.
--
--  * @expr (Maybe (Entity val))@, which brings a single entity
--  that may be @NULL@ into scope.  Used for @OUTER JOIN@s.
--
--  * A @JOIN@ of any other two types allowed by the innermost
--  magic, where a @JOIN@ may be an 'InnerJoin', a 'CrossJoin', a
--  'LeftOuterJoin', a 'RightOuterJoin', or a 'FullOuterJoin'.
--  The @JOINs@ have left fixity.
--
-- The outermost magic allows you to use @from@ on any tuples of
-- types supported by innermost magic (and also tuples of tuples,
-- and so on), up to 8-tuples.
--
-- Note that using @from@ for the same entity twice does work and
-- corresponds to a self-join.  You don't even need to use two
-- different calls to @from@, you may use a @JOIN@ or a tuple.
--
-- The following are valid examples of uses of @from@ (the types
-- of the arguments of the lambda are inside square brackets):
--
-- @
-- 'from' $ \\person -> ...
-- 'from' $ \\(person, blogPost) -> ...
-- 'from' $ \\(p `'LeftOuterJoin`` mb) -> ...
-- 'from' $ \\(p1 `'InnerJoin`` f `'InnerJoin`` p2) -> ...
-- 'from' $ \\((p1 `'InnerJoin`` f) `'InnerJoin`` p2) -> ...
-- @
--
-- The types of the arguments to the lambdas above are,
-- respectively:
--
-- @
-- person
--   :: ( Esqueleto query expr backend
--      , PersistEntity Person
--      , PersistEntityBackend Person ~ backend
--      ) => expr (Entity Person)
-- (person, blogPost)
--   :: (...) => (expr (Entity Person), expr (Entity BlogPost))
-- (p `'LeftOuterJoin`` mb)
--   :: (...) => InnerJoin (expr (Entity Person)) (expr (Maybe (Entity BlogPost)))
-- (p1 `'InnerJoin`` f `'InnerJoin`` p2)
--   :: (...) => InnerJoin
--                 (InnerJoin (expr (Entity Person))
--                            (expr (Entity Follow)))
--                 (expr (Entity Person))
-- (p1 `'InnerJoin`` (f `'InnerJoin`` p2)) ::
--   :: (...) => InnerJoin
--                 (expr (Entity Person))
--                 (InnerJoin (expr (Entity Follow))
--                            (expr (Entity Person)))
-- @
--
-- Note that some backends may not support all kinds of @JOIN@s.
from :: From a => (a -> SqlQuery b) -> SqlQuery b
from :: forall a b. From a => (a -> SqlQuery b) -> SqlQuery b
from = (forall a. From a => SqlQuery a
from_ forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>=)


-- | (Internal) Class that implements the tuple 'from' magic (see
-- 'fromStart').
class From a where
    from_ :: SqlQuery a

instance
    ( FromPreprocess (SqlExpr (Entity val))
    )
  =>
    From (SqlExpr (Entity val))
  where
    from_ :: SqlQuery (SqlExpr (Entity val))
from_ = forall a. FromPreprocess a => SqlQuery (PreprocessedFrom a)
fromPreprocess forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= forall a. PreprocessedFrom a -> SqlQuery a
fromFinish

instance
    ( FromPreprocess (SqlExpr (Maybe (Entity val)))
    )
  =>
    From (SqlExpr (Maybe (Entity val)))
  where
    from_ :: SqlQuery (SqlExpr (Maybe (Entity val)))
from_ = forall a. FromPreprocess a => SqlQuery (PreprocessedFrom a)
fromPreprocess forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= forall a. PreprocessedFrom a -> SqlQuery a
fromFinish

instance
    ( FromPreprocess (InnerJoin a b)
    )
  =>
    From (InnerJoin a b)
  where
    from_ :: SqlQuery (InnerJoin a b)
from_ = forall a. FromPreprocess a => SqlQuery (PreprocessedFrom a)
fromPreprocess forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= forall a. PreprocessedFrom a -> SqlQuery a
fromFinish

instance
    ( FromPreprocess (CrossJoin a b)
    )
  =>
    From (CrossJoin a b)
  where
    from_ :: SqlQuery (CrossJoin a b)
from_ = forall a. FromPreprocess a => SqlQuery (PreprocessedFrom a)
fromPreprocess forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= forall a. PreprocessedFrom a -> SqlQuery a
fromFinish

instance (FromPreprocess (LeftOuterJoin a b)) => From (LeftOuterJoin a b) where
    from_ :: SqlQuery (LeftOuterJoin a b)
from_ = forall a. FromPreprocess a => SqlQuery (PreprocessedFrom a)
fromPreprocess forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= forall a. PreprocessedFrom a -> SqlQuery a
fromFinish

instance (FromPreprocess (RightOuterJoin a b)) => From (RightOuterJoin a b) where
    from_ :: SqlQuery (RightOuterJoin a b)
from_ = forall a. FromPreprocess a => SqlQuery (PreprocessedFrom a)
fromPreprocess forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= forall a. PreprocessedFrom a -> SqlQuery a
fromFinish

instance (FromPreprocess (FullOuterJoin a b)) => From (FullOuterJoin a b) where
    from_ :: SqlQuery (FullOuterJoin a b)
from_ = forall a. FromPreprocess a => SqlQuery (PreprocessedFrom a)
fromPreprocess forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= forall a. PreprocessedFrom a -> SqlQuery a
fromFinish

instance (From a, From b) => From (a, b) where
    from_ :: SqlQuery (a, b)
from_ = (,) forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> forall a. From a => SqlQuery a
from_ forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> forall a. From a => SqlQuery a
from_

instance (From a, From b, From c) => From (a, b, c) where
    from_ :: SqlQuery (a, b, c)
from_ = (,,) forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> forall a. From a => SqlQuery a
from_ forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> forall a. From a => SqlQuery a
from_ forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> forall a. From a => SqlQuery a
from_

instance (From a, From b, From c, From d) => From (a, b, c, d) where
    from_ :: SqlQuery (a, b, c, d)
from_ = (,,,) forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> forall a. From a => SqlQuery a
from_ forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> forall a. From a => SqlQuery a
from_ forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> forall a. From a => SqlQuery a
from_ forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> forall a. From a => SqlQuery a
from_

instance (From a, From b, From c, From d, From e) => From (a, b, c, d, e) where
    from_ :: SqlQuery (a, b, c, d, e)
from_ = (,,,,) forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> forall a. From a => SqlQuery a
from_ forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> forall a. From a => SqlQuery a
from_ forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> forall a. From a => SqlQuery a
from_ forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> forall a. From a => SqlQuery a
from_ forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> forall a. From a => SqlQuery a
from_

instance
    (From a, From b, From c, From d, From e, From f)
  =>
    From (a, b, c, d, e, f)
  where
    from_ :: SqlQuery (a, b, c, d, e, f)
from_ = (,,,,,) forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> forall a. From a => SqlQuery a
from_ forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> forall a. From a => SqlQuery a
from_ forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> forall a. From a => SqlQuery a
from_ forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> forall a. From a => SqlQuery a
from_ forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> forall a. From a => SqlQuery a
from_ forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> forall a. From a => SqlQuery a
from_

instance
    (From a, From b, From c, From d, From e, From f, From g)
  =>
    From (a, b, c, d, e, f, g)
  where
    from_ :: SqlQuery (a, b, c, d, e, f, g)
from_ =
        (,,,,,,) forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> forall a. From a => SqlQuery a
from_ forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> forall a. From a => SqlQuery a
from_ forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> forall a. From a => SqlQuery a
from_ forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> forall a. From a => SqlQuery a
from_ forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> forall a. From a => SqlQuery a
from_ forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> forall a. From a => SqlQuery a
from_ forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> forall a. From a => SqlQuery a
from_

instance
    (From a, From b, From c, From d, From e, From f, From g, From h)
  =>
    From (a, b, c, d, e, f, g, h)
  where
    from_ :: SqlQuery (a, b, c, d, e, f, g, h)
from_ =
        (,,,,,,,) forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> forall a. From a => SqlQuery a
from_ forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> forall a. From a => SqlQuery a
from_ forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> forall a. From a => SqlQuery a
from_ forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> forall a. From a => SqlQuery a
from_ forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> forall a. From a => SqlQuery a
from_ forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> forall a. From a => SqlQuery a
from_ forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> forall a. From a => SqlQuery a
from_ forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> forall a. From a => SqlQuery a
from_



-- | (Internal) Class that implements the @JOIN@ 'from' magic
-- (see 'fromStart').
class FromPreprocess a where
    fromPreprocess :: SqlQuery (PreprocessedFrom a)

instance
    (PersistEntity val, BackendCompatible SqlBackend (PersistEntityBackend val))
  =>
    FromPreprocess (SqlExpr (Entity val))
  where
    fromPreprocess :: SqlQuery (PreprocessedFrom (SqlExpr (Entity val)))
fromPreprocess = forall a.
(PersistEntity a,
 BackendCompatible SqlBackend (PersistEntityBackend a)) =>
SqlQuery (PreprocessedFrom (SqlExpr (Entity a)))
fromStart

instance
    (PersistEntity val, BackendCompatible SqlBackend (PersistEntityBackend val))
  =>
    FromPreprocess (SqlExpr (Maybe (Entity val)))
  where
    fromPreprocess :: SqlQuery (PreprocessedFrom (SqlExpr (Maybe (Entity val))))
fromPreprocess = forall a.
(PersistEntity a,
 BackendCompatible SqlBackend (PersistEntityBackend a)) =>
SqlQuery (PreprocessedFrom (SqlExpr (Maybe (Entity a))))
fromStartMaybe

instance
    (FromPreprocess a, FromPreprocess b, IsJoinKind join)
  =>
    FromPreprocess (join a b)
  where
    fromPreprocess :: SqlQuery (PreprocessedFrom (join a b))
fromPreprocess = do
        PreprocessedFrom a
a <- forall a. FromPreprocess a => SqlQuery (PreprocessedFrom a)
fromPreprocess
        PreprocessedFrom b
b <- forall a. FromPreprocess a => SqlQuery (PreprocessedFrom a)
fromPreprocess
        forall (join :: * -> * -> *) a b.
IsJoinKind join =>
PreprocessedFrom a
-> PreprocessedFrom b -> SqlQuery (PreprocessedFrom (join a b))
fromJoin PreprocessedFrom a
a PreprocessedFrom b
b

-- | Exception data type for @esqueleto@ internal errors
data EsqueletoError
    = CompositeKeyErr CompositeKeyError
    | AliasedValueErr UnexpectedValueError
    | UnexpectedCaseErr UnexpectedCaseError
    | SqlBinOpCompositeErr SqlBinOpCompositeError
    deriving (Int -> EsqueletoError -> ShowS
[EsqueletoError] -> ShowS
EsqueletoError -> String
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [EsqueletoError] -> ShowS
$cshowList :: [EsqueletoError] -> ShowS
show :: EsqueletoError -> String
$cshow :: EsqueletoError -> String
showsPrec :: Int -> EsqueletoError -> ShowS
$cshowsPrec :: Int -> EsqueletoError -> ShowS
Show)

instance Exception EsqueletoError

data UnexpectedValueError
    = NotError
    | ToInsertionError
    | CombineInsertionError
    | FoldHelpError
    | SqlCaseError
    | SqlCastAsError
    | SqlFunctionError
    | MakeOnClauseError
    | MakeExcError
    | MakeSetError
    | MakeWhereError
    | MakeHavingError
    | FilterWhereAggError
    | FilterWhereClauseError
    deriving (Int -> UnexpectedValueError -> ShowS
[UnexpectedValueError] -> ShowS
UnexpectedValueError -> String
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [UnexpectedValueError] -> ShowS
$cshowList :: [UnexpectedValueError] -> ShowS
show :: UnexpectedValueError -> String
$cshow :: UnexpectedValueError -> String
showsPrec :: Int -> UnexpectedValueError -> ShowS
$cshowsPrec :: Int -> UnexpectedValueError -> ShowS
Show)

type CompositeKeyError = UnexpectedValueError

data UnexpectedCaseError
    = EmptySqlExprValueList
    | MakeFromError
    | UnsupportedSqlInsertIntoType
    | InsertionFinalError
    | NewIdentForError
    | UnsafeSqlCaseError
    | OperationNotSupported
    | NotImplemented
    deriving (Int -> UnexpectedCaseError -> ShowS
[UnexpectedCaseError] -> ShowS
UnexpectedCaseError -> String
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [UnexpectedCaseError] -> ShowS
$cshowList :: [UnexpectedCaseError] -> ShowS
show :: UnexpectedCaseError -> String
$cshow :: UnexpectedCaseError -> String
showsPrec :: Int -> UnexpectedCaseError -> ShowS
$cshowsPrec :: Int -> UnexpectedCaseError -> ShowS
Show)

data SqlBinOpCompositeError
    = MismatchingLengthsError
    | NullPlaceholdersError
    | DeconstructionError
    deriving (Int -> SqlBinOpCompositeError -> ShowS
[SqlBinOpCompositeError] -> ShowS
SqlBinOpCompositeError -> String
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [SqlBinOpCompositeError] -> ShowS
$cshowList :: [SqlBinOpCompositeError] -> ShowS
show :: SqlBinOpCompositeError -> String
$cshow :: SqlBinOpCompositeError -> String
showsPrec :: Int -> SqlBinOpCompositeError -> ShowS
$cshowsPrec :: Int -> SqlBinOpCompositeError -> ShowS
Show)

-- | SQL backend for @esqueleto@ using 'SqlPersistT'.
newtype SqlQuery a = Q { forall a.
SqlQuery a -> WriterT SideData (StateT IdentState Identity) a
unQ :: W.WriterT SideData (S.State IdentState) a }
    deriving newtype (forall a b. a -> SqlQuery b -> SqlQuery a
forall a b. (a -> b) -> SqlQuery a -> SqlQuery b
forall (f :: * -> *).
(forall a b. (a -> b) -> f a -> f b)
-> (forall a b. a -> f b -> f a) -> Functor f
<$ :: forall a b. a -> SqlQuery b -> SqlQuery a
$c<$ :: forall a b. a -> SqlQuery b -> SqlQuery a
fmap :: forall a b. (a -> b) -> SqlQuery a -> SqlQuery b
$cfmap :: forall a b. (a -> b) -> SqlQuery a -> SqlQuery b
Functor, Functor SqlQuery
forall a. a -> SqlQuery a
forall a b. SqlQuery a -> SqlQuery b -> SqlQuery a
forall a b. SqlQuery a -> SqlQuery b -> SqlQuery b
forall a b. SqlQuery (a -> b) -> SqlQuery a -> SqlQuery b
forall a b c.
(a -> b -> c) -> SqlQuery a -> SqlQuery b -> SqlQuery c
forall (f :: * -> *).
Functor f
-> (forall a. a -> f a)
-> (forall a b. f (a -> b) -> f a -> f b)
-> (forall a b c. (a -> b -> c) -> f a -> f b -> f c)
-> (forall a b. f a -> f b -> f b)
-> (forall a b. f a -> f b -> f a)
-> Applicative f
<* :: forall a b. SqlQuery a -> SqlQuery b -> SqlQuery a
$c<* :: forall a b. SqlQuery a -> SqlQuery b -> SqlQuery a
*> :: forall a b. SqlQuery a -> SqlQuery b -> SqlQuery b
$c*> :: forall a b. SqlQuery a -> SqlQuery b -> SqlQuery b
liftA2 :: forall a b c.
(a -> b -> c) -> SqlQuery a -> SqlQuery b -> SqlQuery c
$cliftA2 :: forall a b c.
(a -> b -> c) -> SqlQuery a -> SqlQuery b -> SqlQuery c
<*> :: forall a b. SqlQuery (a -> b) -> SqlQuery a -> SqlQuery b
$c<*> :: forall a b. SqlQuery (a -> b) -> SqlQuery a -> SqlQuery b
pure :: forall a. a -> SqlQuery a
$cpure :: forall a. a -> SqlQuery a
Applicative, Applicative SqlQuery
forall a. a -> SqlQuery a
forall a b. SqlQuery a -> SqlQuery b -> SqlQuery b
forall a b. SqlQuery a -> (a -> SqlQuery b) -> SqlQuery b
forall (m :: * -> *).
Applicative m
-> (forall a b. m a -> (a -> m b) -> m b)
-> (forall a b. m a -> m b -> m b)
-> (forall a. a -> m a)
-> Monad m
return :: forall a. a -> SqlQuery a
$creturn :: forall a. a -> SqlQuery a
>> :: forall a b. SqlQuery a -> SqlQuery b -> SqlQuery b
$c>> :: forall a b. SqlQuery a -> SqlQuery b -> SqlQuery b
>>= :: forall a b. SqlQuery a -> (a -> SqlQuery b) -> SqlQuery b
$c>>= :: forall a b. SqlQuery a -> (a -> SqlQuery b) -> SqlQuery b
Monad)

-- | Constraint synonym for @persistent@ entities whose backend
-- is 'SqlBackend'.
type SqlEntity ent = (PersistEntity ent, PersistEntityBackend ent ~ SqlBackend)


----------------------------------------------------------------------


-- | Side data written by 'SqlQuery'.
data SideData = SideData
    { SideData -> DistinctClause
sdDistinctClause :: !DistinctClause
    , SideData -> [FromClause]
sdFromClause     :: ![FromClause]
    , SideData -> [SetClause]
sdSetClause      :: ![SetClause]
    , SideData -> WhereClause
sdWhereClause    :: !WhereClause
    , SideData -> GroupByClause
sdGroupByClause  :: !GroupByClause
    , SideData -> WhereClause
sdHavingClause   :: !HavingClause
    , SideData -> [SqlExpr OrderBy]
sdOrderByClause  :: ![OrderByClause]
    , SideData -> LimitClause
sdLimitClause    :: !LimitClause
    , SideData -> LockingClause
sdLockingClause  :: !LockingClause
    , SideData -> [CommonTableExpressionClause]
sdCteClause      :: ![CommonTableExpressionClause]
    }

instance Semigroup SideData where
    SideData DistinctClause
d [FromClause]
f [SetClause]
s WhereClause
w GroupByClause
g WhereClause
h [SqlExpr OrderBy]
o LimitClause
l LockingClause
k [CommonTableExpressionClause]
c <> :: SideData -> SideData -> SideData
<> SideData DistinctClause
d' [FromClause]
f' [SetClause]
s' WhereClause
w' GroupByClause
g' WhereClause
h' [SqlExpr OrderBy]
o' LimitClause
l' LockingClause
k' [CommonTableExpressionClause]
c' =
        DistinctClause
-> [FromClause]
-> [SetClause]
-> WhereClause
-> GroupByClause
-> WhereClause
-> [SqlExpr OrderBy]
-> LimitClause
-> LockingClause
-> [CommonTableExpressionClause]
-> SideData
SideData (DistinctClause
d forall a. Semigroup a => a -> a -> a
<> DistinctClause
d') ([FromClause]
f forall a. Semigroup a => a -> a -> a
<> [FromClause]
f') ([SetClause]
s forall a. Semigroup a => a -> a -> a
<> [SetClause]
s') (WhereClause
w forall a. Semigroup a => a -> a -> a
<> WhereClause
w') (GroupByClause
g forall a. Semigroup a => a -> a -> a
<> GroupByClause
g') (WhereClause
h forall a. Semigroup a => a -> a -> a
<> WhereClause
h') ([SqlExpr OrderBy]
o forall a. Semigroup a => a -> a -> a
<> [SqlExpr OrderBy]
o') (LimitClause
l forall a. Semigroup a => a -> a -> a
<> LimitClause
l') (LockingClause
k forall a. Semigroup a => a -> a -> a
<> LockingClause
k') ([CommonTableExpressionClause]
c forall a. Semigroup a => a -> a -> a
<> [CommonTableExpressionClause]
c')

instance Monoid SideData where
    mempty :: SideData
mempty = DistinctClause
-> [FromClause]
-> [SetClause]
-> WhereClause
-> GroupByClause
-> WhereClause
-> [SqlExpr OrderBy]
-> LimitClause
-> LockingClause
-> [CommonTableExpressionClause]
-> SideData
SideData forall a. Monoid a => a
mempty forall a. Monoid a => a
mempty forall a. Monoid a => a
mempty forall a. Monoid a => a
mempty forall a. Monoid a => a
mempty forall a. Monoid a => a
mempty forall a. Monoid a => a
mempty forall a. Monoid a => a
mempty forall a. Monoid a => a
mempty forall a. Monoid a => a
mempty
    mappend :: SideData -> SideData -> SideData
mappend = forall a. Semigroup a => a -> a -> a
(<>)

-- | The @DISTINCT@ "clause".
data DistinctClause
    = DistinctAll
    -- ^ The default, everything.
    | DistinctStandard
    -- ^ Only @DISTINCT@, SQL standard.
    | DistinctOn [SqlExpr DistinctOn]
    -- ^ @DISTINCT ON@, PostgreSQL extension.

instance Semigroup DistinctClause where
    DistinctOn [SqlExpr DistinctOn]
a     <> :: DistinctClause -> DistinctClause -> DistinctClause
<> DistinctOn [SqlExpr DistinctOn]
b = [SqlExpr DistinctOn] -> DistinctClause
DistinctOn ([SqlExpr DistinctOn]
a forall a. Semigroup a => a -> a -> a
<> [SqlExpr DistinctOn]
b)
    DistinctOn [SqlExpr DistinctOn]
a     <> DistinctClause
_            = [SqlExpr DistinctOn] -> DistinctClause
DistinctOn [SqlExpr DistinctOn]
a
    DistinctClause
DistinctStandard <> DistinctClause
_            = DistinctClause
DistinctStandard
    DistinctClause
DistinctAll      <> DistinctClause
b            = DistinctClause
b

instance Monoid DistinctClause where
    mempty :: DistinctClause
mempty = DistinctClause
DistinctAll
    mappend :: DistinctClause -> DistinctClause -> DistinctClause
mappend = forall a. Semigroup a => a -> a -> a
(<>)

-- | A part of a @FROM@ clause.
data FromClause
    = FromStart Ident EntityDef
    | FromJoin FromClause JoinKind FromClause (Maybe (SqlExpr (Value Bool)))
    | OnClause (SqlExpr (Value Bool))
    | FromRaw (NeedParens -> IdentInfo -> (TLB.Builder, [PersistValue]))

data CommonTableExpressionKind
    = RecursiveCommonTableExpression
    | NormalCommonTableExpression
    deriving CommonTableExpressionKind -> CommonTableExpressionKind -> Bool
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: CommonTableExpressionKind -> CommonTableExpressionKind -> Bool
$c/= :: CommonTableExpressionKind -> CommonTableExpressionKind -> Bool
== :: CommonTableExpressionKind -> CommonTableExpressionKind -> Bool
$c== :: CommonTableExpressionKind -> CommonTableExpressionKind -> Bool
Eq

data CommonTableExpressionClause =
    CommonTableExpressionClause CommonTableExpressionKind Ident (IdentInfo -> (TLB.Builder, [PersistValue]))

data SubQueryType
    = NormalSubQuery
    | LateralSubQuery
    deriving Int -> SubQueryType -> ShowS
[SubQueryType] -> ShowS
SubQueryType -> String
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [SubQueryType] -> ShowS
$cshowList :: [SubQueryType] -> ShowS
show :: SubQueryType -> String
$cshow :: SubQueryType -> String
showsPrec :: Int -> SubQueryType -> ShowS
$cshowsPrec :: Int -> SubQueryType -> ShowS
Show

collectIdents :: FromClause -> Set Ident
collectIdents :: FromClause -> Set Ident
collectIdents FromClause
fc = case FromClause
fc of
    FromStart Ident
i EntityDef
_ -> forall a. a -> Set a
Set.singleton Ident
i
    FromJoin FromClause
lhs JoinKind
_ FromClause
rhs Maybe (SqlExpr (Value Bool))
_ -> FromClause -> Set Ident
collectIdents FromClause
lhs forall a. Semigroup a => a -> a -> a
<> FromClause -> Set Ident
collectIdents FromClause
rhs
    OnClause SqlExpr (Value Bool)
_ -> forall a. Monoid a => a
mempty
    FromRaw NeedParens -> IdentInfo -> (Builder, [PersistValue])
_ -> forall a. Monoid a => a
mempty

instance Show FromClause where
    show :: FromClause -> String
show FromClause
fc = case FromClause
fc of
        FromStart Ident
i EntityDef
_ ->
            String
"(FromStart " forall a. Semigroup a => a -> a -> a
<> forall a. Show a => a -> String
show Ident
i forall a. Semigroup a => a -> a -> a
<> String
")"
        FromJoin FromClause
lhs JoinKind
jk FromClause
rhs Maybe (SqlExpr (Value Bool))
mexpr ->
            forall a. Monoid a => [a] -> a
mconcat
            [ String
"(FromJoin "
            , forall a. Show a => a -> String
show FromClause
lhs
            , String
" "
            , forall a. Show a => a -> String
show JoinKind
jk
            , String
" "
            , case Maybe (SqlExpr (Value Bool))
mexpr of
                Maybe (SqlExpr (Value Bool))
Nothing -> String
"(no on clause)"
                Just SqlExpr (Value Bool)
expr -> String
"(" forall a. Semigroup a => a -> a -> a
<> SqlExpr (Value Bool) -> String
render' SqlExpr (Value Bool)
expr forall a. Semigroup a => a -> a -> a
<> String
")"
            , String
" "
            , forall a. Show a => a -> String
show FromClause
rhs
            , String
")"
            ]
        OnClause SqlExpr (Value Bool)
expr ->
            String
"(OnClause " forall a. Semigroup a => a -> a -> a
<> SqlExpr (Value Bool) -> String
render' SqlExpr (Value Bool)
expr forall a. Semigroup a => a -> a -> a
<> String
")"
        FromRaw NeedParens -> IdentInfo -> (Builder, [PersistValue])
_ ->
            String
"(FromRaw _)"

      where
        -- We just want to use this to render expressions for a `Show` instance
        -- so we leave most of the fields undefined. But we explicitly
        -- initialize them to `undefined` so that GHC doesn't complain.
        dummy :: SqlBackend
dummy = MkSqlBackendArgs -> SqlBackend
mkSqlBackend MkSqlBackendArgs
            { connEscapeRawName :: Text -> Text
connEscapeRawName = forall a. a -> a
id
            , connPrepare :: Text -> IO Statement
connPrepare = forall a. HasCallStack => a
undefined
            , connInsertSql :: EntityDef -> [PersistValue] -> InsertSqlResult
connInsertSql = forall a. HasCallStack => a
undefined
            , connStmtMap :: IORef (Map Text Statement)
connStmtMap = forall a. HasCallStack => a
undefined
            , connClose :: IO ()
connClose = forall a. HasCallStack => a
undefined
            , connMigrateSql :: [EntityDef]
-> (Text -> IO Statement)
-> EntityDef
-> IO (Either [Text] [(Bool, Text)])
connMigrateSql = forall a. HasCallStack => a
undefined
            , connBegin :: (Text -> IO Statement) -> Maybe IsolationLevel -> IO ()
connBegin = forall a. HasCallStack => a
undefined
            , connCommit :: (Text -> IO Statement) -> IO ()
connCommit = forall a. HasCallStack => a
undefined
            , connRollback :: (Text -> IO Statement) -> IO ()
connRollback = forall a. HasCallStack => a
undefined
            , connEscapeFieldName :: FieldNameDB -> Text
connEscapeFieldName  = forall a. HasCallStack => a
undefined
            , connEscapeTableName :: EntityDef -> Text
connEscapeTableName = forall a. HasCallStack => a
undefined
            , connNoLimit :: Text
connNoLimit = forall a. HasCallStack => a
undefined
            , connRDBMS :: Text
connRDBMS = forall a. HasCallStack => a
undefined
            , connLimitOffset :: (Int, Int) -> Text -> Text
connLimitOffset = forall a. HasCallStack => a
undefined
            , connLogFunc :: LogFunc
connLogFunc = forall a. HasCallStack => a
undefined
            }
        render' :: SqlExpr (Value Bool) -> String
render' = Text -> String
T.unpack forall b c a. (b -> c) -> (a -> b) -> a -> c
. SqlBackend -> SqlExpr (Value Bool) -> Text
renderExpr SqlBackend
dummy

-- | A part of a @SET@ clause.
newtype SetClause = SetClause (SqlExpr Update)

-- | Collect 'OnClause's on 'FromJoin's.  Returns the first
-- unmatched 'OnClause's data on error.  Returns a list without
-- 'OnClauses' on success.
collectOnClauses
    :: SqlBackend
    -> [FromClause]
    -> Either (SqlExpr (Value Bool)) [FromClause]
collectOnClauses :: SqlBackend
-> [FromClause] -> Either (SqlExpr (Value Bool)) [FromClause]
collectOnClauses SqlBackend
sqlBackend = Set Ident
-> [FromClause]
-> [FromClause]
-> Either (SqlExpr (Value Bool)) [FromClause]
go forall a. Set a
Set.empty []
  where
    go :: Set Ident
-> [FromClause]
-> [FromClause]
-> Either (SqlExpr (Value Bool)) [FromClause]
go Set Ident
is []  (f :: FromClause
f@(FromStart Ident
i EntityDef
_) : [FromClause]
fs) =
        forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (FromClause
fforall a. a -> [a] -> [a]
:) (Set Ident
-> [FromClause]
-> [FromClause]
-> Either (SqlExpr (Value Bool)) [FromClause]
go (forall a. Ord a => a -> Set a -> Set a
Set.insert Ident
i Set Ident
is) [] [FromClause]
fs) -- fast path
    go Set Ident
idents [FromClause]
acc (OnClause SqlExpr (Value Bool)
expr : [FromClause]
fs) = do
        (Set Ident
idents', [FromClause]
a) <- Set Ident
-> [FromClause]
-> SqlExpr (Value Bool)
-> Either (SqlExpr (Value Bool)) (Set Ident, [FromClause])
findMatching Set Ident
idents [FromClause]
acc SqlExpr (Value Bool)
expr
        Set Ident
-> [FromClause]
-> [FromClause]
-> Either (SqlExpr (Value Bool)) [FromClause]
go Set Ident
idents' [FromClause]
a [FromClause]
fs
    go Set Ident
idents [FromClause]
acc (FromClause
f:[FromClause]
fs) =
        Set Ident
-> [FromClause]
-> [FromClause]
-> Either (SqlExpr (Value Bool)) [FromClause]
go Set Ident
idents (FromClause
fforall a. a -> [a] -> [a]
:[FromClause]
acc) [FromClause]
fs
    go Set Ident
_ [FromClause]
acc [] =
        forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$ forall a. [a] -> [a]
reverse [FromClause]
acc

    findMatching
        :: Set Ident
        -> [FromClause]
        -> SqlExpr (Value Bool)
        -> Either (SqlExpr (Value Bool)) (Set Ident, [FromClause])
    findMatching :: Set Ident
-> [FromClause]
-> SqlExpr (Value Bool)
-> Either (SqlExpr (Value Bool)) (Set Ident, [FromClause])
findMatching Set Ident
idents [FromClause]
fromClauses SqlExpr (Value Bool)
expr =
        case [FromClause]
fromClauses of
            FromClause
f : [FromClause]
acc ->
              let idents' :: Set Ident
idents' =
                      Set Ident
idents
                      forall a. Semigroup a => a -> a -> a
<> forall a. Ord a => [a] -> Set a
Set.fromList
                          (forall a. [Maybe a] -> [a]
Maybe.catMaybes [FromClause -> Maybe Ident
findLeftmostIdent FromClause
f, FromClause -> Maybe Ident
findRightmostIdent FromClause
f])
              in
                  case Set Ident
-> SqlExpr (Value Bool)
-> FromClause
-> Maybe (Set Ident, FromClause)
tryMatch Set Ident
idents' SqlExpr (Value Bool)
expr FromClause
f of
                      Just (Set Ident
idents'', FromClause
f') ->
                          forall (m :: * -> *) a. Monad m => a -> m a
return (Set Ident
idents'', FromClause
f' forall a. a -> [a] -> [a]
: [FromClause]
acc)
                      Maybe (Set Ident, FromClause)
Nothing ->
                          forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (FromClause
fforall a. a -> [a] -> [a]
:) forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Set Ident
-> [FromClause]
-> SqlExpr (Value Bool)
-> Either (SqlExpr (Value Bool)) (Set Ident, [FromClause])
findMatching Set Ident
idents' [FromClause]
acc SqlExpr (Value Bool)
expr
            [] ->
                forall a b. a -> Either a b
Left SqlExpr (Value Bool)
expr

    findRightmostIdent :: FromClause -> Maybe Ident
findRightmostIdent (FromStart Ident
i EntityDef
_) = forall a. a -> Maybe a
Just Ident
i
    findRightmostIdent (FromJoin FromClause
_ JoinKind
_ FromClause
r Maybe (SqlExpr (Value Bool))
_) = FromClause -> Maybe Ident
findRightmostIdent FromClause
r
    findRightmostIdent (OnClause {}) = forall a. Maybe a
Nothing
    findRightmostIdent (FromRaw NeedParens -> IdentInfo -> (Builder, [PersistValue])
_) = forall a. Maybe a
Nothing

    findLeftmostIdent :: FromClause -> Maybe Ident
findLeftmostIdent (FromStart Ident
i EntityDef
_) = forall a. a -> Maybe a
Just Ident
i
    findLeftmostIdent (FromJoin FromClause
l JoinKind
_ FromClause
_ Maybe (SqlExpr (Value Bool))
_) = FromClause -> Maybe Ident
findLeftmostIdent FromClause
l
    findLeftmostIdent (OnClause {}) = forall a. Maybe a
Nothing
    findLeftmostIdent (FromRaw NeedParens -> IdentInfo -> (Builder, [PersistValue])
_) = forall a. Maybe a
Nothing

    tryMatch
        :: Set Ident
        -> SqlExpr (Value Bool)
        -> FromClause
        -> Maybe (Set Ident, FromClause)
    tryMatch :: Set Ident
-> SqlExpr (Value Bool)
-> FromClause
-> Maybe (Set Ident, FromClause)
tryMatch Set Ident
idents SqlExpr (Value Bool)
expr FromClause
fromClause =
      case FromClause
fromClause of
        FromJoin FromClause
l JoinKind
k FromClause
r Maybe (SqlExpr (Value Bool))
onClause ->
          Maybe (Set Ident, FromClause)
matchTable forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> Maybe (Set Ident, FromClause)
matchR forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> Maybe (Set Ident, FromClause)
matchC forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> Maybe (Set Ident, FromClause)
matchL forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> Maybe (Set Ident, FromClause)
matchPartial -- right to left
            where
              matchR :: Maybe (Set Ident, FromClause)
matchR = forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (\FromClause
r' -> FromClause
-> JoinKind
-> FromClause
-> Maybe (SqlExpr (Value Bool))
-> FromClause
FromJoin FromClause
l JoinKind
k FromClause
r' Maybe (SqlExpr (Value Bool))
onClause)
                forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Set Ident
-> SqlExpr (Value Bool)
-> FromClause
-> Maybe (Set Ident, FromClause)
tryMatch Set Ident
idents SqlExpr (Value Bool)
expr FromClause
r
              matchL :: Maybe (Set Ident, FromClause)
matchL = forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (\FromClause
l' -> FromClause
-> JoinKind
-> FromClause
-> Maybe (SqlExpr (Value Bool))
-> FromClause
FromJoin FromClause
l' JoinKind
k FromClause
r Maybe (SqlExpr (Value Bool))
onClause)
                forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Set Ident
-> SqlExpr (Value Bool)
-> FromClause
-> Maybe (Set Ident, FromClause)
tryMatch Set Ident
idents SqlExpr (Value Bool)
expr FromClause
l

              matchPartial :: Maybe (Set Ident, FromClause)
matchPartial = do
                --Debug.traceM $ "matchPartial"
                --Debug.traceM $ "matchPartial: identsInOnClause: " <> show identsInOnClause
                Ident
i1 <- FromClause -> Maybe Ident
findLeftmostIdent FromClause
l
                Ident
i2 <- FromClause -> Maybe Ident
findLeftmostIdent FromClause
r
                let leftIdents :: Set Ident
leftIdents = FromClause -> Set Ident
collectIdents FromClause
l
                -- Debug.traceM $ "matchPartial: i1: " <> show i1
                -- Debug.traceM $ "matchPartial: i2: " <> show i2
                -- Debug.traceM $ "matchPartial: idents: " <> show idents
                forall (f :: * -> *). Alternative f => Bool -> f ()
guard forall a b. (a -> b) -> a -> b
$
                  forall a. Ord a => Set a -> Set a -> Bool
Set.isSubsetOf
                    Set Ident
identsInOnClause
                    (forall a. Ord a => [a] -> Set a
Set.fromList [Ident
i1, Ident
i2] forall a. Semigroup a => a -> a -> a
<> Set Ident
leftIdents)
                forall (f :: * -> *). Alternative f => Bool -> f ()
guard forall a b. (a -> b) -> a -> b
$ JoinKind
k forall a. Eq a => a -> a -> Bool
/= JoinKind
CrossJoinKind
                forall (f :: * -> *). Alternative f => Bool -> f ()
guard forall a b. (a -> b) -> a -> b
$ forall a. Maybe a -> Bool
Maybe.isNothing Maybe (SqlExpr (Value Bool))
onClause
                forall (f :: * -> *) a. Applicative f => a -> f a
pure (Set Ident
idents, FromClause
-> JoinKind
-> FromClause
-> Maybe (SqlExpr (Value Bool))
-> FromClause
FromJoin FromClause
l JoinKind
k FromClause
r (forall a. a -> Maybe a
Just SqlExpr (Value Bool)
expr))

              matchC :: Maybe (Set Ident, FromClause)
matchC =
                case Maybe (SqlExpr (Value Bool))
onClause of
                  Maybe (SqlExpr (Value Bool))
Nothing
                    | Text
"?" Text -> Text -> Bool
`T.isInfixOf` Text
renderedExpr ->
                        forall (m :: * -> *) a. Monad m => a -> m a
return (Set Ident
idents, FromClause
-> JoinKind
-> FromClause
-> Maybe (SqlExpr (Value Bool))
-> FromClause
FromJoin FromClause
l JoinKind
k FromClause
r (forall a. a -> Maybe a
Just SqlExpr (Value Bool)
expr))
                    | forall a. Set a -> Bool
Set.null Set Ident
identsInOnClause ->
                        forall (m :: * -> *) a. Monad m => a -> m a
return (Set Ident
idents, FromClause
-> JoinKind
-> FromClause
-> Maybe (SqlExpr (Value Bool))
-> FromClause
FromJoin FromClause
l JoinKind
k FromClause
r (forall a. a -> Maybe a
Just SqlExpr (Value Bool)
expr))
                    | Bool
otherwise ->
                        forall a. Maybe a
Nothing
                  Just SqlExpr (Value Bool)
_ ->
                    forall a. Maybe a
Nothing
              matchTable :: Maybe (Set Ident, FromClause)
matchTable = do
                Ident
i1 <- FromClause -> Maybe Ident
findLeftmostIdent FromClause
r
                Ident
i2 <- FromClause -> Maybe Ident
findRightmostIdent FromClause
l
                forall (f :: * -> *). Alternative f => Bool -> f ()
guard forall a b. (a -> b) -> a -> b
$ forall a. Ord a => [a] -> Set a
Set.fromList [Ident
i1, Ident
i2] forall a. Ord a => Set a -> Set a -> Bool
`Set.isSubsetOf` Set Ident
identsInOnClause
                forall (f :: * -> *). Alternative f => Bool -> f ()
guard forall a b. (a -> b) -> a -> b
$ JoinKind
k forall a. Eq a => a -> a -> Bool
/= JoinKind
CrossJoinKind
                forall (f :: * -> *). Alternative f => Bool -> f ()
guard forall a b. (a -> b) -> a -> b
$ forall a. Maybe a -> Bool
Maybe.isNothing Maybe (SqlExpr (Value Bool))
onClause
                forall (f :: * -> *) a. Applicative f => a -> f a
pure (forall a. Ord a => [a] -> Set a
Set.fromList [Ident
i1, Ident
i2] forall a. Semigroup a => a -> a -> a
<> Set Ident
idents, FromClause
-> JoinKind
-> FromClause
-> Maybe (SqlExpr (Value Bool))
-> FromClause
FromJoin FromClause
l JoinKind
k FromClause
r (forall a. a -> Maybe a
Just SqlExpr (Value Bool)
expr))

        FromClause
_ ->
          forall a. Maybe a
Nothing
      where
        identsInOnClause :: Set Ident
identsInOnClause =
          Set Ident
onExprToTableIdentifiers

        renderedExpr :: Text
renderedExpr =
          SqlBackend -> SqlExpr (Value Bool) -> Text
renderExpr SqlBackend
sqlBackend SqlExpr (Value Bool)
expr

        onExprToTableIdentifiers :: Set Ident
onExprToTableIdentifiers =
          forall b a. Ord b => (a -> b) -> Set a -> Set b
Set.map (Text -> Ident
I forall b c a. (b -> c) -> (a -> b) -> a -> c
. TableAccess -> Text
tableAccessTable)
          forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either forall a. HasCallStack => String -> a
error forall a. a -> a
id
          forall b c a. (b -> c) -> (a -> b) -> a -> c
. SqlBackend -> Text -> Either String (Set TableAccess)
parseOnExpr SqlBackend
sqlBackend
          forall a b. (a -> b) -> a -> b
$ Text
renderedExpr

-- | A complete @WHERE@ clause.
data WhereClause = Where (SqlExpr (Value Bool))
                 | NoWhere

instance Semigroup WhereClause where
  WhereClause
NoWhere  <> :: WhereClause -> WhereClause -> WhereClause
<> WhereClause
w        = WhereClause
w
  WhereClause
w        <> WhereClause
NoWhere  = WhereClause
w
  Where SqlExpr (Value Bool)
e1 <> Where SqlExpr (Value Bool)
e2 = SqlExpr (Value Bool) -> WhereClause
Where (SqlExpr (Value Bool)
e1 SqlExpr (Value Bool)
-> SqlExpr (Value Bool) -> SqlExpr (Value Bool)
&&. SqlExpr (Value Bool)
e2)

instance Monoid WhereClause where
  mempty :: WhereClause
mempty = WhereClause
NoWhere
  mappend :: WhereClause -> WhereClause -> WhereClause
mappend = forall a. Semigroup a => a -> a -> a
(<>)

-- | A @GROUP BY@ clause.
newtype GroupByClause = GroupBy [SomeValue]

instance Semigroup GroupByClause where
  GroupBy [SomeValue]
fs <> :: GroupByClause -> GroupByClause -> GroupByClause
<> GroupBy [SomeValue]
fs' = [SomeValue] -> GroupByClause
GroupBy ([SomeValue]
fs forall a. Semigroup a => a -> a -> a
<> [SomeValue]
fs')

instance Monoid GroupByClause where
  mempty :: GroupByClause
mempty = [SomeValue] -> GroupByClause
GroupBy []
  mappend :: GroupByClause -> GroupByClause -> GroupByClause
mappend = forall a. Semigroup a => a -> a -> a
(<>)

-- | A @HAVING@ cause.
type HavingClause = WhereClause

-- | A @ORDER BY@ clause.
type OrderByClause = SqlExpr OrderBy

-- | A @LIMIT@ clause.
data LimitClause = Limit (Maybe Int64) (Maybe Int64)
  deriving LimitClause -> LimitClause -> Bool
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: LimitClause -> LimitClause -> Bool
$c/= :: LimitClause -> LimitClause -> Bool
== :: LimitClause -> LimitClause -> Bool
$c== :: LimitClause -> LimitClause -> Bool
Eq

instance Semigroup LimitClause where
  Limit Maybe Int64
l1 Maybe Int64
o1 <> :: LimitClause -> LimitClause -> LimitClause
<> Limit Maybe Int64
l2 Maybe Int64
o2 =
    Maybe Int64 -> Maybe Int64 -> LimitClause
Limit (Maybe Int64
l2 forall (m :: * -> *) a. MonadPlus m => m a -> m a -> m a
`mplus` Maybe Int64
l1) (Maybe Int64
o2 forall (m :: * -> *) a. MonadPlus m => m a -> m a -> m a
`mplus` Maybe Int64
o1)
    -- More than one 'limit' or 'offset' is issued, we want to
    -- keep the latest one.  That's why we use mplus with
    -- "reversed" arguments.

instance Monoid LimitClause where
  mempty :: LimitClause
mempty = Maybe Int64 -> Maybe Int64 -> LimitClause
Limit forall (m :: * -> *) a. MonadPlus m => m a
mzero forall (m :: * -> *) a. MonadPlus m => m a
mzero

-- | A locking clause.
data LockingClause =
    LegacyLockingClause LockingKind
    -- ^ Locking clause not specific to any database implementation
    | PostgresLockingClauses [PostgresLockingKind]
    -- ^ Locking clause specific to postgres
    | NoLockingClause

instance Semigroup LockingClause where
  -- Postgres allows us to have multiple locking clauses
    <> :: LockingClause -> LockingClause -> LockingClause
(<>) (PostgresLockingClauses [PostgresLockingKind]
pleft) (PostgresLockingClauses [PostgresLockingKind]
pright) = [PostgresLockingKind] -> LockingClause
PostgresLockingClauses ([PostgresLockingKind]
pleft forall a. Semigroup a => a -> a -> a
<> [PostgresLockingKind]
pright)
    (<>) LockingClause
mleft LockingClause
NoLockingClause = LockingClause
mleft
    (<>) LockingClause
_ LockingClause
mright = LockingClause
mright
--
instance Monoid LockingClause where
    mempty :: LockingClause
mempty = LockingClause
NoLockingClause
    mappend :: LockingClause -> LockingClause -> LockingClause
mappend = forall a. Semigroup a => a -> a -> a
(<>)

----------------------------------------------------------------------

-- | Identifier used for table names.
newtype Ident = I T.Text
  deriving (Ident -> Ident -> Bool
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: Ident -> Ident -> Bool
$c/= :: Ident -> Ident -> Bool
== :: Ident -> Ident -> Bool
$c== :: Ident -> Ident -> Bool
Eq, Eq Ident
Ident -> Ident -> Bool
Ident -> Ident -> Ordering
Ident -> Ident -> Ident
forall a.
Eq a
-> (a -> a -> Ordering)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> a)
-> (a -> a -> a)
-> Ord a
min :: Ident -> Ident -> Ident
$cmin :: Ident -> Ident -> Ident
max :: Ident -> Ident -> Ident
$cmax :: Ident -> Ident -> Ident
>= :: Ident -> Ident -> Bool
$c>= :: Ident -> Ident -> Bool
> :: Ident -> Ident -> Bool
$c> :: Ident -> Ident -> Bool
<= :: Ident -> Ident -> Bool
$c<= :: Ident -> Ident -> Bool
< :: Ident -> Ident -> Bool
$c< :: Ident -> Ident -> Bool
compare :: Ident -> Ident -> Ordering
$ccompare :: Ident -> Ident -> Ordering
Ord, Int -> Ident -> ShowS
[Ident] -> ShowS
Ident -> String
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [Ident] -> ShowS
$cshowList :: [Ident] -> ShowS
show :: Ident -> String
$cshow :: Ident -> String
showsPrec :: Int -> Ident -> ShowS
$cshowsPrec :: Int -> Ident -> ShowS
Show)

-- | List of identifiers already in use and supply of temporary
-- identifiers.
newtype IdentState = IdentState { IdentState -> HashSet Text
inUse :: HS.HashSet T.Text }

initialIdentState :: IdentState
initialIdentState :: IdentState
initialIdentState = HashSet Text -> IdentState
IdentState forall a. Monoid a => a
mempty

-- | Create a fresh 'Ident'.  If possible, use the given
-- 'DBName'.
newIdentFor :: DBName -> SqlQuery Ident
newIdentFor :: DBName -> SqlQuery Ident
newIdentFor (DBName Text
original) = forall a.
WriterT SideData (StateT IdentState Identity) a -> SqlQuery a
Q forall a b. (a -> b) -> a -> b
$ forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall a b. (a -> b) -> a -> b
$ Maybe Int -> StateT IdentState Identity Ident
findFree forall a. Maybe a
Nothing
  where
    findFree :: Maybe Int -> StateT IdentState Identity Ident
findFree Maybe Int
msuffix = do
      let
        withSuffix :: Text
withSuffix =
          forall b a. b -> (a -> b) -> Maybe a -> b
maybe forall a. a -> a
id (\Int
suffix -> (forall a. Semigroup a => a -> a -> a
<> String -> Text
T.pack (forall a. Show a => a -> String
show Int
suffix))) Maybe Int
msuffix Text
original
      Bool
isInUse <- forall (m :: * -> *) s a. Monad m => (s -> a) -> StateT s m a
S.gets (forall a. (Eq a, Hashable a) => a -> HashSet a -> Bool
HS.member Text
withSuffix forall b c a. (b -> c) -> (a -> b) -> a -> c
. IdentState -> HashSet Text
inUse)
      if Bool
isInUse
        then Maybe Int -> StateT IdentState Identity Ident
findFree (forall a. Enum a => a -> a
succ forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (Maybe Int
msuffix forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> forall a. a -> Maybe a
Just (Int
1 :: Int)))
        else do
          forall (m :: * -> *) s. Monad m => (s -> s) -> StateT s m ()
S.modify (\IdentState
s -> IdentState
s { inUse :: HashSet Text
inUse = forall a. (Eq a, Hashable a) => a -> HashSet a -> HashSet a
HS.insert Text
withSuffix (IdentState -> HashSet Text
inUse IdentState
s) })
          forall (f :: * -> *) a. Applicative f => a -> f a
pure (Text -> Ident
I Text
withSuffix)

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

-- | Use an identifier.
useIdent :: IdentInfo -> Ident -> TLB.Builder
useIdent :: IdentInfo -> Ident -> Builder
useIdent IdentInfo
info (I Text
ident) = IdentInfo -> DBName -> Builder
fromDBName IdentInfo
info forall a b. (a -> b) -> a -> b
$ Text -> DBName
DBName Text
ident

data SqlExprMeta = SqlExprMeta
    { -- A composite key.
      --
      -- Persistent uses the same 'PersistList' constructor for both
      -- fields which are (homogeneous) lists of values and the
      -- (probably heterogeneous) values of a composite primary key.
      --
      -- We need to treat composite keys as fields.  For example, we
      -- have to support using ==., otherwise you wouldn't be able to
      -- join.  OTOH, lists of values should be treated exactly the
      -- same as any other scalar value.
      --
      -- In particular, this is valid for persistent via rawSql for
      -- an F field that is a list:
      --
      --   A.F in ?    -- [PersistList [foo, bar]]
      --
      -- However, this is not for a composite key entity:
      --
      --   A.ID = ?    -- [PersistList [foo, bar]]
      --
      -- The ID field doesn't exist on the DB for a composite key
      -- table, it exists only on the Haskell side.  Those variations
      -- also don't work:
      --
      --   (A.KeyA, A.KeyB) = ?    -- [PersistList [foo, bar]]
      --   [A.KeyA, A.KeyB] = ?    -- [PersistList [foo, bar]]
      --
      -- We have to generate:
      --
      --   A.KeyA = ? AND A.KeyB = ?      -- [foo, bar]
      --
      -- Note that the PersistList had to be deconstructed into its
      -- components.
      --
      -- In order to disambiguate behaviors, this constructor is used
      -- /only/ to represent a composite field access.  It does not
      -- represent a 'PersistList', not even if the 'PersistList' is
      -- used in the context of a composite key.  That's because it's
      -- impossible, e.g., for 'val' to disambiguate between these
      -- uses.
      SqlExprMeta -> Maybe (IdentInfo -> [Builder])
sqlExprMetaCompositeFields :: Maybe (IdentInfo -> [TLB.Builder])
    , SqlExprMeta -> Maybe Ident
sqlExprMetaAlias :: Maybe Ident -- Alias ident if this is an aliased value/entity
    , SqlExprMeta -> Bool
sqlExprMetaIsReference :: Bool -- Is this SqlExpr a reference to the selected value/entity (supports subqueries)
    }

-- | Empty 'SqlExprMeta' if you are constructing an 'ERaw' probably use this
-- for your meta
noMeta :: SqlExprMeta
noMeta :: SqlExprMeta
noMeta = SqlExprMeta
    { sqlExprMetaCompositeFields :: Maybe (IdentInfo -> [Builder])
sqlExprMetaCompositeFields = forall a. Maybe a
Nothing
    , sqlExprMetaAlias :: Maybe Ident
sqlExprMetaAlias = forall a. Maybe a
Nothing
    , sqlExprMetaIsReference :: Bool
sqlExprMetaIsReference = Bool
False
    }

-- | Does this meta contain values for composite fields.
-- This field is field out for composite key values
hasCompositeKeyMeta :: SqlExprMeta -> Bool
hasCompositeKeyMeta :: SqlExprMeta -> Bool
hasCompositeKeyMeta = forall a. Maybe a -> Bool
Maybe.isJust forall b c a. (b -> c) -> (a -> b) -> a -> c
. SqlExprMeta -> Maybe (IdentInfo -> [Builder])
sqlExprMetaCompositeFields

entityAsValue
    :: SqlExpr (Entity val)
    -> SqlExpr (Value (Entity val))
entityAsValue :: forall val. SqlExpr (Entity val) -> SqlExpr (Value (Entity val))
entityAsValue = coerce :: forall a b. Coercible a b => a -> b
coerce

entityAsValueMaybe
    :: SqlExpr (Maybe (Entity val))
    -> SqlExpr (Value (Maybe (Entity val)))
entityAsValueMaybe :: forall val.
SqlExpr (Maybe (Entity val))
-> SqlExpr (Value (Maybe (Entity val)))
entityAsValueMaybe = coerce :: forall a b. Coercible a b => a -> b
coerce

-- | An expression on the SQL backend.
--
-- Raw expression: Contains a 'SqlExprMeta' 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 ('TLB.Builder') and a list of values to be
-- interpolated by the SQL backend.
data SqlExpr a = ERaw SqlExprMeta (NeedParens -> IdentInfo -> (TLB.Builder, [PersistValue]))

-- | Folks often want the ability to promote a Haskell function into the
-- 'SqlExpr' expression language - and naturally reach for 'fmap'.
-- Unfortunately, this is impossible. We cannot send *functions* to the
-- database, which is what we would need to do in order for this to make sense.
-- Let's consider the type of 'fmap' for 'SqlExpr':
--
-- @
-- fmap :: (a -> b) -> 'SqlExpr' a -> 'SqlExpr' b
-- @
--
-- This type signature is making a pretty strong claim: "Give me a Haskell
-- function from @a -> b@. I will then transform a SQL expression representing
-- a Haskell value of type @a@ and turn it into a SQL expression representing
-- a Haskell value of type @b@."
--
-- Let's suppose we *could* do this - @fmap (+1)@ would have to somehow inspect
-- the function expression means "add one", and then translate that to the
-- appropriate SQL.
--
-- This is why @esqueleto@ defines a bunch of operators: @x '+.' ('val' 1)@ can
-- be used instead of @'fmap' (+1) x@.
--
-- If you do have a SQL function, then you can provide a safe type and introduce
-- it with 'unsafeSqlFunction' or 'unsafeSqlBinOp'.
--
-- @since 3.5.8.2
instance TypeError SqlExprFunctorMessage => Functor SqlExpr where
    fmap :: forall a b. (a -> b) -> SqlExpr a -> SqlExpr b
fmap = forall a. HasCallStack => String -> a
error String
"impossible"

-- | The type error message given when you try to do 'fmap' on a 'SqlExpr'. This
-- is intended to guide folks towards the docs, which should guide them towards
-- alternative implementations.
--
-- @since 3.5.8.2
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."

-- |  This instance allows you to use @record.field@ notation with GHC 9.2's
-- @OverloadedRecordDot@ extension.
--
-- Example:
--
-- @
-- -- persistent model:
-- BlogPost
--     authorId     PersonId
--     title        Text
--
-- -- query:
-- 'select' $ do
--     bp <- 'from' $ 'table' \@BlogPost
--     pure $ bp.title
-- @
--
-- This is exactly equivalent to the following:
--
-- @
-- blogPost :: SqlExpr (Entity BlogPost)
--
-- blogPost ^. BlogPostTitle
-- blogPost ^. #title
-- blogPost.title
-- @
-- There's another instance defined on @'SqlExpr' ('Entity' ('Maybe' rec))@,
-- which allows you to project from a @LEFT JOIN@ed entity.
--
-- @since 3.5.4.0
instance
    (PersistEntity rec, PersistField typ, SymbolToField sym rec typ)
  =>
    HasField sym (SqlExpr (Entity rec)) (SqlExpr (Value typ))
  where
    getField :: SqlExpr (Entity rec) -> SqlExpr (Value typ)
getField SqlExpr (Entity rec)
expr = SqlExpr (Entity rec)
expr forall typ val.
(PersistEntity val, PersistField typ) =>
SqlExpr (Entity val) -> EntityField val typ -> SqlExpr (Value typ)
^. forall (sym :: Symbol) rec typ.
SymbolToField sym rec typ =>
EntityField rec typ
symbolToField @sym

-- | This instance allows you to use @record.field@ notation with GC 9.2's
-- @OverloadedRecordDot@ extension.
--
-- Example:
--
-- @
-- -- persistent model:
-- Person
--     name         Text
--
-- BlogPost
--     title        Text
--     authorId     PersonId
--
-- -- query:
--
-- 'select' $ do
--     (p :& bp) <- 'from' $
--         'table' @Person
--         `leftJoin` table @BlogPost
--         `on` do
--             \\(p :& bp) ->
--                 just p.id ==. bp.authorId
--     pure (p.name, bp.title)
-- @
--
-- The following forms are all equivalent:
--
-- @
-- blogPost :: SqlExpr (Maybe (Entity BlogPost))
--
-- blogPost ?. BlogPostTitle
-- blogPost ?. #title
-- blogPost.title
-- @
--
-- @since 3.5.4.0
instance
    (PersistEntity rec, PersistField typ, SymbolToField sym rec typ)
  =>
    HasField sym (SqlExpr (Maybe (Entity rec))) (SqlExpr (Value (Maybe typ)))
  where
    getField :: SqlExpr (Maybe (Entity rec)) -> SqlExpr (Value (Maybe typ))
getField SqlExpr (Maybe (Entity rec))
expr = SqlExpr (Maybe (Entity rec))
expr forall val typ.
(PersistEntity val, PersistField typ) =>
SqlExpr (Maybe (Entity val))
-> EntityField val typ -> SqlExpr (Value (Maybe typ))
?. forall (sym :: Symbol) rec typ.
SymbolToField sym rec typ =>
EntityField rec typ
symbolToField @sym

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

-- | Phantom type used to mark a @INSERT INTO@ query.
data InsertFinal

data NeedParens = Parens | Never
    deriving NeedParens -> NeedParens -> Bool
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: NeedParens -> NeedParens -> Bool
$c/= :: NeedParens -> NeedParens -> Bool
== :: NeedParens -> NeedParens -> Bool
$c== :: NeedParens -> NeedParens -> Bool
Eq

parensM :: NeedParens -> TLB.Builder -> TLB.Builder
parensM :: NeedParens -> Builder -> Builder
parensM NeedParens
Never  = forall a. a -> a
id
parensM NeedParens
Parens = Builder -> Builder
parens

data OrderByType = ASC | DESC

instance ToSomeValues (SqlExpr (Value a)) where
  toSomeValues :: SqlExpr (Value a) -> [SomeValue]
toSomeValues SqlExpr (Value a)
a = [forall a. SqlExpr (Value a) -> SomeValue
SomeValue SqlExpr (Value a)
a]

fieldName
    :: (PersistEntity val, PersistField typ)
    => IdentInfo -> EntityField val typ -> TLB.Builder
fieldName :: forall val typ.
(PersistEntity val, PersistField typ) =>
IdentInfo -> EntityField val typ -> Builder
fieldName IdentInfo
info = IdentInfo -> DBName -> Builder
fromDBName IdentInfo
info forall b c a. (b -> c) -> (a -> b) -> a -> c
. coerce :: forall a b. Coercible a b => a -> b
coerce forall b c a. (b -> c) -> (a -> b) -> a -> c
. FieldDef -> FieldNameDB
fieldDB forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall record typ.
PersistEntity record =>
EntityField record typ -> FieldDef
persistFieldDef

-- FIXME: Composite/non-id pKS not supported on set
setAux
    :: (PersistEntity val, PersistField typ)
    => EntityField val typ
    -> (SqlExpr (Entity val) -> SqlExpr (Value typ))
    -> (SqlExpr (Entity val) -> SqlExpr Update)
setAux :: forall val typ.
(PersistEntity val, PersistField typ) =>
EntityField val typ
-> (SqlExpr (Entity val) -> SqlExpr (Value typ))
-> SqlExpr (Entity val)
-> SqlExpr Update
setAux EntityField val typ
field SqlExpr (Entity val) -> SqlExpr (Value typ)
value = \SqlExpr (Entity val)
ent -> forall a.
SqlExprMeta
-> (NeedParens -> IdentInfo -> (Builder, [PersistValue]))
-> SqlExpr a
ERaw SqlExprMeta
noMeta forall a b. (a -> b) -> a -> b
$ \NeedParens
_ IdentInfo
info ->
    let ERaw SqlExprMeta
_ NeedParens -> IdentInfo -> (Builder, [PersistValue])
valueF = SqlExpr (Entity val) -> SqlExpr (Value typ)
value SqlExpr (Entity val)
ent
        (Builder
valueToSet, [PersistValue]
valueVals) = NeedParens -> IdentInfo -> (Builder, [PersistValue])
valueF NeedParens
Parens IdentInfo
info
    in (forall val typ.
(PersistEntity val, PersistField typ) =>
IdentInfo -> EntityField val typ -> Builder
fieldName IdentInfo
info EntityField val typ
field forall a. Semigroup a => a -> a -> a
<> Builder
" = " forall a. Semigroup a => a -> a -> a
<> Builder
valueToSet, [PersistValue]
valueVals)

sub :: PersistField a => Mode -> SqlQuery (SqlExpr (Value a)) -> SqlExpr (Value a)
sub :: forall a.
PersistField a =>
Mode -> SqlQuery (SqlExpr (Value a)) -> SqlExpr (Value a)
sub Mode
mode SqlQuery (SqlExpr (Value a))
query = forall a.
SqlExprMeta
-> (NeedParens -> IdentInfo -> (Builder, [PersistValue]))
-> SqlExpr a
ERaw SqlExprMeta
noMeta forall a b. (a -> b) -> a -> b
$ \NeedParens
_ IdentInfo
info -> forall (a :: * -> * -> *) b c d.
Arrow a =>
a b c -> a (b, d) (c, d)
first Builder -> Builder
parens forall a b. (a -> b) -> a -> b
$ forall a r backend.
(SqlSelect a r, BackendCompatible SqlBackend backend) =>
Mode
-> (backend, IdentState) -> SqlQuery a -> (Builder, [PersistValue])
toRawSql Mode
mode IdentInfo
info SqlQuery (SqlExpr (Value a))
query

fromDBName :: IdentInfo -> DBName -> TLB.Builder
fromDBName :: IdentInfo -> DBName -> Builder
fromDBName (SqlBackend
conn, IdentState
_) = Text -> Builder
TLB.fromText forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a b c. (a -> b -> c) -> b -> a -> c
flip forall backend (m :: * -> *).
(BackendCompatible SqlBackend backend, MonadReader backend m) =>
Text -> m Text
getEscapedRawName SqlBackend
conn forall b c a. (b -> c) -> (a -> b) -> a -> c
. DBName -> Text
unDBName

existsHelper :: SqlQuery () -> SqlExpr (Value Bool)
existsHelper :: SqlQuery () -> SqlExpr (Value Bool)
existsHelper = forall a.
PersistField a =>
Mode -> SqlQuery (SqlExpr (Value a)) -> SqlExpr (Value a)
sub Mode
SELECT forall b c a. (b -> c) -> (a -> b) -> a -> c
. (forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> forall (m :: * -> *) a. Monad m => a -> m a
return SqlExpr (Value Bool)
true)
  where
    true  :: SqlExpr (Value Bool)
    true :: SqlExpr (Value Bool)
true = forall typ. PersistField typ => typ -> SqlExpr (Value typ)
val Bool
True

-- | (Internal) Create a case statement.
--
-- Since: 2.1.1
unsafeSqlCase :: PersistField a => [(SqlExpr (Value Bool), SqlExpr (Value a))] -> SqlExpr (Value a) -> SqlExpr (Value a)
unsafeSqlCase :: forall a.
PersistField a =>
[(SqlExpr (Value Bool), SqlExpr (Value a))]
-> SqlExpr (Value a) -> SqlExpr (Value a)
unsafeSqlCase [(SqlExpr (Value Bool), SqlExpr (Value a))]
when SqlExpr (Value a)
v = forall a.
SqlExprMeta
-> (NeedParens -> IdentInfo -> (Builder, [PersistValue]))
-> SqlExpr a
ERaw SqlExprMeta
noMeta NeedParens -> IdentInfo -> (Builder, [PersistValue])
buildCase
  where
    buildCase :: NeedParens -> IdentInfo -> (TLB.Builder, [PersistValue])
    buildCase :: NeedParens -> IdentInfo -> (Builder, [PersistValue])
buildCase NeedParens
_ IdentInfo
info =
        let (Builder
elseText, [PersistValue]
elseVals) = forall a.
SqlExpr (Value a)
-> NeedParens -> IdentInfo -> (Builder, [PersistValue])
valueToSql SqlExpr (Value a)
v NeedParens
Parens IdentInfo
info
            (Builder
whenText, [PersistValue]
whenVals) = forall a.
[(SqlExpr (Value Bool), SqlExpr (Value a))]
-> NeedParens -> IdentInfo -> (Builder, [PersistValue])
mapWhen [(SqlExpr (Value Bool), SqlExpr (Value a))]
when NeedParens
Parens IdentInfo
info
        in ( Builder
"CASE" forall a. Semigroup a => a -> a -> a
<> Builder
whenText forall a. Semigroup a => a -> a -> a
<> Builder
" ELSE " forall a. Semigroup a => a -> a -> a
<> Builder
elseText forall a. Semigroup a => a -> a -> a
<> Builder
" END", [PersistValue]
whenVals forall a. Semigroup a => a -> a -> a
<> [PersistValue]
elseVals)

    mapWhen :: [(SqlExpr (Value Bool), SqlExpr (Value a))] -> NeedParens -> IdentInfo -> (TLB.Builder, [PersistValue])
    mapWhen :: forall a.
[(SqlExpr (Value Bool), SqlExpr (Value a))]
-> NeedParens -> IdentInfo -> (Builder, [PersistValue])
mapWhen []    NeedParens
_ IdentInfo
_    = forall a e. Exception e => e -> a
throw (UnexpectedCaseError -> EsqueletoError
UnexpectedCaseErr UnexpectedCaseError
UnsafeSqlCaseError)
    mapWhen [(SqlExpr (Value Bool), SqlExpr (Value a))]
when' NeedParens
p IdentInfo
info = forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl (forall a.
NeedParens
-> IdentInfo
-> (Builder, [PersistValue])
-> (SqlExpr (Value Bool), SqlExpr (Value a))
-> (Builder, [PersistValue])
foldHelp NeedParens
p IdentInfo
info) (forall a. Monoid a => a
mempty, forall a. Monoid a => a
mempty) [(SqlExpr (Value Bool), SqlExpr (Value a))]
when'


    foldHelp :: NeedParens -> IdentInfo -> (TLB.Builder, [PersistValue]) -> (SqlExpr (Value Bool), SqlExpr (Value a)) -> (TLB.Builder, [PersistValue])
    foldHelp :: forall a.
NeedParens
-> IdentInfo
-> (Builder, [PersistValue])
-> (SqlExpr (Value Bool), SqlExpr (Value a))
-> (Builder, [PersistValue])
foldHelp NeedParens
p IdentInfo
info (Builder
b0, [PersistValue]
vals0) (SqlExpr (Value Bool)
v1, SqlExpr (Value a)
v2) =
        let (Builder
b1, [PersistValue]
vals1) = forall a.
SqlExpr (Value a)
-> NeedParens -> IdentInfo -> (Builder, [PersistValue])
valueToSql SqlExpr (Value Bool)
v1 NeedParens
p IdentInfo
info
            (Builder
b2, [PersistValue]
vals2) = forall a.
SqlExpr (Value a)
-> NeedParens -> IdentInfo -> (Builder, [PersistValue])
valueToSql SqlExpr (Value a)
v2 NeedParens
p IdentInfo
info
        in ( Builder
b0 forall a. Semigroup a => a -> a -> a
<> Builder
" WHEN " forall a. Semigroup a => a -> a -> a
<> Builder
b1 forall a. Semigroup a => a -> a -> a
<> Builder
" THEN " forall a. Semigroup a => a -> a -> a
<> Builder
b2, [PersistValue]
vals0 forall a. Semigroup a => a -> a -> a
<> [PersistValue]
vals1 forall a. Semigroup a => a -> a -> a
<> [PersistValue]
vals2 )

    valueToSql :: SqlExpr (Value a) -> NeedParens -> IdentInfo -> (TLB.Builder, [PersistValue])
    valueToSql :: forall a.
SqlExpr (Value a)
-> NeedParens -> IdentInfo -> (Builder, [PersistValue])
valueToSql (ERaw SqlExprMeta
_ NeedParens -> IdentInfo -> (Builder, [PersistValue])
f) NeedParens
p = NeedParens -> IdentInfo -> (Builder, [PersistValue])
f NeedParens
p

-- | (Internal) Create a custom binary operator.  You /should/
-- /not/ use this function directly since its type is very
-- general, you should always use it with an explicit type
-- signature.  For example:
--
-- @
-- (==.) :: SqlExpr (Value a) -> SqlExpr (Value a) -> SqlExpr (Value Bool)
-- (==.) = unsafeSqlBinOp " = "
-- @
--
-- In the example above, we constraint the arguments to be of the
-- same type and constraint the result to be a boolean value.
unsafeSqlBinOp :: TLB.Builder -> SqlExpr (Value a) -> SqlExpr (Value b) -> SqlExpr (Value c)
unsafeSqlBinOp :: forall a b c.
Builder
-> SqlExpr (Value a) -> SqlExpr (Value b) -> SqlExpr (Value c)
unsafeSqlBinOp Builder
op (ERaw SqlExprMeta
m1 NeedParens -> IdentInfo -> (Builder, [PersistValue])
f1) (ERaw SqlExprMeta
m2 NeedParens -> IdentInfo -> (Builder, [PersistValue])
f2)
  | Bool -> Bool
not (SqlExprMeta -> Bool
hasCompositeKeyMeta SqlExprMeta
m1 Bool -> Bool -> Bool
|| SqlExprMeta -> Bool
hasCompositeKeyMeta SqlExprMeta
m2) = forall a.
SqlExprMeta
-> (NeedParens -> IdentInfo -> (Builder, [PersistValue]))
-> SqlExpr a
ERaw SqlExprMeta
noMeta NeedParens -> IdentInfo -> (Builder, [PersistValue])
f
  where
    f :: NeedParens -> IdentInfo -> (Builder, [PersistValue])
f NeedParens
p IdentInfo
info =
        let (Builder
b1, [PersistValue]
vals1) = NeedParens -> IdentInfo -> (Builder, [PersistValue])
f1 NeedParens
Parens IdentInfo
info
            (Builder
b2, [PersistValue]
vals2) = NeedParens -> IdentInfo -> (Builder, [PersistValue])
f2 NeedParens
Parens IdentInfo
info
        in
            ( NeedParens -> Builder -> Builder
parensM NeedParens
p (Builder
b1 forall a. Semigroup a => a -> a -> a
<> Builder
op forall a. Semigroup a => a -> a -> a
<> Builder
b2)
            , [PersistValue]
vals1 forall a. Semigroup a => a -> a -> a
<> [PersistValue]
vals2
            )
unsafeSqlBinOp Builder
op SqlExpr (Value a)
a SqlExpr (Value b)
b = forall a b c.
Builder
-> SqlExpr (Value a) -> SqlExpr (Value b) -> SqlExpr (Value c)
unsafeSqlBinOp Builder
op (forall a. SqlExpr (Value a) -> SqlExpr (Value a)
construct SqlExpr (Value a)
a) (forall a. SqlExpr (Value a) -> SqlExpr (Value a)
construct SqlExpr (Value b)
b)
  where
    construct :: SqlExpr (Value a) -> SqlExpr (Value a)
    construct :: forall a. SqlExpr (Value a) -> SqlExpr (Value a)
construct (ERaw SqlExprMeta
m NeedParens -> IdentInfo -> (Builder, [PersistValue])
f) =
        case SqlExprMeta -> Maybe (IdentInfo -> [Builder])
sqlExprMetaCompositeFields SqlExprMeta
m of
            Just IdentInfo -> [Builder]
fields ->
                forall a.
SqlExprMeta
-> (NeedParens -> IdentInfo -> (Builder, [PersistValue]))
-> SqlExpr a
ERaw SqlExprMeta
noMeta forall a b. (a -> b) -> a -> b
$ \NeedParens
_ IdentInfo
info -> (Builder -> Builder
parens forall a b. (a -> b) -> a -> b
$ [Builder] -> Builder
uncommas forall a b. (a -> b) -> a -> b
$ IdentInfo -> [Builder]
fields IdentInfo
info, forall a. Monoid a => a
mempty)
            Maybe (IdentInfo -> [Builder])
Nothing ->
                forall a.
SqlExprMeta
-> (NeedParens -> IdentInfo -> (Builder, [PersistValue]))
-> SqlExpr a
ERaw SqlExprMeta
noMeta forall a b. (a -> b) -> a -> b
$ \NeedParens
p IdentInfo
info ->
                    let (Builder
b1, [PersistValue]
vals) = NeedParens -> IdentInfo -> (Builder, [PersistValue])
f (if NeedParens
p forall a. Eq a => a -> a -> Bool
== NeedParens
Never then NeedParens
Parens else NeedParens
Never) IdentInfo
info
                        build :: (Builder, [PersistValue]) -> (Builder, [PersistValue])
build (Builder
"?", [PersistList [PersistValue]
vals']) =
                            ([Builder] -> Builder
uncommas forall a b. (a -> b) -> a -> b
$ forall a. Int -> a -> [a]
replicate (forall (t :: * -> *) a. Foldable t => t a -> Int
length [PersistValue]
vals') Builder
"?", [PersistValue]
vals')
                        build (Builder, [PersistValue])
expr = (Builder, [PersistValue])
expr
                     in
                        forall (a :: * -> * -> *) b c d.
Arrow a =>
a b c -> a (b, d) (c, d)
first (NeedParens -> Builder -> Builder
parensM NeedParens
p) forall a b. (a -> b) -> a -> b
$ (Builder, [PersistValue]) -> (Builder, [PersistValue])
build (Builder
b1, [PersistValue]
vals)
{-# INLINE unsafeSqlBinOp #-}

-- | Similar to 'unsafeSqlBinOp', but may also be applied to
-- composite keys.  Uses the operator given as the second
-- argument whenever applied to composite keys.
--
-- Usage example:
--
-- @
-- (==.) :: SqlExpr (Value a) -> SqlExpr (Value a) -> SqlExpr (Value Bool)
-- (==.) = unsafeSqlBinOpComposite " = " " AND "
-- @
--
-- Persistent has a hack for implementing composite keys (see
-- 'ECompositeKey' doc for more details), so we're forced to use
-- a hack here as well.  We deconstruct 'ERaw' values based on
-- two rules:
--
--   - If it is a single placeholder, then it's assumed to be
--   coming from a 'PersistList' and thus its components are
--   separated so that they may be applied to a composite key.
--
--   - 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.
unsafeSqlBinOpComposite :: TLB.Builder -> TLB.Builder -> SqlExpr (Value a) -> SqlExpr (Value b) -> SqlExpr (Value c)
unsafeSqlBinOpComposite :: forall a b c.
Builder
-> Builder
-> SqlExpr (Value a)
-> SqlExpr (Value b)
-> SqlExpr (Value c)
unsafeSqlBinOpComposite Builder
op Builder
sep SqlExpr (Value a)
a SqlExpr (Value b)
b
    | forall x. SqlExpr (Value x) -> Bool
isCompositeKey SqlExpr (Value a)
a Bool -> Bool -> Bool
|| forall x. SqlExpr (Value x) -> Bool
isCompositeKey SqlExpr (Value b)
b = forall a.
SqlExprMeta
-> (NeedParens -> IdentInfo -> (Builder, [PersistValue]))
-> SqlExpr a
ERaw SqlExprMeta
noMeta forall a b. (a -> b) -> a -> b
$ forall a b. a -> b -> a
const forall a b. (a -> b) -> a -> b
$ (IdentInfo -> ([Builder], [PersistValue]))
-> (IdentInfo -> ([Builder], [PersistValue]))
-> IdentInfo
-> (Builder, [PersistValue])
compose (forall x.
SqlExpr (Value x) -> IdentInfo -> ([Builder], [PersistValue])
listify SqlExpr (Value a)
a) (forall x.
SqlExpr (Value x) -> IdentInfo -> ([Builder], [PersistValue])
listify SqlExpr (Value b)
b)
    | Bool
otherwise = forall a b c.
Builder
-> SqlExpr (Value a) -> SqlExpr (Value b) -> SqlExpr (Value c)
unsafeSqlBinOp Builder
op SqlExpr (Value a)
a SqlExpr (Value b)
b
  where
    isCompositeKey :: SqlExpr (Value x) -> Bool
    isCompositeKey :: forall x. SqlExpr (Value x) -> Bool
isCompositeKey (ERaw SqlExprMeta
m NeedParens -> IdentInfo -> (Builder, [PersistValue])
_) = SqlExprMeta -> Bool
hasCompositeKeyMeta SqlExprMeta
m

    listify :: SqlExpr (Value x) -> IdentInfo -> ([TLB.Builder], [PersistValue])
    listify :: forall x.
SqlExpr (Value x) -> IdentInfo -> ([Builder], [PersistValue])
listify (ERaw SqlExprMeta
m NeedParens -> IdentInfo -> (Builder, [PersistValue])
f)
        | Just IdentInfo -> [Builder]
k <- SqlExprMeta -> Maybe (IdentInfo -> [Builder])
sqlExprMetaCompositeFields SqlExprMeta
m = forall a b c. (a -> b -> c) -> b -> a -> c
flip (,) [] forall b c a. (b -> c) -> (a -> b) -> a -> c
. IdentInfo -> [Builder]
k
        | Bool
otherwise = (Builder, [PersistValue]) -> ([Builder], [PersistValue])
deconstruct forall b c a. (b -> c) -> (a -> b) -> a -> c
. NeedParens -> IdentInfo -> (Builder, [PersistValue])
f NeedParens
Parens

    deconstruct :: (TLB.Builder, [PersistValue]) -> ([TLB.Builder], [PersistValue])
    deconstruct :: (Builder, [PersistValue]) -> ([Builder], [PersistValue])
deconstruct (Builder
"?", [PersistList [PersistValue]
vals]) = (forall a. Int -> a -> [a]
replicate (forall (t :: * -> *) a. Foldable t => t a -> Int
length [PersistValue]
vals) Builder
"?", [PersistValue]
vals)
    deconstruct (Builder
b', []) = (Text -> Builder
TLB.fromLazyText forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Text -> Text -> [Text]
TL.splitOn Text
"," (Builder -> Text
TLB.toLazyText Builder
b'), [])
    deconstruct (Builder, [PersistValue])
_ = forall a e. Exception e => e -> a
throw (SqlBinOpCompositeError -> EsqueletoError
SqlBinOpCompositeErr SqlBinOpCompositeError
DeconstructionError)

    compose :: (IdentInfo -> ([Builder], [PersistValue]))
-> (IdentInfo -> ([Builder], [PersistValue]))
-> IdentInfo
-> (Builder, [PersistValue])
compose IdentInfo -> ([Builder], [PersistValue])
f1 IdentInfo -> ([Builder], [PersistValue])
f2 IdentInfo
info
        | Bool -> Bool
not (forall (t :: * -> *) a. Foldable t => t a -> Bool
null [PersistValue]
v1 Bool -> Bool -> Bool
|| forall (t :: * -> *) a. Foldable t => t a -> Bool
null [PersistValue]
v2) = forall a e. Exception e => e -> a
throw (SqlBinOpCompositeError -> EsqueletoError
SqlBinOpCompositeErr SqlBinOpCompositeError
NullPlaceholdersError)
        | forall (t :: * -> *) a. Foldable t => t a -> Int
length [Builder]
b1 forall a. Eq a => a -> a -> Bool
/= forall (t :: * -> *) a. Foldable t => t a -> Int
length [Builder]
b2   = forall a e. Exception e => e -> a
throw (SqlBinOpCompositeError -> EsqueletoError
SqlBinOpCompositeErr SqlBinOpCompositeError
MismatchingLengthsError)
        | Bool
otherwise                = (Builder
bc, [PersistValue]
vc)
      where
        ([Builder]
b1, [PersistValue]
v1) = IdentInfo -> ([Builder], [PersistValue])
f1 IdentInfo
info
        ([Builder]
b2, [PersistValue]
v2) = IdentInfo -> ([Builder], [PersistValue])
f2 IdentInfo
info
        bc :: Builder
bc = Builder -> [Builder] -> Builder
intersperseB Builder
sep [Builder
x forall a. Semigroup a => a -> a -> a
<> Builder
op forall a. Semigroup a => a -> a -> a
<> Builder
y | (Builder
x, Builder
y) <- forall a b. [a] -> [b] -> [(a, b)]
zip [Builder]
b1 [Builder]
b2]
        vc :: [PersistValue]
vc = [PersistValue]
v1 forall a. Semigroup a => a -> a -> a
<> [PersistValue]
v2


-- | (Internal) A raw SQL value.  The same warning from
-- 'unsafeSqlBinOp' applies to this function as well.
unsafeSqlValue :: TLB.Builder -> SqlExpr (Value a)
unsafeSqlValue :: forall a. Builder -> SqlExpr (Value a)
unsafeSqlValue Builder
v = forall a.
SqlExprMeta
-> (NeedParens -> IdentInfo -> (Builder, [PersistValue]))
-> SqlExpr a
ERaw SqlExprMeta
noMeta forall a b. (a -> b) -> a -> b
$ \NeedParens
_ IdentInfo
_ -> (Builder
v, forall a. Monoid a => a
mempty)
{-# INLINE unsafeSqlValue #-}

unsafeSqlEntity :: PersistEntity ent => Ident -> SqlExpr (Entity ent)
unsafeSqlEntity :: forall ent. PersistEntity ent => Ident -> SqlExpr (Entity ent)
unsafeSqlEntity Ident
ident = forall a.
SqlExprMeta
-> (NeedParens -> IdentInfo -> (Builder, [PersistValue]))
-> SqlExpr a
ERaw SqlExprMeta
noMeta forall a b. (a -> b) -> a -> b
$ \NeedParens
_ IdentInfo
info ->
    (IdentInfo -> Ident -> Builder
useIdent IdentInfo
info Ident
ident, [])

valueToFunctionArg :: IdentInfo -> SqlExpr (Value a) -> (TLB.Builder, [PersistValue])
valueToFunctionArg :: forall a.
IdentInfo -> SqlExpr (Value a) -> (Builder, [PersistValue])
valueToFunctionArg IdentInfo
info (ERaw SqlExprMeta
_ NeedParens -> IdentInfo -> (Builder, [PersistValue])
f) = NeedParens -> IdentInfo -> (Builder, [PersistValue])
f NeedParens
Never IdentInfo
info

-- | (Internal) A raw SQL function.  Once again, the same warning
-- from 'unsafeSqlBinOp' applies to this function as well.
unsafeSqlFunction
    :: UnsafeSqlFunctionArgument a
    => TLB.Builder -> a -> SqlExpr (Value b)
unsafeSqlFunction :: forall a b.
UnsafeSqlFunctionArgument a =>
Builder -> a -> SqlExpr (Value b)
unsafeSqlFunction Builder
name a
arg =
    forall a.
SqlExprMeta
-> (NeedParens -> IdentInfo -> (Builder, [PersistValue]))
-> SqlExpr a
ERaw SqlExprMeta
noMeta forall a b. (a -> b) -> a -> b
$ \NeedParens
_ IdentInfo
info ->
        let (Builder
argsTLB, [PersistValue]
argsVals) =
              forall a. Monoid a => [(Builder, a)] -> (Builder, a)
uncommas' forall a b. (a -> b) -> a -> b
$ forall a b. (a -> b) -> [a] -> [b]
map (forall a.
IdentInfo -> SqlExpr (Value a) -> (Builder, [PersistValue])
valueToFunctionArg IdentInfo
info) forall a b. (a -> b) -> a -> b
$ forall a. UnsafeSqlFunctionArgument a => a -> [SqlExpr (Value ())]
toArgList a
arg
        in
            (Builder
name forall a. Semigroup a => a -> a -> a
<> Builder -> Builder
parens Builder
argsTLB, [PersistValue]
argsVals)

-- | (Internal) An unsafe SQL function to extract a subfield from a compound
-- field, e.g. datetime. See 'unsafeSqlBinOp' for warnings.
--
-- Since: 1.3.6.
unsafeSqlExtractSubField
    :: UnsafeSqlFunctionArgument a
    => TLB.Builder -> a -> SqlExpr (Value b)
unsafeSqlExtractSubField :: forall a b.
UnsafeSqlFunctionArgument a =>
Builder -> a -> SqlExpr (Value b)
unsafeSqlExtractSubField Builder
subField a
arg =
    forall a.
SqlExprMeta
-> (NeedParens -> IdentInfo -> (Builder, [PersistValue]))
-> SqlExpr a
ERaw SqlExprMeta
noMeta forall a b. (a -> b) -> a -> b
$ \NeedParens
_ IdentInfo
info ->
        let (Builder
argsTLB, [PersistValue]
argsVals) =
                forall a. Monoid a => [(Builder, a)] -> (Builder, a)
uncommas' forall a b. (a -> b) -> a -> b
$ forall a b. (a -> b) -> [a] -> [b]
map (forall a.
IdentInfo -> SqlExpr (Value a) -> (Builder, [PersistValue])
valueToFunctionArg IdentInfo
info) forall a b. (a -> b) -> a -> b
$ forall a. UnsafeSqlFunctionArgument a => a -> [SqlExpr (Value ())]
toArgList a
arg
        in
            (Builder
"EXTRACT" forall a. Semigroup a => a -> a -> a
<> Builder -> Builder
parens (Builder
subField forall a. Semigroup a => a -> a -> a
<> Builder
" FROM " forall a. Semigroup a => a -> a -> a
<> Builder
argsTLB), [PersistValue]
argsVals)

-- | (Internal) A raw SQL function. Preserves parentheses around arguments.
-- See 'unsafeSqlBinOp' for warnings.
unsafeSqlFunctionParens
    :: UnsafeSqlFunctionArgument a
    => TLB.Builder -> a -> SqlExpr (Value b)
unsafeSqlFunctionParens :: forall a b.
UnsafeSqlFunctionArgument a =>
Builder -> a -> SqlExpr (Value b)
unsafeSqlFunctionParens Builder
name a
arg =
    forall a.
SqlExprMeta
-> (NeedParens -> IdentInfo -> (Builder, [PersistValue]))
-> SqlExpr a
ERaw SqlExprMeta
noMeta forall a b. (a -> b) -> a -> b
$ \NeedParens
_ IdentInfo
info ->
        let valueToFunctionArgParens :: SqlExpr (Value ()) -> (Builder, [PersistValue])
valueToFunctionArgParens (ERaw SqlExprMeta
_ NeedParens -> IdentInfo -> (Builder, [PersistValue])
f) = NeedParens -> IdentInfo -> (Builder, [PersistValue])
f NeedParens
Never IdentInfo
info
            (Builder
argsTLB, [PersistValue]
argsVals) =
                forall a. Monoid a => [(Builder, a)] -> (Builder, a)
uncommas' forall a b. (a -> b) -> a -> b
$ forall a b. (a -> b) -> [a] -> [b]
map SqlExpr (Value ()) -> (Builder, [PersistValue])
valueToFunctionArgParens forall a b. (a -> b) -> a -> b
$ forall a. UnsafeSqlFunctionArgument a => a -> [SqlExpr (Value ())]
toArgList a
arg
        in (Builder
name forall a. Semigroup a => a -> a -> a
<> Builder -> Builder
parens Builder
argsTLB, [PersistValue]
argsVals)

-- | (Internal) An explicit SQL type cast using CAST(value as type).
-- See 'unsafeSqlBinOp' for warnings.
unsafeSqlCastAs :: T.Text -> SqlExpr (Value a) -> SqlExpr (Value b)
unsafeSqlCastAs :: forall a b. Text -> SqlExpr (Value a) -> SqlExpr (Value b)
unsafeSqlCastAs Text
t (ERaw SqlExprMeta
_ NeedParens -> IdentInfo -> (Builder, [PersistValue])
f) = forall a.
SqlExprMeta
-> (NeedParens -> IdentInfo -> (Builder, [PersistValue]))
-> SqlExpr a
ERaw SqlExprMeta
noMeta forall a b. (a -> b) -> a -> b
$ \NeedParens
_ -> ((forall (a :: * -> * -> *) b c d.
Arrow a =>
a b c -> a (b, d) (c, d)
first (\Builder
value -> Builder
"CAST" forall a. Semigroup a => a -> a -> a
<> Builder -> Builder
parens (Builder
value forall a. Semigroup a => a -> a -> a
<> Builder
" AS " forall a. Semigroup a => a -> a -> a
<> Text -> Builder
TLB.fromText Text
t))) forall b c a. (b -> c) -> (a -> b) -> a -> c
. NeedParens -> IdentInfo -> (Builder, [PersistValue])
f NeedParens
Never)

-- | (Internal) This class allows 'unsafeSqlFunction' to work with different
-- numbers of arguments; specifically it allows providing arguments to a sql
-- function via an n-tuple of @SqlExpr (Value _)@ 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. @toArgList ((a,b),(c,d))@ is the same as
-- @toArgList (a,b,c,d)@.
class UnsafeSqlFunctionArgument a where
    toArgList :: a -> [SqlExpr (Value ())]

-- | Useful for 0-argument functions, like @now@ in Postgresql.
--
-- @since 3.2.1
instance UnsafeSqlFunctionArgument () where
    toArgList :: () -> [SqlExpr (Value ())]
toArgList ()
_ = []

instance (a ~ Value b) => UnsafeSqlFunctionArgument (SqlExpr a) where
    toArgList :: SqlExpr a -> [SqlExpr (Value ())]
toArgList = (forall a. a -> [a] -> [a]
:[]) forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a b. SqlExpr (Value a) -> SqlExpr (Value b)
veryUnsafeCoerceSqlExprValue

instance UnsafeSqlFunctionArgument a => UnsafeSqlFunctionArgument [a] where
  toArgList :: [a] -> [SqlExpr (Value ())]
toArgList = forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap forall a. UnsafeSqlFunctionArgument a => a -> [SqlExpr (Value ())]
toArgList

instance
    (UnsafeSqlFunctionArgument a , UnsafeSqlFunctionArgument b)
  =>
    UnsafeSqlFunctionArgument (a, b)
  where
    toArgList :: (a, b) -> [SqlExpr (Value ())]
toArgList (a
a, b
b) = forall a. UnsafeSqlFunctionArgument a => a -> [SqlExpr (Value ())]
toArgList a
a forall a. [a] -> [a] -> [a]
++ forall a. UnsafeSqlFunctionArgument a => a -> [SqlExpr (Value ())]
toArgList b
b

instance
    ( UnsafeSqlFunctionArgument a
    , UnsafeSqlFunctionArgument b
    , UnsafeSqlFunctionArgument c
    )
  =>
    UnsafeSqlFunctionArgument (a, b, c)
  where
    toArgList :: (a, b, c) -> [SqlExpr (Value ())]
toArgList = forall a. UnsafeSqlFunctionArgument a => a -> [SqlExpr (Value ())]
toArgList forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a b c. (a, b, c) -> ((a, b), c)
from3

instance
    ( UnsafeSqlFunctionArgument a
    , UnsafeSqlFunctionArgument b
    , UnsafeSqlFunctionArgument c
    , UnsafeSqlFunctionArgument d
    )
  =>
    UnsafeSqlFunctionArgument (a, b, c, d)
  where
    toArgList :: (a, b, c, d) -> [SqlExpr (Value ())]
toArgList = forall a. UnsafeSqlFunctionArgument a => a -> [SqlExpr (Value ())]
toArgList forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a b c d. (a, b, c, d) -> ((a, b), (c, d))
from4

-- | @since 3.2.3
instance
    ( UnsafeSqlFunctionArgument a
    , UnsafeSqlFunctionArgument b
    , UnsafeSqlFunctionArgument c
    , UnsafeSqlFunctionArgument d
    , UnsafeSqlFunctionArgument e
    )
  =>
    UnsafeSqlFunctionArgument (a, b, c, d, e)
  where
    toArgList :: (a, b, c, d, e) -> [SqlExpr (Value ())]
toArgList = forall a. UnsafeSqlFunctionArgument a => a -> [SqlExpr (Value ())]
toArgList forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a b c d e. (a, b, c, d, e) -> ((a, b), (c, d), e)
from5

-- | @since 3.2.3
instance
    ( UnsafeSqlFunctionArgument a
    , UnsafeSqlFunctionArgument b
    , UnsafeSqlFunctionArgument c
    , UnsafeSqlFunctionArgument d
    , UnsafeSqlFunctionArgument e
    , UnsafeSqlFunctionArgument f
    )
  =>
    UnsafeSqlFunctionArgument (a, b, c, d, e, f)
  where
    toArgList :: (a, b, c, d, e, f) -> [SqlExpr (Value ())]
toArgList = forall a. UnsafeSqlFunctionArgument a => a -> [SqlExpr (Value ())]
toArgList forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a b c d e f. (a, b, c, d, e, f) -> ((a, b), (c, d), (e, f))
from6

-- | @since 3.2.3
instance ( UnsafeSqlFunctionArgument a
         , UnsafeSqlFunctionArgument b
         , UnsafeSqlFunctionArgument c
         , UnsafeSqlFunctionArgument d
         , UnsafeSqlFunctionArgument e
         , UnsafeSqlFunctionArgument f
         , UnsafeSqlFunctionArgument g
         ) => UnsafeSqlFunctionArgument (a, b, c, d, e, f, g) where
  toArgList :: (a, b, c, d, e, f, g) -> [SqlExpr (Value ())]
toArgList = forall a. UnsafeSqlFunctionArgument a => a -> [SqlExpr (Value ())]
toArgList forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a b c d e f g.
(a, b, c, d, e, f, g) -> ((a, b), (c, d), (e, f), g)
from7
-- | @since 3.2.3
instance ( UnsafeSqlFunctionArgument a
         , UnsafeSqlFunctionArgument b
         , UnsafeSqlFunctionArgument c
         , UnsafeSqlFunctionArgument d
         , UnsafeSqlFunctionArgument e
         , UnsafeSqlFunctionArgument f
         , UnsafeSqlFunctionArgument g
         , UnsafeSqlFunctionArgument h
         ) => UnsafeSqlFunctionArgument (a, b, c, d, e, f, g, h) where
  toArgList :: (a, b, c, d, e, f, g, h) -> [SqlExpr (Value ())]
toArgList = forall a. UnsafeSqlFunctionArgument a => a -> [SqlExpr (Value ())]
toArgList forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a b c d e f g h.
(a, b, c, d, e, f, g, h) -> ((a, b), (c, d), (e, f), (g, h))
from8
-- | @since 3.2.3
instance ( UnsafeSqlFunctionArgument a
         , UnsafeSqlFunctionArgument b
         , UnsafeSqlFunctionArgument c
         , UnsafeSqlFunctionArgument d
         , UnsafeSqlFunctionArgument e
         , UnsafeSqlFunctionArgument f
         , UnsafeSqlFunctionArgument g
         , UnsafeSqlFunctionArgument h
         , UnsafeSqlFunctionArgument i
         ) => UnsafeSqlFunctionArgument (a, b, c, d, e, f, g, h, i) where
  toArgList :: (a, b, c, d, e, f, g, h, i) -> [SqlExpr (Value ())]
toArgList = forall a. UnsafeSqlFunctionArgument a => a -> [SqlExpr (Value ())]
toArgList forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a b c d e f g h i.
(a, b, c, d, e, f, g, h, i) -> ((a, b), (c, d), (e, f), (g, h), i)
from9
-- | @since 3.2.3
instance ( UnsafeSqlFunctionArgument a
         , UnsafeSqlFunctionArgument b
         , UnsafeSqlFunctionArgument c
         , UnsafeSqlFunctionArgument d
         , UnsafeSqlFunctionArgument e
         , UnsafeSqlFunctionArgument f
         , UnsafeSqlFunctionArgument g
         , UnsafeSqlFunctionArgument h
         , UnsafeSqlFunctionArgument i
         , UnsafeSqlFunctionArgument j
         ) => UnsafeSqlFunctionArgument (a, b, c, d, e, f, g, h, i, j) where
  toArgList :: (a, b, c, d, e, f, g, h, i, j) -> [SqlExpr (Value ())]
toArgList = forall a. UnsafeSqlFunctionArgument a => a -> [SqlExpr (Value ())]
toArgList forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a b c d e f g h i j.
(a, b, c, d, e, f, g, h, i, j)
-> ((a, b), (c, d), (e, f), (g, h), (i, j))
from10


-- | (Internal) Coerce a value's type from 'SqlExpr (Value a)' to
-- 'SqlExpr (Value b)'.  You should /not/ use this function
-- unless you know what you're doing!
veryUnsafeCoerceSqlExprValue :: SqlExpr (Value a) -> SqlExpr (Value b)
veryUnsafeCoerceSqlExprValue :: forall a b. SqlExpr (Value a) -> SqlExpr (Value b)
veryUnsafeCoerceSqlExprValue = coerce :: forall a b. Coercible a b => a -> b
coerce


-- | (Internal) Coerce a value's type from 'SqlExpr (ValueList
-- a)' to 'SqlExpr (Value a)'.  Does not work with empty lists.
veryUnsafeCoerceSqlExprValueList :: SqlExpr (ValueList a) -> SqlExpr (Value a)
veryUnsafeCoerceSqlExprValueList :: forall a. SqlExpr (ValueList a) -> SqlExpr (Value a)
veryUnsafeCoerceSqlExprValueList = coerce :: forall a b. Coercible a b => a -> b
coerce


----------------------------------------------------------------------

-- | (Internal) Execute an @esqueleto@ @SELECT@ 'SqlQuery' inside
-- @persistent@'s 'SqlPersistT' monad.
rawSelectSource
    ::
    ( SqlSelect a r
    , MonadIO m1
    , MonadIO m2
    , SqlBackendCanRead backend
    )
    => Mode
    -> SqlQuery a
    -> R.ReaderT backend m1 (Acquire (C.ConduitT () r m2 ()))
rawSelectSource :: forall a r (m1 :: * -> *) (m2 :: * -> *) backend.
(SqlSelect a r, MonadIO m1, MonadIO m2,
 SqlBackendCanRead backend) =>
Mode
-> SqlQuery a -> ReaderT backend m1 (Acquire (ConduitT () r m2 ()))
rawSelectSource Mode
mode SqlQuery a
query = do
    SqlBackend
conn <- forall sup sub. BackendCompatible sup sub => sub -> sup
projectBackend forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> forall (m :: * -> *) r. Monad m => ReaderT r m r
R.ask
    let SqlBackend
_ = SqlBackend
conn :: SqlBackend
    Acquire (ConduitM () [PersistValue] m2 ())
res <- forall r' r (m :: * -> *) a.
(r' -> r) -> ReaderT r m a -> ReaderT r' m a
R.withReaderT (forall a b. a -> b -> a
const SqlBackend
conn) (SqlBackend
-> ReaderT
     SqlBackend m1 (Acquire (ConduitM () [PersistValue] m2 ()))
run SqlBackend
conn)
    forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$ (forall (m :: * -> *) a b c r.
Monad m =>
ConduitT a b m () -> ConduitT b c m r -> ConduitT a c m r
C..| ConduitT [PersistValue] r m2 ()
massage) forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
`fmap` Acquire (ConduitM () [PersistValue] m2 ())
res
  where
    run :: SqlBackend
-> ReaderT
     SqlBackend m1 (Acquire (ConduitM () [PersistValue] m2 ()))
run SqlBackend
conn =
        forall a b c. (a -> b -> c) -> (a, b) -> c
uncurry forall (m1 :: * -> *) (m2 :: * -> *) env.
(MonadIO m1, MonadIO m2, BackendCompatible SqlBackend env) =>
Text
-> [PersistValue]
-> ReaderT env m1 (Acquire (ConduitM () [PersistValue] m2 ()))
rawQueryRes forall a b. (a -> b) -> a -> b
$
        forall (a :: * -> * -> *) b c d.
Arrow a =>
a b c -> a (b, d) (c, d)
first Builder -> Text
builderToText forall a b. (a -> b) -> a -> b
$
        forall a r backend.
(SqlSelect a r, BackendCompatible SqlBackend backend) =>
Mode
-> (backend, IdentState) -> SqlQuery a -> (Builder, [PersistValue])
toRawSql Mode
mode (SqlBackend
conn, IdentState
initialIdentState) SqlQuery a
query

    massage :: ConduitT [PersistValue] r m2 ()
massage = do
        Maybe [PersistValue]
mrow <- forall (m :: * -> *) i o. Monad m => ConduitT i o m (Maybe i)
C.await
        case forall a r. SqlSelect a r => [PersistValue] -> Either Text r
sqlSelectProcessRow forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe [PersistValue]
mrow of
            Just (Right r
r)  -> forall (m :: * -> *) o i. Monad m => o -> ConduitT i o m ()
C.yield r
r forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> ConduitT [PersistValue] r m2 ()
massage
            Just (Left Text
err) -> forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO forall a b. (a -> b) -> a -> b
$ forall e a. Exception e => e -> IO a
throwIO forall a b. (a -> b) -> a -> b
$ Text -> PersistException
PersistMarshalError Text
err
            Maybe (Either Text r)
Nothing         -> forall (m :: * -> *) a. Monad m => a -> m a
return ()

-- | Execute an @esqueleto@ @SELECT@ query inside @persistent@'s
-- 'SqlPersistT' monad and return a 'C.Source' of rows.
selectSource
    ::
    ( SqlSelect a r
    , BackendCompatible SqlBackend backend
    , IsPersistBackend backend
    , PersistQueryRead backend
    , PersistStoreRead backend, PersistUniqueRead backend
    , MonadResource m
    )
    => SqlQuery a
    -> C.ConduitT () r (R.ReaderT backend m) ()
selectSource :: forall a r backend (m :: * -> *).
(SqlSelect a r, BackendCompatible SqlBackend backend,
 IsPersistBackend backend, PersistQueryRead backend,
 PersistStoreRead backend, PersistUniqueRead backend,
 MonadResource m) =>
SqlQuery a -> ConduitT () r (ReaderT backend m) ()
selectSource SqlQuery a
query = do
    Acquire (ConduitT () r (ReaderT backend m) ())
res <- forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall a b. (a -> b) -> a -> b
$ forall a r (m1 :: * -> *) (m2 :: * -> *) backend.
(SqlSelect a r, MonadIO m1, MonadIO m2,
 SqlBackendCanRead backend) =>
Mode
-> SqlQuery a -> ReaderT backend m1 (Acquire (ConduitT () r m2 ()))
rawSelectSource Mode
SELECT SqlQuery a
query
    (ReleaseKey
key, ConduitT () r (ReaderT backend m) ()
src) <- forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall a b. (a -> b) -> a -> b
$ forall (m :: * -> *) a.
MonadResource m =>
Acquire a -> m (ReleaseKey, a)
allocateAcquire Acquire (ConduitT () r (ReaderT backend m) ())
res
    ConduitT () r (ReaderT backend m) ()
src
    forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall a b. (a -> b) -> a -> b
$ forall (m :: * -> *). MonadIO m => ReleaseKey -> m ()
release ReleaseKey
key

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

-- | Execute an @esqueleto@ @SELECT@ query inside @persistent@'s
-- 'SqlPersistT' monad and return the first entry wrapped in a @Maybe@.
-- @since 3.5.1.0
--
-- === __Example usage__
--
-- @
-- firstPerson :: MonadIO m => SqlPersistT m (Maybe (Entity Person))
-- firstPerson =
--  'selectOne' $ do
--      person <- 'from' $ 'table' @Person
--      return person
-- @
--
-- The above query is equivalent to a 'select' combined with 'limit' but you
-- would still have to transform the results from a list:
--
-- @
-- firstPerson :: MonadIO m => SqlPersistT m [Entity Person]
-- firstPerson =
--  'select' $ do
--      person <- 'from' $ 'table' @Person
--      'limit' 1
--      return person
-- @

selectOne :: (SqlSelect a r, MonadIO m, SqlBackendCanRead backend) => SqlQuery a -> R.ReaderT backend m (Maybe r)
selectOne :: forall a r (m :: * -> *) backend.
(SqlSelect a r, MonadIO m, SqlBackendCanRead backend) =>
SqlQuery a -> ReaderT backend m (Maybe r)
selectOne SqlQuery a
query = forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap forall a. [a] -> Maybe a
Maybe.listToMaybe forall a b. (a -> b) -> a -> b
$ forall a r (m :: * -> *) backend.
(SqlSelect a r, MonadIO m, SqlBackendCanRead backend) =>
SqlQuery a -> ReaderT backend m [r]
select forall a b. (a -> b) -> a -> b
$ Int64 -> SqlQuery ()
limit Int64
1 forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> SqlQuery a
query

-- | (Internal) Run a 'C.Source' of rows.
runSource
    :: Monad m
    => C.ConduitT () r (R.ReaderT backend m) ()
    -> R.ReaderT backend m [r]
runSource :: forall (m :: * -> *) r backend.
Monad m =>
ConduitT () r (ReaderT backend m) () -> ReaderT backend m [r]
runSource ConduitT () r (ReaderT backend m) ()
src = forall (m :: * -> *) r. Monad m => ConduitT () Void m r -> m r
C.runConduit forall a b. (a -> b) -> a -> b
$ ConduitT () r (ReaderT backend m) ()
src forall (m :: * -> *) a b c r.
Monad m =>
ConduitT a b m () -> ConduitT b c m r -> ConduitT a c m r
C..| forall (m :: * -> *) a o. Monad m => ConduitT a o m [a]
CL.consume

-- | (Internal) Execute an @esqueleto@ statement inside
-- @persistent@'s 'SqlPersistT' monad.
rawEsqueleto
    :: (MonadIO m, SqlSelect a r, BackendCompatible SqlBackend backend)
    => Mode
    -> SqlQuery a
    -> R.ReaderT backend m Int64
rawEsqueleto :: forall (m :: * -> *) a r backend.
(MonadIO m, SqlSelect a r, BackendCompatible SqlBackend backend) =>
Mode -> SqlQuery a -> ReaderT backend m Int64
rawEsqueleto Mode
mode SqlQuery a
query = do
    backend
conn <- forall (m :: * -> *) r. Monad m => ReaderT r m r
R.ask
    forall a b c. (a -> b -> c) -> (a, b) -> c
uncurry forall (m :: * -> *) backend.
(MonadIO m, BackendCompatible SqlBackend backend) =>
Text -> [PersistValue] -> ReaderT backend m Int64
rawExecuteCount forall a b. (a -> b) -> a -> b
$
        forall (a :: * -> * -> *) b c d.
Arrow a =>
a b c -> a (b, d) (c, d)
first Builder -> Text
builderToText forall a b. (a -> b) -> a -> b
$
        forall a r backend.
(SqlSelect a r, BackendCompatible SqlBackend backend) =>
Mode
-> (backend, IdentState) -> SqlQuery a -> (Builder, [PersistValue])
toRawSql Mode
mode (backend
conn, IdentState
initialIdentState) SqlQuery a
query

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

-- | Same as 'delete', but returns the number of rows affected.
deleteCount
    :: (MonadIO m, SqlBackendCanWrite backend)
    => SqlQuery ()
    -> R.ReaderT backend m Int64
deleteCount :: forall (m :: * -> *) backend.
(MonadIO m, SqlBackendCanWrite backend) =>
SqlQuery () -> ReaderT backend m Int64
deleteCount SqlQuery ()
a = forall (m :: * -> *) a r backend.
(MonadIO m, SqlSelect a r, BackendCompatible SqlBackend backend) =>
Mode -> SqlQuery a -> ReaderT backend m Int64
rawEsqueleto Mode
DELETE SqlQuery ()
a

-- | Execute an @esqueleto@ @UPDATE@ query inside @persistent@'s
-- 'SqlPersistT' monad.  Note that currently there are no type
-- checks for statements that should not appear on a @UPDATE@
-- query.
--
-- Example of usage:
--
-- @
-- 'update' $ \\p -> do
-- 'set' p [ PersonAge '=.' 'just' ('val' thisYear) -. p '^.' PersonBorn ]
-- 'where_' $ isNothing (p '^.' PersonAge)
-- @
update
    ::
    ( MonadIO m, PersistEntity val
    , BackendCompatible SqlBackend (PersistEntityBackend val)
    , SqlBackendCanWrite backend
    )
    => (SqlExpr (Entity val) -> SqlQuery ())
    -> R.ReaderT backend m ()
update :: forall (m :: * -> *) val backend.
(MonadIO m, PersistEntity val,
 BackendCompatible SqlBackend (PersistEntityBackend val),
 SqlBackendCanWrite backend) =>
(SqlExpr (Entity val) -> SqlQuery ()) -> ReaderT backend m ()
update SqlExpr (Entity val) -> SqlQuery ()
a = forall (f :: * -> *) a. Functor f => f a -> f ()
void forall a b. (a -> b) -> a -> b
$ forall (m :: * -> *) val backend.
(MonadIO m, PersistEntity val,
 BackendCompatible SqlBackend (PersistEntityBackend val),
 SqlBackendCanWrite backend) =>
(SqlExpr (Entity val) -> SqlQuery ()) -> ReaderT backend m Int64
updateCount SqlExpr (Entity val) -> SqlQuery ()
a

-- | Same as 'update', but returns the number of rows affected.
updateCount
    ::
    ( MonadIO m, PersistEntity val
    , BackendCompatible SqlBackend (PersistEntityBackend val)
    , SqlBackendCanWrite backend
    )
    => (SqlExpr (Entity val) -> SqlQuery ())
    -> R.ReaderT backend m Int64
updateCount :: forall (m :: * -> *) val backend.
(MonadIO m, PersistEntity val,
 BackendCompatible SqlBackend (PersistEntityBackend val),
 SqlBackendCanWrite backend) =>
(SqlExpr (Entity val) -> SqlQuery ()) -> ReaderT backend m Int64
updateCount SqlExpr (Entity val) -> SqlQuery ()
a = forall (m :: * -> *) a r backend.
(MonadIO m, SqlSelect a r, BackendCompatible SqlBackend backend) =>
Mode -> SqlQuery a -> ReaderT backend m Int64
rawEsqueleto Mode
UPDATE forall a b. (a -> b) -> a -> b
$ forall a b. From a => (a -> SqlQuery b) -> SqlQuery b
from SqlExpr (Entity val) -> SqlQuery ()
a

builderToText :: TLB.Builder -> T.Text
builderToText :: Builder -> Text
builderToText = Text -> Text
TL.toStrict forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> Builder -> Text
TLB.toLazyTextWith Int
defaultChunkSize
  where
    defaultChunkSize :: Int
    defaultChunkSize :: Int
defaultChunkSize = Int
1024 forall a. Num a => a -> a -> a
- Int
32

-- | (Internal) Pretty prints a 'SqlQuery' into a SQL query.
--
-- Note: if you're curious about the SQL query being generated by
-- @esqueleto@, instead of manually using this function (which is
-- possible but tedious), see the 'renderQueryToText' function (along with
-- 'renderQuerySelect', 'renderQueryUpdate', etc).
toRawSql
  :: (SqlSelect a r, BackendCompatible SqlBackend backend)
  => Mode -> (backend, IdentState) -> SqlQuery a -> (TLB.Builder, [PersistValue])
toRawSql :: forall a r backend.
(SqlSelect a r, BackendCompatible SqlBackend backend) =>
Mode
-> (backend, IdentState) -> SqlQuery a -> (Builder, [PersistValue])
toRawSql Mode
mode (backend
conn, IdentState
firstIdentState) SqlQuery a
query =
    let ((a
ret, SideData
sd), IdentState
finalIdentState) =
            forall a b c. (a -> b -> c) -> b -> a -> c
flip forall s a. State s a -> s -> (a, s)
S.runState IdentState
firstIdentState forall a b. (a -> b) -> a -> b
$
            forall w (m :: * -> *) a. WriterT w m a -> m (a, w)
W.runWriterT forall a b. (a -> b) -> a -> b
$
            forall a.
SqlQuery a -> WriterT SideData (StateT IdentState Identity) a
unQ SqlQuery a
query
        SideData DistinctClause
distinctClause
                 [FromClause]
fromClauses
                 [SetClause]
setClauses
                 WhereClause
whereClauses
                 GroupByClause
groupByClause
                 WhereClause
havingClause
                 [SqlExpr OrderBy]
orderByClauses
                 LimitClause
limitClause
                 LockingClause
lockingClause
                 [CommonTableExpressionClause]
cteClause = SideData
sd
        -- Pass the finalIdentState (containing all identifiers
        -- that were used) to the subsequent calls.  This ensures
        -- that no name clashes will occur on subqueries that may
        -- appear on the expressions below.
        info :: IdentInfo
info = (forall sup sub. BackendCompatible sup sub => sub -> sup
projectBackend backend
conn, IdentState
finalIdentState)
    in forall a. Monoid a => [a] -> a
mconcat
        [ IdentInfo
-> [CommonTableExpressionClause] -> (Builder, [PersistValue])
makeCte        IdentInfo
info [CommonTableExpressionClause]
cteClause
        , forall a r.
SqlSelect a r =>
IdentInfo -> Mode -> a -> (Builder, [PersistValue])
makeInsertInto IdentInfo
info Mode
mode a
ret
        , forall a r.
SqlSelect a r =>
IdentInfo
-> Mode -> DistinctClause -> a -> (Builder, [PersistValue])
makeSelect     IdentInfo
info Mode
mode DistinctClause
distinctClause a
ret
        , IdentInfo -> Mode -> [FromClause] -> (Builder, [PersistValue])
makeFrom       IdentInfo
info Mode
mode [FromClause]
fromClauses
        , IdentInfo -> [SetClause] -> (Builder, [PersistValue])
makeSet        IdentInfo
info [SetClause]
setClauses
        , IdentInfo -> WhereClause -> (Builder, [PersistValue])
makeWhere      IdentInfo
info WhereClause
whereClauses
        , IdentInfo -> GroupByClause -> (Builder, [PersistValue])
makeGroupBy    IdentInfo
info GroupByClause
groupByClause
        , IdentInfo -> WhereClause -> (Builder, [PersistValue])
makeHaving     IdentInfo
info WhereClause
havingClause
        , IdentInfo -> [SqlExpr OrderBy] -> (Builder, [PersistValue])
makeOrderBy    IdentInfo
info [SqlExpr OrderBy]
orderByClauses
        , IdentInfo -> LimitClause -> (Builder, [PersistValue])
makeLimit      IdentInfo
info LimitClause
limitClause
        , IdentInfo -> LockingClause -> (Builder, [PersistValue])
makeLocking    IdentInfo
info LockingClause
lockingClause
        ]

-- | Renders a 'SqlQuery' into a 'Text' value along with the list of
-- 'PersistValue's that would be supplied to the database for @?@ placeholders.
--
-- You must ensure that the 'Mode' you pass to this function corresponds with
-- the actual 'SqlQuery'. If you pass a query that uses incompatible features
-- (like an @INSERT@ statement with a @SELECT@ mode) then you'll get a weird
-- result.
--
-- @since 3.1.1
renderQueryToText
    :: (SqlSelect a r, BackendCompatible SqlBackend backend, Monad m)
    => Mode
    -- ^ Whether to render as an 'SELECT', 'DELETE', etc.
    -> SqlQuery a
    -- ^ The SQL query you want to render.
    -> R.ReaderT backend m (T.Text, [PersistValue])
renderQueryToText :: forall a r backend (m :: * -> *).
(SqlSelect a r, BackendCompatible SqlBackend backend, Monad m) =>
Mode -> SqlQuery a -> ReaderT backend m (Text, [PersistValue])
renderQueryToText Mode
mode SqlQuery a
query = do
    backend
backend <- forall (m :: * -> *) r. Monad m => ReaderT r m r
R.ask
    let (Builder
builder, [PersistValue]
pvals) = forall a r backend.
(SqlSelect a r, BackendCompatible SqlBackend backend) =>
Mode
-> (backend, IdentState) -> SqlQuery a -> (Builder, [PersistValue])
toRawSql Mode
mode (backend
backend, IdentState
initialIdentState) SqlQuery a
query
    forall (f :: * -> *) a. Applicative f => a -> f a
pure (Builder -> Text
builderToText Builder
builder, [PersistValue]
pvals)

-- | Renders a 'SqlQuery' into a 'Text' value along with the list of
-- 'PersistValue's that would be supplied to the database for @?@ placeholders.
--
-- @since 3.1.1
renderQuerySelect
    :: (SqlSelect a r, BackendCompatible SqlBackend backend, Monad m)
    => SqlQuery a
    -- ^ The SQL query you want to render.
    -> R.ReaderT backend m (T.Text, [PersistValue])
renderQuerySelect :: forall a r backend (m :: * -> *).
(SqlSelect a r, BackendCompatible SqlBackend backend, Monad m) =>
SqlQuery a -> ReaderT backend m (Text, [PersistValue])
renderQuerySelect = forall a r backend (m :: * -> *).
(SqlSelect a r, BackendCompatible SqlBackend backend, Monad m) =>
Mode -> SqlQuery a -> ReaderT backend m (Text, [PersistValue])
renderQueryToText Mode
SELECT

-- | Renders a 'SqlQuery' into a 'Text' value along with the list of
-- 'PersistValue's that would be supplied to the database for @?@ placeholders.
--
-- @since 3.1.1
renderQueryDelete
    :: (SqlSelect a r, BackendCompatible SqlBackend backend, Monad m)
    => SqlQuery a
    -- ^ The SQL query you want to render.
    -> R.ReaderT backend m (T.Text, [PersistValue])
renderQueryDelete :: forall a r backend (m :: * -> *).
(SqlSelect a r, BackendCompatible SqlBackend backend, Monad m) =>
SqlQuery a -> ReaderT backend m (Text, [PersistValue])
renderQueryDelete = forall a r backend (m :: * -> *).
(SqlSelect a r, BackendCompatible SqlBackend backend, Monad m) =>
Mode -> SqlQuery a -> ReaderT backend m (Text, [PersistValue])
renderQueryToText Mode
DELETE

-- | Renders a 'SqlQuery' into a 'Text' value along with the list of
-- 'PersistValue's that would be supplied to the database for @?@ placeholders.
--
-- @since 3.1.1
renderQueryUpdate
    :: (SqlSelect a r, BackendCompatible SqlBackend backend, Monad m)
    => SqlQuery a
    -- ^ The SQL query you want to render.
    -> R.ReaderT backend m (T.Text, [PersistValue])
renderQueryUpdate :: forall a r backend (m :: * -> *).
(SqlSelect a r, BackendCompatible SqlBackend backend, Monad m) =>
SqlQuery a -> ReaderT backend m (Text, [PersistValue])
renderQueryUpdate = forall a r backend (m :: * -> *).
(SqlSelect a r, BackendCompatible SqlBackend backend, Monad m) =>
Mode -> SqlQuery a -> ReaderT backend m (Text, [PersistValue])
renderQueryToText Mode
UPDATE

-- | Renders a 'SqlQuery' into a 'Text' value along with the list of
-- 'PersistValue's that would be supplied to the database for @?@ placeholders.
--
-- @since 3.1.1
renderQueryInsertInto
    :: (SqlSelect a r, BackendCompatible SqlBackend backend, Monad m)
    => SqlQuery a
    -- ^ The SQL query you want to render.
    -> R.ReaderT backend m (T.Text, [PersistValue])
renderQueryInsertInto :: forall a r backend (m :: * -> *).
(SqlSelect a r, BackendCompatible SqlBackend backend, Monad m) =>
SqlQuery a -> ReaderT backend m (Text, [PersistValue])
renderQueryInsertInto = forall a r backend (m :: * -> *).
(SqlSelect a r, BackendCompatible SqlBackend backend, Monad m) =>
Mode -> SqlQuery a -> ReaderT backend m (Text, [PersistValue])
renderQueryToText Mode
INSERT_INTO

-- | (Internal) Mode of query being converted by 'toRawSql'.
data Mode
    = SELECT
    | DELETE
    | UPDATE
    | INSERT_INTO

uncommas :: [TLB.Builder] -> TLB.Builder
uncommas :: [Builder] -> Builder
uncommas = Builder -> [Builder] -> Builder
intersperseB Builder
", "

intersperseB :: TLB.Builder -> [TLB.Builder] -> TLB.Builder
intersperseB :: Builder -> [Builder] -> Builder
intersperseB Builder
a = forall a. Monoid a => [a] -> a
mconcat forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a. a -> [a] -> [a]
intersperse Builder
a forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a. (a -> Bool) -> [a] -> [a]
filter (forall a. Eq a => a -> a -> Bool
/= forall a. Monoid a => a
mempty)

uncommas' :: Monoid a => [(TLB.Builder, a)] -> (TLB.Builder, a)
uncommas' :: forall a. Monoid a => [(Builder, a)] -> (Builder, a)
uncommas' = ([Builder] -> Builder
uncommas forall (a :: * -> * -> *) b c b' c'.
Arrow a =>
a b c -> a b' c' -> a (b, b') (c, c')
*** forall a. Monoid a => [a] -> a
mconcat) forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a b. [(a, b)] -> ([a], [b])
unzip

makeCte :: IdentInfo -> [CommonTableExpressionClause] -> (TLB.Builder, [PersistValue])
makeCte :: IdentInfo
-> [CommonTableExpressionClause] -> (Builder, [PersistValue])
makeCte IdentInfo
info [CommonTableExpressionClause]
cteClauses =
  let
    withCteText :: Builder
withCteText
        | Bool
hasRecursive = Builder
"WITH RECURSIVE "
        | Bool
otherwise = Builder
"WITH "
      where
        hasRecursive :: Bool
hasRecursive =
            forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
elem CommonTableExpressionKind
RecursiveCommonTableExpression
            forall a b. (a -> b) -> a -> b
$ forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (\(CommonTableExpressionClause CommonTableExpressionKind
cteKind Ident
_ IdentInfo -> (Builder, [PersistValue])
_) -> CommonTableExpressionKind
cteKind)
            forall a b. (a -> b) -> a -> b
$ [CommonTableExpressionClause]
cteClauses

    cteClauseToText :: CommonTableExpressionClause -> (Builder, [PersistValue])
cteClauseToText (CommonTableExpressionClause CommonTableExpressionKind
_ Ident
cteIdent IdentInfo -> (Builder, [PersistValue])
cteFn) =
        forall (a :: * -> * -> *) b c d.
Arrow a =>
a b c -> a (b, d) (c, d)
first
            (\Builder
tlb -> IdentInfo -> Ident -> Builder
useIdent IdentInfo
info Ident
cteIdent forall a. Semigroup a => a -> a -> a
<> Builder
" AS " forall a. Semigroup a => a -> a -> a
<> Builder -> Builder
parens Builder
tlb)
            (IdentInfo -> (Builder, [PersistValue])
cteFn IdentInfo
info)

    cteBody :: (Builder, [PersistValue])
cteBody =
        forall a. Monoid a => [a] -> a
mconcat
        forall a b. (a -> b) -> a -> b
$ forall a. a -> [a] -> [a]
intersperse (Builder
",\n", forall a. Monoid a => a
mempty)
        forall a b. (a -> b) -> a -> b
$ forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap CommonTableExpressionClause -> (Builder, [PersistValue])
cteClauseToText [CommonTableExpressionClause]
cteClauses
  in
    case [CommonTableExpressionClause]
cteClauses of
        [] ->
            forall a. Monoid a => a
mempty
        [CommonTableExpressionClause]
_ ->
          forall (a :: * -> * -> *) b c d.
Arrow a =>
a b c -> a (b, d) (c, d)
first (\Builder
tlb -> Builder
withCteText forall a. Semigroup a => a -> a -> a
<> Builder
tlb forall a. Semigroup a => a -> a -> a
<> Builder
"\n") (Builder, [PersistValue])
cteBody

makeInsertInto :: SqlSelect a r => IdentInfo -> Mode -> a -> (TLB.Builder, [PersistValue])
makeInsertInto :: forall a r.
SqlSelect a r =>
IdentInfo -> Mode -> a -> (Builder, [PersistValue])
makeInsertInto IdentInfo
info Mode
INSERT_INTO a
ret = forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlInsertInto IdentInfo
info a
ret
makeInsertInto IdentInfo
_    Mode
_           a
_   = forall a. Monoid a => a
mempty

makeSelect :: SqlSelect a r => IdentInfo -> Mode -> DistinctClause -> a -> (TLB.Builder, [PersistValue])
makeSelect :: forall a r.
SqlSelect a r =>
IdentInfo
-> Mode -> DistinctClause -> a -> (Builder, [PersistValue])
makeSelect IdentInfo
info Mode
mode_ DistinctClause
distinctClause a
ret = Mode -> (Builder, [PersistValue])
process Mode
mode_
  where
    process :: Mode -> (Builder, [PersistValue])
process Mode
mode =
        case Mode
mode of
            Mode
SELECT      -> (Builder, [PersistValue]) -> (Builder, [PersistValue])
withCols (Builder, [PersistValue])
selectKind
            Mode
DELETE      -> forall {a} {a}. a -> (a, [a])
plain Builder
"DELETE "
            Mode
UPDATE      -> forall {a} {a}. a -> (a, [a])
plain Builder
"UPDATE "
            Mode
INSERT_INTO -> Mode -> (Builder, [PersistValue])
process Mode
SELECT
    selectKind :: (Builder, [PersistValue])
selectKind =
        case DistinctClause
distinctClause of
            DistinctClause
DistinctAll      -> (Builder
"SELECT ", [])
            DistinctClause
DistinctStandard -> (Builder
"SELECT DISTINCT ", [])
            DistinctOn [SqlExpr DistinctOn]
exprs ->
                forall (a :: * -> * -> *) b c d.
Arrow a =>
a b c -> a (b, d) (c, d)
first ((Builder
"SELECT DISTINCT ON (" forall a. Semigroup a => a -> a -> a
<>) forall b c a. (b -> c) -> (a -> b) -> a -> c
. (forall a. Semigroup a => a -> a -> a
<> Builder
") "))
                forall a b. (a -> b) -> a -> b
$ forall a. Monoid a => [(Builder, a)] -> (Builder, a)
uncommas' (SqlExpr DistinctOn -> (Builder, [PersistValue])
processExpr forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> [SqlExpr DistinctOn]
exprs)
      where
        processExpr :: SqlExpr DistinctOn -> (Builder, [PersistValue])
processExpr SqlExpr DistinctOn
e = forall a.
IdentInfo -> SqlExpr (Value a) -> (Builder, [PersistValue])
materializeExpr IdentInfo
info (coerce :: forall a b. Coercible a b => a -> b
coerce SqlExpr DistinctOn
e :: SqlExpr (Value a))
    withCols :: (Builder, [PersistValue]) -> (Builder, [PersistValue])
withCols (Builder, [PersistValue])
v = (Builder, [PersistValue])
v forall a. Semigroup a => a -> a -> a
<> forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
info a
ret
    plain :: a -> (a, [a])
plain    a
v = (a
v, [])

makeFrom
    :: IdentInfo
    -> Mode
    -> [FromClause]
    -> (TLB.Builder, [PersistValue])
makeFrom :: IdentInfo -> Mode -> [FromClause] -> (Builder, [PersistValue])
makeFrom IdentInfo
_    Mode
_    [] = forall a. Monoid a => a
mempty
makeFrom IdentInfo
info Mode
mode [FromClause]
fs = (Builder, [PersistValue])
ret
  where
    ret :: (Builder, [PersistValue])
ret =
        case SqlBackend
-> [FromClause] -> Either (SqlExpr (Value Bool)) [FromClause]
collectOnClauses (forall a b. (a, b) -> a
fst IdentInfo
info) [FromClause]
fs of
            Left SqlExpr (Value Bool)
expr -> forall a e. Exception e => e -> a
throw forall a b. (a -> b) -> a -> b
$ SqlExpr (Value Bool) -> OnClauseWithoutMatchingJoinException
mkExc SqlExpr (Value Bool)
expr
            Right [FromClause]
fs' -> (Builder, [PersistValue]) -> (Builder, [PersistValue])
keyword forall a b. (a -> b) -> a -> b
$ forall a. Monoid a => [(Builder, a)] -> (Builder, a)
uncommas' (forall a b. (a -> b) -> [a] -> [b]
map (NeedParens -> FromClause -> (Builder, [PersistValue])
mk NeedParens
Never) [FromClause]
fs')
    keyword :: (Builder, [PersistValue]) -> (Builder, [PersistValue])
keyword =
        case Mode
mode of
            Mode
UPDATE -> forall a. a -> a
id
            Mode
_      -> forall (a :: * -> * -> *) b c d.
Arrow a =>
a b c -> a (b, d) (c, d)
first (Builder
"\nFROM " forall a. Semigroup a => a -> a -> a
<>)

    mk :: NeedParens -> FromClause -> (Builder, [PersistValue])
mk NeedParens
_     (FromStart Ident
i EntityDef
def) = Ident -> EntityDef -> (Builder, [PersistValue])
base Ident
i EntityDef
def
    mk NeedParens
paren (FromJoin FromClause
lhs JoinKind
kind FromClause
rhs Maybe (SqlExpr (Value Bool))
monClause) =
        forall (a :: * -> * -> *) b c d.
Arrow a =>
a b c -> a (b, d) (c, d)
first (NeedParens -> Builder -> Builder
parensM NeedParens
paren) forall a b. (a -> b) -> a -> b
$
        forall a. Monoid a => [a] -> a
mconcat [ NeedParens -> FromClause -> (Builder, [PersistValue])
mk NeedParens
Never FromClause
lhs
                , (forall {a}. IsString a => JoinKind -> a
fromKind JoinKind
kind, forall a. Monoid a => a
mempty)
                , NeedParens -> FromClause -> (Builder, [PersistValue])
mk NeedParens
Parens FromClause
rhs
                , forall b a. b -> (a -> b) -> Maybe a -> b
maybe forall a. Monoid a => a
mempty SqlExpr (Value Bool) -> (Builder, [PersistValue])
makeOnClause Maybe (SqlExpr (Value Bool))
monClause
                ]
    mk NeedParens
_ (OnClause SqlExpr (Value Bool)
_) = forall a e. Exception e => e -> a
throw (UnexpectedCaseError -> EsqueletoError
UnexpectedCaseErr UnexpectedCaseError
MakeFromError)
    mk NeedParens
paren (FromRaw NeedParens -> IdentInfo -> (Builder, [PersistValue])
f) = NeedParens -> IdentInfo -> (Builder, [PersistValue])
f NeedParens
paren IdentInfo
info

    base :: Ident -> EntityDef -> (Builder, [PersistValue])
base ident :: Ident
ident@(I Text
identText) EntityDef
def =
        let db :: DBName
db@(DBName Text
dbText) = coerce :: forall a b. Coercible a b => a -> b
coerce forall a b. (a -> b) -> a -> b
$ EntityDef -> EntityNameDB
getEntityDBName EntityDef
def
        in ( IdentInfo -> DBName -> Builder
fromDBName IdentInfo
info DBName
db forall a. Semigroup a => a -> a -> a
<>
                 if Text
dbText forall a. Eq a => a -> a -> Bool
== Text
identText
                 then forall a. Monoid a => a
mempty
                 else Builder
" AS " forall a. Semigroup a => a -> a -> a
<> IdentInfo -> Ident -> Builder
useIdent IdentInfo
info Ident
ident
           , forall a. Monoid a => a
mempty
           )

    fromKind :: JoinKind -> a
fromKind JoinKind
InnerJoinKind      = a
" INNER JOIN "
    fromKind JoinKind
CrossJoinKind      = a
" CROSS JOIN "
    fromKind JoinKind
LeftOuterJoinKind  = a
" LEFT OUTER JOIN "
    fromKind JoinKind
RightOuterJoinKind = a
" RIGHT OUTER JOIN "
    fromKind JoinKind
FullOuterJoinKind  = a
" FULL OUTER JOIN "

    makeOnClause :: SqlExpr (Value Bool) -> (Builder, [PersistValue])
makeOnClause (ERaw SqlExprMeta
_ NeedParens -> IdentInfo -> (Builder, [PersistValue])
f)        = forall (a :: * -> * -> *) b c d.
Arrow a =>
a b c -> a (b, d) (c, d)
first (Builder
" ON " forall a. Semigroup a => a -> a -> a
<>) (NeedParens -> IdentInfo -> (Builder, [PersistValue])
f NeedParens
Never IdentInfo
info)

    mkExc :: SqlExpr (Value Bool) -> OnClauseWithoutMatchingJoinException
    mkExc :: SqlExpr (Value Bool) -> OnClauseWithoutMatchingJoinException
mkExc (ERaw SqlExprMeta
_ NeedParens -> IdentInfo -> (Builder, [PersistValue])
f) =
        String -> OnClauseWithoutMatchingJoinException
OnClauseWithoutMatchingJoinException forall a b. (a -> b) -> a -> b
$
            Text -> String
TL.unpack forall a b. (a -> b) -> a -> b
$ Builder -> Text
TLB.toLazyText forall a b. (a -> b) -> a -> b
$ forall a b. (a, b) -> a
fst (NeedParens -> IdentInfo -> (Builder, [PersistValue])
f NeedParens
Never IdentInfo
info)

makeSet :: IdentInfo -> [SetClause] -> (TLB.Builder, [PersistValue])
makeSet :: IdentInfo -> [SetClause] -> (Builder, [PersistValue])
makeSet IdentInfo
_    [] = forall a. Monoid a => a
mempty
makeSet IdentInfo
info [SetClause]
os = forall (a :: * -> * -> *) b c d.
Arrow a =>
a b c -> a (b, d) (c, d)
first (Builder
"\nSET " forall a. Semigroup a => a -> a -> a
<>) forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a. Monoid a => [(Builder, a)] -> (Builder, a)
uncommas' forall a b. (a -> b) -> a -> b
$ forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap SetClause -> [(Builder, [PersistValue])]
mk [SetClause]
os
  where
    mk :: SetClause -> [(Builder, [PersistValue])]
mk (SetClause (ERaw SqlExprMeta
_ NeedParens -> IdentInfo -> (Builder, [PersistValue])
f))             = [NeedParens -> IdentInfo -> (Builder, [PersistValue])
f NeedParens
Never IdentInfo
info]

makeWhere :: IdentInfo -> WhereClause -> (TLB.Builder, [PersistValue])
makeWhere :: IdentInfo -> WhereClause -> (Builder, [PersistValue])
makeWhere IdentInfo
_    WhereClause
NoWhere            = forall a. Monoid a => a
mempty
makeWhere IdentInfo
info (Where (ERaw SqlExprMeta
_ NeedParens -> IdentInfo -> (Builder, [PersistValue])
f)) = forall (a :: * -> * -> *) b c d.
Arrow a =>
a b c -> a (b, d) (c, d)
first (Builder
"\nWHERE " forall a. Semigroup a => a -> a -> a
<>) forall a b. (a -> b) -> a -> b
$ NeedParens -> IdentInfo -> (Builder, [PersistValue])
f NeedParens
Never IdentInfo
info

makeGroupBy :: IdentInfo -> GroupByClause -> (TLB.Builder, [PersistValue])
makeGroupBy :: IdentInfo -> GroupByClause -> (Builder, [PersistValue])
makeGroupBy IdentInfo
_ (GroupBy []) = (forall a. Monoid a => a
mempty, [])
makeGroupBy IdentInfo
info (GroupBy [SomeValue]
fields) = forall (a :: * -> * -> *) b c d.
Arrow a =>
a b c -> a (b, d) (c, d)
first (Builder
"\nGROUP BY " forall a. Semigroup a => a -> a -> a
<>) (Builder, [PersistValue])
build
  where
    build :: (TLB.Builder, [PersistValue])
    build :: (Builder, [PersistValue])
build = forall a. Monoid a => [(Builder, a)] -> (Builder, a)
uncommas' forall a b. (a -> b) -> a -> b
$ forall a b. (a -> b) -> [a] -> [b]
map SomeValue -> (Builder, [PersistValue])
match [SomeValue]
fields

    match :: SomeValue -> (TLB.Builder, [PersistValue])
    match :: SomeValue -> (Builder, [PersistValue])
match (SomeValue (ERaw SqlExprMeta
_ NeedParens -> IdentInfo -> (Builder, [PersistValue])
f)) = NeedParens -> IdentInfo -> (Builder, [PersistValue])
f NeedParens
Never IdentInfo
info

makeHaving :: IdentInfo -> WhereClause -> (TLB.Builder, [PersistValue])
makeHaving :: IdentInfo -> WhereClause -> (Builder, [PersistValue])
makeHaving IdentInfo
_    WhereClause
NoWhere   = forall a. Monoid a => a
mempty
makeHaving IdentInfo
info (Where (ERaw SqlExprMeta
_ NeedParens -> IdentInfo -> (Builder, [PersistValue])
f)) = forall (a :: * -> * -> *) b c d.
Arrow a =>
a b c -> a (b, d) (c, d)
first (Builder
"\nHAVING " forall a. Semigroup a => a -> a -> a
<>) forall a b. (a -> b) -> a -> b
$ NeedParens -> IdentInfo -> (Builder, [PersistValue])
f NeedParens
Never IdentInfo
info

-- makeHaving, makeWhere and makeOrderBy
makeOrderByNoNewline
    :: IdentInfo -> [OrderByClause] -> (TLB.Builder, [PersistValue])
makeOrderByNoNewline :: IdentInfo -> [SqlExpr OrderBy] -> (Builder, [PersistValue])
makeOrderByNoNewline IdentInfo
_    [] = forall a. Monoid a => a
mempty
makeOrderByNoNewline IdentInfo
info [SqlExpr OrderBy]
os = forall (a :: * -> * -> *) b c d.
Arrow a =>
a b c -> a (b, d) (c, d)
first (Builder
"ORDER BY " forall a. Semigroup a => a -> a -> a
<>) forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a. Monoid a => [(Builder, a)] -> (Builder, a)
uncommas' forall a b. (a -> b) -> a -> b
$ forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap SqlExpr OrderBy -> [(Builder, [PersistValue])]
mk [SqlExpr OrderBy]
os
  where
    mk :: OrderByClause -> [(TLB.Builder, [PersistValue])]
    mk :: SqlExpr OrderBy -> [(Builder, [PersistValue])]
mk (ERaw SqlExprMeta
_ NeedParens -> IdentInfo -> (Builder, [PersistValue])
f) = [NeedParens -> IdentInfo -> (Builder, [PersistValue])
f NeedParens
Never IdentInfo
info]

makeOrderBy :: IdentInfo -> [OrderByClause] -> (TLB.Builder, [PersistValue])
makeOrderBy :: IdentInfo -> [SqlExpr OrderBy] -> (Builder, [PersistValue])
makeOrderBy IdentInfo
_ [] = forall a. Monoid a => a
mempty
makeOrderBy IdentInfo
info [SqlExpr OrderBy]
is =
    let (Builder
tlb, [PersistValue]
vals) = IdentInfo -> [SqlExpr OrderBy] -> (Builder, [PersistValue])
makeOrderByNoNewline IdentInfo
info [SqlExpr OrderBy]
is
    in (Builder
"\n" forall a. Semigroup a => a -> a -> a
<> Builder
tlb, [PersistValue]
vals)

makeLimit :: IdentInfo -> LimitClause -> (TLB.Builder, [PersistValue])
makeLimit :: IdentInfo -> LimitClause -> (Builder, [PersistValue])
makeLimit (SqlBackend
conn, IdentState
_) (Limit Maybe Int64
ml Maybe Int64
mo) =
    let limitRaw :: Text
limitRaw = forall backend (m :: * -> *).
(BackendCompatible SqlBackend backend, MonadReader backend m) =>
(Int, Int) -> Text -> m Text
getConnLimitOffset (Maybe Int64 -> Int
v Maybe Int64
ml, Maybe Int64 -> Int
v Maybe Int64
mo) Text
"\n" SqlBackend
conn
        v :: Maybe Int64 -> Int
        v :: Maybe Int64 -> Int
v = forall b a. b -> (a -> b) -> Maybe a -> b
maybe Int
0 forall a b. (Integral a, Num b) => a -> b
fromIntegral
    in (Text -> Builder
TLB.fromText Text
limitRaw, forall a. Monoid a => a
mempty)

makeLocking :: IdentInfo -> LockingClause -> (TLB.Builder, [PersistValue])
makeLocking :: IdentInfo -> LockingClause -> (Builder, [PersistValue])
makeLocking IdentInfo
_ (LegacyLockingClause LockingKind
lockingClause) =
    case LockingKind
lockingClause of
        LockingKind
ForUpdate           -> (Builder
"\nFOR UPDATE", [])
        LockingKind
ForUpdateSkipLocked -> (Builder
"\nFOR UPDATE SKIP LOCKED", [])
        LockingKind
ForShare            -> (Builder
"\nFOR SHARE", [])
        LockingKind
LockInShareMode     -> (Builder
"\nLOCK IN SHARE MODE", [])
makeLocking IdentInfo
info (PostgresLockingClauses [PostgresLockingKind]
clauses) =
    forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
List.foldl' forall {a} {b}.
(IsString a, Semigroup a, Semigroup b) =>
(a, b) -> (a, b) -> (a, b)
combineBuilderValPairs (Builder
"",[]) (PostgresLockingKind -> (Builder, [PersistValue])
makePostgresLockingClauses forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> [PostgresLockingKind]
clauses)
        where
            combineBuilderValPairs :: (a, b) -> (a, b) -> (a, b)
combineBuilderValPairs (a
builder1, b
persistvals1) (a
builder2,b
persistvals2) =
                (a
builder1 forall a. Semigroup a => a -> a -> a
<> a
builder2 forall a. Semigroup a => a -> a -> a
<> a
"\n", b
persistvals1 forall a. Semigroup a => a -> a -> a
<> b
persistvals2)

            makePostgresLockingClauses :: PostgresLockingKind -> (TLB.Builder , [PersistValue])
            makePostgresLockingClauses :: PostgresLockingKind -> (Builder, [PersistValue])
makePostgresLockingClauses PostgresLockingKind
l =
                PostgresRowLevelLockStrength -> (Builder, [PersistValue])
makeLockingStrength (PostgresLockingKind -> PostgresRowLevelLockStrength
postgresRowLevelLockStrength PostgresLockingKind
l)
                    forall a. Semigroup a => a -> a -> a
<> forall {a} {a}. a -> (a, [a])
plain Builder
" "
                    forall a. Semigroup a => a -> a -> a
<> Maybe LockingOfClause -> (Builder, [PersistValue])
makeOfClause (PostgresLockingKind -> Maybe LockingOfClause
postgresLockingOfClause PostgresLockingKind
l)
                    forall a. Semigroup a => a -> a -> a
<> forall {a} {a}. a -> (a, [a])
plain Builder
" "
                    forall a. Semigroup a => a -> a -> a
<> OnLockedBehavior -> (Builder, [PersistValue])
makeLockingBehavior (PostgresLockingKind -> OnLockedBehavior
postgresOnLockedBehavior PostgresLockingKind
l)
            makeLockingStrength :: PostgresRowLevelLockStrength -> (TLB.Builder, [PersistValue])
            makeLockingStrength :: PostgresRowLevelLockStrength -> (Builder, [PersistValue])
makeLockingStrength PostgresRowLevelLockStrength
PostgresForUpdate = forall {a} {a}. a -> (a, [a])
plain Builder
"FOR UPDATE"
            makeLockingStrength PostgresRowLevelLockStrength
PostgresForShare = forall {a} {a}. a -> (a, [a])
plain Builder
"FOR SHARE"

            makeLockingBehavior :: OnLockedBehavior -> (TLB.Builder, [PersistValue])
            makeLockingBehavior :: OnLockedBehavior -> (Builder, [PersistValue])
makeLockingBehavior OnLockedBehavior
NoWait = forall {a} {a}. a -> (a, [a])
plain Builder
"NO WAIT"
            makeLockingBehavior OnLockedBehavior
SkipLocked = forall {a} {a}. a -> (a, [a])
plain Builder
"SKIP LOCKED"
            makeLockingBehavior OnLockedBehavior
Wait = forall {a} {a}. a -> (a, [a])
plain Builder
""

            makeOfClause :: Maybe LockingOfClause -> (TLB.Builder, [PersistValue])
            makeOfClause :: Maybe LockingOfClause -> (Builder, [PersistValue])
makeOfClause (Just (LockingOfClause a
lockableEnts)) = forall {a} {a}. a -> (a, [a])
plain Builder
"OF " forall a. Semigroup a => a -> a -> a
<> forall a.
LockableEntity a =>
IdentInfo -> a -> (Builder, [PersistValue])
makeLockableEntity IdentInfo
info a
lockableEnts
            makeOfClause Maybe LockingOfClause
Nothing = forall {a} {a}. a -> (a, [a])
plain Builder
""

            plain :: a -> (a, [a])
plain a
v = (a
v,[])
makeLocking IdentInfo
_ LockingClause
NoLockingClause = forall a. Monoid a => a
mempty

parens :: TLB.Builder -> TLB.Builder
parens :: Builder -> Builder
parens Builder
b = Builder
"(" forall a. Semigroup a => a -> a -> a
<> (Builder
b forall a. Semigroup a => a -> a -> a
<> Builder
")")

aliasedEntityColumnIdent :: Ident -> FieldDef -> Ident
aliasedEntityColumnIdent :: Ident -> FieldDef -> Ident
aliasedEntityColumnIdent (I Text
baseIdent) FieldDef
field =
    Text -> Ident
I (Text
baseIdent forall a. Semigroup a => a -> a -> a
<> Text
"_" forall a. Semigroup a => a -> a -> a
<> (DBName -> Text
unDBName forall a b. (a -> b) -> a -> b
$ coerce :: forall a b. Coercible a b => a -> b
coerce forall a b. (a -> b) -> a -> b
$ FieldDef -> FieldNameDB
fieldDB FieldDef
field))

aliasedColumnName :: Ident -> IdentInfo -> T.Text -> TLB.Builder
aliasedColumnName :: Ident -> IdentInfo -> Text -> Builder
aliasedColumnName (I Text
baseIdent) IdentInfo
info Text
columnName =
    IdentInfo -> Ident -> Builder
useIdent IdentInfo
info (Text -> Ident
I (Text
baseIdent forall a. Semigroup a => a -> a -> a
<> Text
"_" forall a. Semigroup a => a -> a -> a
<> Text
columnName))

-- | (Internal) Class for mapping results coming from 'SqlQuery'
-- into actual results.
--
-- This looks very similar to @RawSql@, and it is!  However,
-- there are some crucial differences and ultimately they're
-- different classes.
class SqlSelect a r | a -> r, r -> a where
    -- | Creates the variable part of the @SELECT@ query and
    -- returns the list of 'PersistValue's that will be given to
    -- 'rawQuery'.
    sqlSelectCols :: IdentInfo -> a -> (TLB.Builder, [PersistValue])

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

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

    -- | Create @INSERT INTO@ clause instead.
    sqlInsertInto :: IdentInfo -> a -> (TLB.Builder, [PersistValue])
    sqlInsertInto = forall a e. Exception e => e -> a
throw (UnexpectedCaseError -> EsqueletoError
UnexpectedCaseErr UnexpectedCaseError
UnsupportedSqlInsertIntoType)


-- | @INSERT INTO@ hack.
instance PersistEntity e => SqlSelect (SqlExpr (Insertion e)) (Insertion e) where
    sqlInsertInto :: IdentInfo -> SqlExpr (Insertion e) -> (Builder, [PersistValue])
sqlInsertInto IdentInfo
info SqlExpr (Insertion e)
e =
        let fields :: Builder
fields =
                [Builder] -> Builder
uncommas forall a b. (a -> b) -> a -> b
$
                forall a b. (a -> b) -> [a] -> [b]
map (IdentInfo -> DBName -> Builder
fromDBName IdentInfo
info forall b c a. (b -> c) -> (a -> b) -> a -> c
. coerce :: forall a b. Coercible a b => a -> b
coerce forall b c a. (b -> c) -> (a -> b) -> a -> c
. FieldDef -> FieldNameDB
fieldDB) forall a b. (a -> b) -> a -> b
$
                EntityDef -> [FieldDef]
getEntityFields forall a b. (a -> b) -> a -> b
$
                forall record (proxy :: * -> *).
PersistEntity record =>
proxy record -> EntityDef
entityDef (forall a. SqlExpr (Insertion a) -> Proxy a
proxy SqlExpr (Insertion e)
e)

            proxy :: SqlExpr (Insertion a) -> Proxy a
            proxy :: forall a. SqlExpr (Insertion a) -> Proxy a
proxy = forall a b. a -> b -> a
const forall {k} (t :: k). Proxy t
Proxy

            table :: SqlExpr (Insertion e) -> Builder
table  =
                IdentInfo -> DBName -> Builder
fromDBName IdentInfo
info forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> DBName
DBName forall b c a. (b -> c) -> (a -> b) -> a -> c
. coerce :: forall a b. Coercible a b => a -> b
coerce forall b c a. (b -> c) -> (a -> b) -> a -> c
. EntityDef -> EntityNameDB
getEntityDBName forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall record (proxy :: * -> *).
PersistEntity record =>
proxy record -> EntityDef
entityDef forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a. SqlExpr (Insertion a) -> Proxy a
proxy
        in
            (Builder
"INSERT INTO " forall a. Semigroup a => a -> a -> a
<> SqlExpr (Insertion e) -> Builder
table SqlExpr (Insertion e)
e forall a. Semigroup a => a -> a -> a
<> Builder -> Builder
parens Builder
fields forall a. Semigroup a => a -> a -> a
<> Builder
"\n", [])
    sqlSelectCols :: IdentInfo -> SqlExpr (Insertion e) -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
info (ERaw SqlExprMeta
_ NeedParens -> IdentInfo -> (Builder, [PersistValue])
f) = NeedParens -> IdentInfo -> (Builder, [PersistValue])
f NeedParens
Never IdentInfo
info
    sqlSelectColCount :: Proxy (SqlExpr (Insertion e)) -> Int
sqlSelectColCount   = forall a b. a -> b -> a
const Int
0
    sqlSelectProcessRow :: [PersistValue] -> Either Text (Insertion e)
sqlSelectProcessRow =
      forall a b. a -> b -> a
const (forall a b. b -> Either a b
Right (forall a e. Exception e => e -> a
throw (UnexpectedCaseError -> EsqueletoError
UnexpectedCaseErr UnexpectedCaseError
InsertionFinalError)))

-- | Not useful for 'select', but used for 'update' and 'delete'.
instance SqlSelect () () where
    sqlSelectCols :: IdentInfo -> () -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
_ ()
_ = (Builder
"1", [])
    sqlSelectColCount :: Proxy () -> Int
sqlSelectColCount Proxy ()
_ = Int
1
    sqlSelectProcessRow :: [PersistValue] -> Either Text ()
sqlSelectProcessRow [PersistValue]
_ = forall a b. b -> Either a b
Right ()

unescapedColumnNames :: EntityDef -> [DBName]
unescapedColumnNames :: EntityDef -> [DBName]
unescapedColumnNames EntityDef
ent =
    [DBName] -> [DBName]
addIdColumn [DBName]
rest
  where
    rest :: [DBName]
rest =
        forall a b. (a -> b) -> [a] -> [b]
map (coerce :: forall a b. Coercible a b => a -> b
coerce forall b c a. (b -> c) -> (a -> b) -> a -> c
. FieldDef -> FieldNameDB
fieldDB) (EntityDef -> [FieldDef]
getEntityFields EntityDef
ent)
    addIdColumn :: [DBName] -> [DBName]
addIdColumn =
        case EntityDef -> EntityIdDef
getEntityId EntityDef
ent of
            EntityIdField FieldDef
fd ->
                (:) (coerce :: forall a b. Coercible a b => a -> b
coerce (FieldDef -> FieldNameDB
fieldDB FieldDef
fd))
            EntityIdNaturalKey CompositeDef
_ ->
                forall a. a -> a
id

-- | You may return an 'Entity' from a 'select' query.
instance PersistEntity a => SqlSelect (SqlExpr (Entity a)) (Entity a) where
    sqlSelectCols :: IdentInfo -> SqlExpr (Entity a) -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
info expr :: SqlExpr (Entity a)
expr@(ERaw SqlExprMeta
m NeedParens -> IdentInfo -> (Builder, [PersistValue])
f)
      | Just Ident
baseIdent <- SqlExprMeta -> Maybe Ident
sqlExprMetaAlias SqlExprMeta
m, Bool
False <- SqlExprMeta -> Bool
sqlExprMetaIsReference SqlExprMeta
m =
          let process :: Builder
process = [Builder] -> Builder
uncommas forall a b. (a -> b) -> a -> b
$
                           forall a b. (a -> b) -> [a] -> [b]
map ((Builder
name forall a. Semigroup a => a -> a -> a
<>) forall b c a. (b -> c) -> (a -> b) -> a -> c
. DBName -> Builder
aliasName) forall a b. (a -> b) -> a -> b
$
                           EntityDef -> [DBName]
unescapedColumnNames EntityDef
ed
              aliasName :: DBName -> Builder
aliasName DBName
columnName = (IdentInfo -> DBName -> Builder
fromDBName IdentInfo
info DBName
columnName) forall a. Semigroup a => a -> a -> a
<> Builder
" AS " forall a. Semigroup a => a -> a -> a
<> Ident -> IdentInfo -> Text -> Builder
aliasedColumnName Ident
baseIdent IdentInfo
info (DBName -> Text
unDBName DBName
columnName)
              name :: Builder
name = forall a b. (a, b) -> a
fst (NeedParens -> IdentInfo -> (Builder, [PersistValue])
f NeedParens
Never IdentInfo
info) forall a. Semigroup a => a -> a -> a
<> Builder
"."
              ed :: EntityDef
ed = forall record (proxy :: * -> *).
PersistEntity record =>
proxy record -> EntityDef
entityDef forall a b. (a -> b) -> a -> b
$ forall a. Proxy (SqlExpr (Entity a)) -> Proxy a
getEntityVal forall a b. (a -> b) -> a -> b
$ forall (m :: * -> *) a. Monad m => a -> m a
return SqlExpr (Entity a)
expr
          in (Builder
process, forall a. Monoid a => a
mempty)
      | Just Ident
baseIdent <- SqlExprMeta -> Maybe Ident
sqlExprMetaAlias SqlExprMeta
m, Bool
True <- SqlExprMeta -> Bool
sqlExprMetaIsReference SqlExprMeta
m =
          let process :: Builder
process = [Builder] -> Builder
uncommas forall a b. (a -> b) -> a -> b
$
                           forall a b. (a -> b) -> [a] -> [b]
map ((Builder
name forall a. Semigroup a => a -> a -> a
<>) forall b c a. (b -> c) -> (a -> b) -> a -> c
. Ident -> IdentInfo -> Text -> Builder
aliasedColumnName Ident
baseIdent IdentInfo
info forall b c a. (b -> c) -> (a -> b) -> a -> c
. DBName -> Text
unDBName) forall a b. (a -> b) -> a -> b
$
                           EntityDef -> [DBName]
unescapedColumnNames EntityDef
ed
              name :: Builder
name = forall a b. (a, b) -> a
fst (NeedParens -> IdentInfo -> (Builder, [PersistValue])
f NeedParens
Never IdentInfo
info) forall a. Semigroup a => a -> a -> a
<> Builder
"."
              ed :: EntityDef
ed = forall record (proxy :: * -> *).
PersistEntity record =>
proxy record -> EntityDef
entityDef forall a b. (a -> b) -> a -> b
$ forall a. Proxy (SqlExpr (Entity a)) -> Proxy a
getEntityVal forall a b. (a -> b) -> a -> b
$ forall (m :: * -> *) a. Monad m => a -> m a
return SqlExpr (Entity a)
expr
          in (Builder
process, forall a. Monoid a => a
mempty)
      | Bool
otherwise =
          let process :: Builder
process =
                  [Builder] -> Builder
uncommas
                  forall a b. (a -> b) -> a -> b
$ forall a b. (a -> b) -> [a] -> [b]
map ((Builder
name forall a. Semigroup a => a -> a -> a
<>) forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Builder
TLB.fromText)
                  forall a b. (a -> b) -> a -> b
$ forall a. NonEmpty a -> [a]
NEL.toList
                  forall a b. (a -> b) -> a -> b
$ EntityDef -> SqlBackend -> NonEmpty Text
keyAndEntityColumnNames EntityDef
ed (forall a b. (a, b) -> a
fst IdentInfo
info)
              -- 'name' is the biggest difference between 'RawSql' and
              -- 'SqlSelect'.  We automatically create names for tables
              -- (since it's not the user who's writing the FROM
              -- clause), while 'rawSql' assumes that it's just the
              -- name of the table (which doesn't allow self-joins, for
              -- example).
              name :: Builder
name = forall a b. (a, b) -> a
fst (NeedParens -> IdentInfo -> (Builder, [PersistValue])
f NeedParens
Never IdentInfo
info) forall a. Semigroup a => a -> a -> a
<> Builder
"."
              ed :: EntityDef
ed = forall record (proxy :: * -> *).
PersistEntity record =>
proxy record -> EntityDef
entityDef forall a b. (a -> b) -> a -> b
$ forall a. Proxy (SqlExpr (Entity a)) -> Proxy a
getEntityVal forall a b. (a -> b) -> a -> b
$ forall (m :: * -> *) a. Monad m => a -> m a
return SqlExpr (Entity a)
expr
          in (Builder
process, forall a. Monoid a => a
mempty)

    sqlSelectColCount :: Proxy (SqlExpr (Entity a)) -> Int
sqlSelectColCount = EntityDef -> Int
entityColumnCount forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall record (proxy :: * -> *).
PersistEntity record =>
proxy record -> EntityDef
entityDef forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a. Proxy (SqlExpr (Entity a)) -> Proxy a
getEntityVal
    sqlSelectProcessRow :: [PersistValue] -> Either Text (Entity a)
sqlSelectProcessRow = forall record.
PersistEntity record =>
EntityDef -> [PersistValue] -> Either Text (Entity record)
parseEntityValues EntityDef
ed
      where
        ed :: EntityDef
ed = forall record (proxy :: * -> *).
PersistEntity record =>
proxy record -> EntityDef
entityDef forall a b. (a -> b) -> a -> b
$ forall a. Proxy (SqlExpr (Entity a)) -> Proxy a
getEntityVal (forall {k} (t :: k). Proxy t
Proxy :: Proxy (SqlExpr (Entity a)))

getEntityVal :: Proxy (SqlExpr (Entity a)) -> Proxy a
getEntityVal :: forall a. Proxy (SqlExpr (Entity a)) -> Proxy a
getEntityVal = forall a b. a -> b -> a
const forall {k} (t :: k). Proxy t
Proxy

-- | You may return a possibly-@NULL@ 'Entity' from a 'select' query.
instance PersistEntity a => SqlSelect (SqlExpr (Maybe (Entity a))) (Maybe (Entity a)) where
    sqlSelectCols :: IdentInfo
-> SqlExpr (Maybe (Entity a)) -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
info SqlExpr (Maybe (Entity a))
e = forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
info (coerce :: forall a b. Coercible a b => a -> b
coerce SqlExpr (Maybe (Entity a))
e :: SqlExpr (Entity a))
    sqlSelectColCount :: Proxy (SqlExpr (Maybe (Entity a))) -> Int
sqlSelectColCount = forall a r. SqlSelect a r => Proxy a -> Int
sqlSelectColCount forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall e. Proxy (SqlExpr (Maybe e)) -> Proxy (SqlExpr e)
fromEMaybe
      where
        fromEMaybe :: Proxy (SqlExpr (Maybe e)) -> Proxy (SqlExpr e)
        fromEMaybe :: forall e. Proxy (SqlExpr (Maybe e)) -> Proxy (SqlExpr e)
fromEMaybe = forall a b. a -> b -> a
const forall {k} (t :: k). Proxy t
Proxy
    sqlSelectProcessRow :: [PersistValue] -> Either Text (Maybe (Entity a))
sqlSelectProcessRow [PersistValue]
cols
        | forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all (forall a. Eq a => a -> a -> Bool
== PersistValue
PersistNull) [PersistValue]
cols = forall (m :: * -> *) a. Monad m => a -> m a
return forall a. Maybe a
Nothing
        | Bool
otherwise                 = forall a. a -> Maybe a
Just forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> forall a r. SqlSelect a r => [PersistValue] -> Either Text r
sqlSelectProcessRow [PersistValue]
cols


-- | You may return any single value (i.e. a single column) from
-- a 'select' query.
instance PersistField a => SqlSelect (SqlExpr (Value a)) (Value a) where
    sqlSelectCols :: IdentInfo -> SqlExpr (Value a) -> (Builder, [PersistValue])
sqlSelectCols = forall a.
IdentInfo -> SqlExpr (Value a) -> (Builder, [PersistValue])
materializeExpr
    sqlSelectColCount :: Proxy (SqlExpr (Value a)) -> Int
sqlSelectColCount = forall a b. a -> b -> a
const Int
1
    sqlSelectProcessRow :: [PersistValue] -> Either Text (Value a)
sqlSelectProcessRow [PersistValue
pv] = forall a. a -> Value a
Value forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> forall a. PersistField a => PersistValue -> Either Text a
fromPersistValue PersistValue
pv
    sqlSelectProcessRow [PersistValue]
pvs  = forall a. a -> Value a
Value forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> forall a. PersistField a => PersistValue -> Either Text a
fromPersistValue ([PersistValue] -> PersistValue
PersistList [PersistValue]
pvs)

-- | Materialize a @SqlExpr (Value a)@.
materializeExpr :: IdentInfo -> SqlExpr (Value a) -> (TLB.Builder, [PersistValue])
materializeExpr :: forall a.
IdentInfo -> SqlExpr (Value a) -> (Builder, [PersistValue])
materializeExpr IdentInfo
info (ERaw SqlExprMeta
m NeedParens -> IdentInfo -> (Builder, [PersistValue])
f)
    | Just IdentInfo -> [Builder]
fields <- SqlExprMeta -> Maybe (IdentInfo -> [Builder])
sqlExprMetaCompositeFields SqlExprMeta
m = ([Builder] -> Builder
uncommas forall a b. (a -> b) -> a -> b
$ forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap Builder -> Builder
parens forall a b. (a -> b) -> a -> b
$ IdentInfo -> [Builder]
fields IdentInfo
info, [])
    | Just Ident
alias <- SqlExprMeta -> Maybe Ident
sqlExprMetaAlias SqlExprMeta
m
    , Bool -> Bool
not (SqlExprMeta -> Bool
sqlExprMetaIsReference SqlExprMeta
m) = forall (a :: * -> * -> *) b c d.
Arrow a =>
a b c -> a (b, d) (c, d)
first (forall a. Semigroup a => a -> a -> a
<> Builder
" AS " forall a. Semigroup a => a -> a -> a
<> IdentInfo -> Ident -> Builder
useIdent IdentInfo
info Ident
alias) (NeedParens -> IdentInfo -> (Builder, [PersistValue])
f NeedParens
Parens IdentInfo
info)
    | Bool
otherwise = NeedParens -> IdentInfo -> (Builder, [PersistValue])
f NeedParens
Parens IdentInfo
info


-- | You may return tuples (up to 16-tuples) and tuples of tuples
-- from a 'select' query.
instance (SqlSelect a ra, SqlSelect b rb) => SqlSelect (a, b) (ra, rb) where
    sqlSelectCols :: IdentInfo -> (a, b) -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc (a
a, b
b) =
        forall a. Monoid a => [(Builder, a)] -> (Builder, a)
uncommas'
            [ forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc a
a
            , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc b
b
            ]
    sqlSelectColCount :: Proxy (a, b) -> Int
sqlSelectColCount = forall a b c. (a -> b -> c) -> (a, b) -> c
uncurry forall a. Num a => a -> a -> a
(+) forall b c a. (b -> c) -> (a -> b) -> a -> c
. (forall a r. SqlSelect a r => Proxy a -> Int
sqlSelectColCount forall (a :: * -> * -> *) b c b' c'.
Arrow a =>
a b c -> a b' c' -> a (b, b') (c, c')
*** forall a r. SqlSelect a r => Proxy a -> Int
sqlSelectColCount) forall b c a. (b -> c) -> (a -> b) -> a -> c
. Proxy (a, b) -> (Proxy a, Proxy b)
fromTuple
      where
        fromTuple :: Proxy (a,b) -> (Proxy a, Proxy b)
        fromTuple :: Proxy (a, b) -> (Proxy a, Proxy b)
fromTuple = forall a b. a -> b -> a
const (forall {k} (t :: k). Proxy t
Proxy, forall {k} (t :: k). Proxy t
Proxy)
    sqlSelectProcessRow :: [PersistValue] -> Either Text (ra, rb)
sqlSelectProcessRow =
      let x :: Proxy a
x = forall r z y x. SqlSelect a r => (z -> Either y (r, x)) -> Proxy a
getType [PersistValue] -> Either Text (ra, rb)
processRow
          getType :: SqlSelect a r => (z -> Either y (r,x)) -> Proxy a
          getType :: forall r z y x. SqlSelect a r => (z -> Either y (r, x)) -> Proxy a
getType = forall a b. a -> b -> a
const forall {k} (t :: k). Proxy t
Proxy

          colCountFst :: Int
colCountFst = forall a r. SqlSelect a r => Proxy a -> Int
sqlSelectColCount Proxy a
x

          processRow :: [PersistValue] -> Either Text (ra, rb)
processRow [PersistValue]
row =
              let ([PersistValue]
rowFst, [PersistValue]
rowSnd) = forall a. Int -> [a] -> ([a], [a])
splitAt Int
colCountFst [PersistValue]
row
              in (,) forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> forall a r. SqlSelect a r => [PersistValue] -> Either Text r
sqlSelectProcessRow [PersistValue]
rowFst
                     forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> forall a r. SqlSelect a r => [PersistValue] -> Either Text r
sqlSelectProcessRow [PersistValue]
rowSnd

      in Int
colCountFst seq :: forall a b. a -> b -> b
`seq` [PersistValue] -> Either Text (ra, rb)
processRow
         -- Avoids recalculating 'colCountFst'.

instance ( SqlSelect a ra
         , SqlSelect b rb
         , SqlSelect c rc
         ) => SqlSelect (a, b, c) (ra, rb, rc) where
  sqlSelectCols :: IdentInfo -> (a, b, c) -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc (a
a, b
b, c
c) =
    forall a. Monoid a => [(Builder, a)] -> (Builder, a)
uncommas'
      [ forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc a
a
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc b
b
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc c
c
      ]
  sqlSelectColCount :: Proxy (a, b, c) -> Int
sqlSelectColCount   = forall a r. SqlSelect a r => Proxy a -> Int
sqlSelectColCount forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a b c. Proxy (a, b, c) -> Proxy ((a, b), c)
from3P
  sqlSelectProcessRow :: [PersistValue] -> Either Text (ra, rb, rc)
sqlSelectProcessRow = forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap forall a b c. ((a, b), c) -> (a, b, c)
to3 forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a r. SqlSelect a r => [PersistValue] -> Either Text r
sqlSelectProcessRow

from3P :: Proxy (a,b,c) -> Proxy ((a,b),c)
from3P :: forall a b c. Proxy (a, b, c) -> Proxy ((a, b), c)
from3P = forall a b. a -> b -> a
const forall {k} (t :: k). Proxy t
Proxy

from3 :: (a,b,c) -> ((a,b),c)
from3 :: forall a b c. (a, b, c) -> ((a, b), c)
from3 (a
a,b
b,c
c) = ((a
a,b
b),c
c)

to3 :: ((a,b),c) -> (a,b,c)
to3 :: forall a b c. ((a, b), c) -> (a, b, c)
to3 ((a
a,b
b),c
c) = (a
a,b
b,c
c)

instance ( SqlSelect a ra
         , SqlSelect b rb
         , SqlSelect c rc
         , SqlSelect d rd
         ) => SqlSelect (a, b, c, d) (ra, rb, rc, rd) where
  sqlSelectCols :: IdentInfo -> (a, b, c, d) -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc (a
a, b
b, c
c, d
d) =
    forall a. Monoid a => [(Builder, a)] -> (Builder, a)
uncommas'
      [ forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc a
a
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc b
b
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc c
c
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc d
d
      ]
  sqlSelectColCount :: Proxy (a, b, c, d) -> Int
sqlSelectColCount   = forall a r. SqlSelect a r => Proxy a -> Int
sqlSelectColCount forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a b c d. Proxy (a, b, c, d) -> Proxy ((a, b), (c, d))
from4P
  sqlSelectProcessRow :: [PersistValue] -> Either Text (ra, rb, rc, rd)
sqlSelectProcessRow = forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap forall a b c d. ((a, b), (c, d)) -> (a, b, c, d)
to4 forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a r. SqlSelect a r => [PersistValue] -> Either Text r
sqlSelectProcessRow

from4P :: Proxy (a,b,c,d) -> Proxy ((a,b),(c,d))
from4P :: forall a b c d. Proxy (a, b, c, d) -> Proxy ((a, b), (c, d))
from4P = forall a b. a -> b -> a
const forall {k} (t :: k). Proxy t
Proxy

from4 :: (a,b,c,d) -> ((a,b),(c,d))
from4 :: forall a b c d. (a, b, c, d) -> ((a, b), (c, d))
from4 (a
a,b
b,c
c,d
d) = ((a
a,b
b),(c
c,d
d))

to4 :: ((a,b),(c,d)) -> (a,b,c,d)
to4 :: forall a b c d. ((a, b), (c, d)) -> (a, b, c, d)
to4 ((a
a,b
b),(c
c,d
d)) = (a
a,b
b,c
c,d
d)

instance ( SqlSelect a ra
         , SqlSelect b rb
         , SqlSelect c rc
         , SqlSelect d rd
         , SqlSelect e re
         ) => SqlSelect (a, b, c, d, e) (ra, rb, rc, rd, re) where
  sqlSelectCols :: IdentInfo -> (a, b, c, d, e) -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc (a
a, b
b, c
c, d
d, e
e) =
    forall a. Monoid a => [(Builder, a)] -> (Builder, a)
uncommas'
      [ forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc a
a
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc b
b
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc c
c
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc d
d
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc e
e
      ]
  sqlSelectColCount :: Proxy (a, b, c, d, e) -> Int
sqlSelectColCount   = forall a r. SqlSelect a r => Proxy a -> Int
sqlSelectColCount forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a b c d e.
Proxy (a, b, c, d, e) -> Proxy ((a, b), (c, d), e)
from5P
  sqlSelectProcessRow :: [PersistValue] -> Either Text (ra, rb, rc, rd, re)
sqlSelectProcessRow = forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap forall a b c d e. ((a, b), (c, d), e) -> (a, b, c, d, e)
to5 forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a r. SqlSelect a r => [PersistValue] -> Either Text r
sqlSelectProcessRow

from5P :: Proxy (a,b,c,d,e) -> Proxy ((a,b),(c,d),e)
from5P :: forall a b c d e.
Proxy (a, b, c, d, e) -> Proxy ((a, b), (c, d), e)
from5P = forall a b. a -> b -> a
const forall {k} (t :: k). Proxy t
Proxy

from5 :: (a,b,c,d,e) -> ((a,b),(c,d),e)
from5 :: forall a b c d e. (a, b, c, d, e) -> ((a, b), (c, d), e)
from5 (a
a,b
b,c
c,d
d,e
e) = ((a
a,b
b),(c
c,d
d),e
e)

to5 :: ((a,b),(c,d),e) -> (a,b,c,d,e)
to5 :: forall a b c d e. ((a, b), (c, d), e) -> (a, b, c, d, e)
to5 ((a
a,b
b),(c
c,d
d),e
e) = (a
a,b
b,c
c,d
d,e
e)

instance ( SqlSelect a ra
         , SqlSelect b rb
         , SqlSelect c rc
         , SqlSelect d rd
         , SqlSelect e re
         , SqlSelect f rf
         ) => SqlSelect (a, b, c, d, e, f) (ra, rb, rc, rd, re, rf) where
  sqlSelectCols :: IdentInfo -> (a, b, c, d, e, f) -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc (a
a, b
b, c
c, d
d, e
e, f
f) =
    forall a. Monoid a => [(Builder, a)] -> (Builder, a)
uncommas'
      [ forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc a
a
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc b
b
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc c
c
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc d
d
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc e
e
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc f
f
      ]
  sqlSelectColCount :: Proxy (a, b, c, d, e, f) -> Int
sqlSelectColCount   = forall a r. SqlSelect a r => Proxy a -> Int
sqlSelectColCount forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a b c d e f.
Proxy (a, b, c, d, e, f) -> Proxy ((a, b), (c, d), (e, f))
from6P
  sqlSelectProcessRow :: [PersistValue] -> Either Text (ra, rb, rc, rd, re, rf)
sqlSelectProcessRow = forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap forall a b c d e f. ((a, b), (c, d), (e, f)) -> (a, b, c, d, e, f)
to6 forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a r. SqlSelect a r => [PersistValue] -> Either Text r
sqlSelectProcessRow

from6P :: Proxy (a,b,c,d,e,f) -> Proxy ((a,b),(c,d),(e,f))
from6P :: forall a b c d e f.
Proxy (a, b, c, d, e, f) -> Proxy ((a, b), (c, d), (e, f))
from6P = forall a b. a -> b -> a
const forall {k} (t :: k). Proxy t
Proxy

from6 :: (a,b,c,d,e,f) -> ((a,b),(c,d),(e,f))
from6 :: forall a b c d e f. (a, b, c, d, e, f) -> ((a, b), (c, d), (e, f))
from6 (a
a,b
b,c
c,d
d,e
e,f
f) = ((a
a,b
b),(c
c,d
d),(e
e,f
f))

to6 :: ((a,b),(c,d),(e,f)) -> (a,b,c,d,e,f)
to6 :: forall a b c d e f. ((a, b), (c, d), (e, f)) -> (a, b, c, d, e, f)
to6 ((a
a,b
b),(c
c,d
d),(e
e,f
f)) = (a
a,b
b,c
c,d
d,e
e,f
f)

instance ( SqlSelect a ra
         , SqlSelect b rb
         , SqlSelect c rc
         , SqlSelect d rd
         , SqlSelect e re
         , SqlSelect f rf
         , SqlSelect g rg
         ) => SqlSelect (a, b, c, d, e, f, g) (ra, rb, rc, rd, re, rf, rg) where
  sqlSelectCols :: IdentInfo -> (a, b, c, d, e, f, g) -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc (a
a, b
b, c
c, d
d, e
e, f
f, g
g) =
    forall a. Monoid a => [(Builder, a)] -> (Builder, a)
uncommas'
      [ forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc a
a
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc b
b
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc c
c
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc d
d
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc e
e
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc f
f
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc g
g
      ]
  sqlSelectColCount :: Proxy (a, b, c, d, e, f, g) -> Int
sqlSelectColCount   = forall a r. SqlSelect a r => Proxy a -> Int
sqlSelectColCount forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a b c d e f g.
Proxy (a, b, c, d, e, f, g) -> Proxy ((a, b), (c, d), (e, f), g)
from7P
  sqlSelectProcessRow :: [PersistValue] -> Either Text (ra, rb, rc, rd, re, rf, rg)
sqlSelectProcessRow = forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap forall a b c d e f g.
((a, b), (c, d), (e, f), g) -> (a, b, c, d, e, f, g)
to7 forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a r. SqlSelect a r => [PersistValue] -> Either Text r
sqlSelectProcessRow

from7P :: Proxy (a,b,c,d,e,f,g) -> Proxy ((a,b),(c,d),(e,f),g)
from7P :: forall a b c d e f g.
Proxy (a, b, c, d, e, f, g) -> Proxy ((a, b), (c, d), (e, f), g)
from7P = forall a b. a -> b -> a
const forall {k} (t :: k). Proxy t
Proxy

from7 :: (a,b,c,d,e,f,g) -> ((a,b),(c,d),(e,f),g)
from7 :: forall a b c d e f g.
(a, b, c, d, e, f, g) -> ((a, b), (c, d), (e, f), g)
from7 (a
a,b
b,c
c,d
d,e
e,f
f,g
g) = ((a
a,b
b),(c
c,d
d),(e
e,f
f),g
g)

to7 :: ((a,b),(c,d),(e,f),g) -> (a,b,c,d,e,f,g)
to7 :: forall a b c d e f g.
((a, b), (c, d), (e, f), g) -> (a, b, c, d, e, f, g)
to7 ((a
a,b
b),(c
c,d
d),(e
e,f
f),g
g) = (a
a,b
b,c
c,d
d,e
e,f
f,g
g)

instance ( SqlSelect a ra
         , SqlSelect b rb
         , SqlSelect c rc
         , SqlSelect d rd
         , SqlSelect e re
         , SqlSelect f rf
         , SqlSelect g rg
         , SqlSelect h rh
         ) => SqlSelect (a, b, c, d, e, f, g, h) (ra, rb, rc, rd, re, rf, rg, rh) where
  sqlSelectCols :: IdentInfo -> (a, b, c, d, e, f, g, h) -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc (a
a, b
b, c
c, d
d, e
e, f
f, g
g, h
h) =
    forall a. Monoid a => [(Builder, a)] -> (Builder, a)
uncommas'
      [ forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc a
a
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc b
b
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc c
c
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc d
d
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc e
e
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc f
f
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc g
g
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc h
h
      ]
  sqlSelectColCount :: Proxy (a, b, c, d, e, f, g, h) -> Int
sqlSelectColCount   = forall a r. SqlSelect a r => Proxy a -> Int
sqlSelectColCount forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a b c d e f g h.
Proxy (a, b, c, d, e, f, g, h)
-> Proxy ((a, b), (c, d), (e, f), (g, h))
from8P
  sqlSelectProcessRow :: [PersistValue] -> Either Text (ra, rb, rc, rd, re, rf, rg, rh)
sqlSelectProcessRow = forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap forall a b c d e f g h.
((a, b), (c, d), (e, f), (g, h)) -> (a, b, c, d, e, f, g, h)
to8 forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a r. SqlSelect a r => [PersistValue] -> Either Text r
sqlSelectProcessRow

from8P :: Proxy (a,b,c,d,e,f,g,h) -> Proxy ((a,b),(c,d),(e,f),(g,h))
from8P :: forall a b c d e f g h.
Proxy (a, b, c, d, e, f, g, h)
-> Proxy ((a, b), (c, d), (e, f), (g, h))
from8P = forall a b. a -> b -> a
const forall {k} (t :: k). Proxy t
Proxy

from8 :: (a,b,c,d,e,f,g,h) -> ((a,b),(c,d),(e,f),(g,h))
from8 :: forall a b c d e f g h.
(a, b, c, d, e, f, g, h) -> ((a, b), (c, d), (e, f), (g, h))
from8 (a
a,b
b,c
c,d
d,e
e,f
f,g
g,h
h) = ((a
a,b
b),(c
c,d
d),(e
e,f
f),(g
g,h
h))

to8 :: ((a,b),(c,d),(e,f),(g,h)) -> (a,b,c,d,e,f,g,h)
to8 :: forall a b c d e f g h.
((a, b), (c, d), (e, f), (g, h)) -> (a, b, c, d, e, f, g, h)
to8 ((a
a,b
b),(c
c,d
d),(e
e,f
f),(g
g,h
h)) = (a
a,b
b,c
c,d
d,e
e,f
f,g
g,h
h)

instance ( SqlSelect a ra
         , SqlSelect b rb
         , SqlSelect c rc
         , SqlSelect d rd
         , SqlSelect e re
         , SqlSelect f rf
         , SqlSelect g rg
         , SqlSelect h rh
         , SqlSelect i ri
         ) => SqlSelect (a, b, c, d, e, f, g, h, i) (ra, rb, rc, rd, re, rf, rg, rh, ri) where
  sqlSelectCols :: IdentInfo
-> (a, b, c, d, e, f, g, h, i) -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc (a
a, b
b, c
c, d
d, e
e, f
f, g
g, h
h, i
i) =
    forall a. Monoid a => [(Builder, a)] -> (Builder, a)
uncommas'
      [ forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc a
a
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc b
b
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc c
c
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc d
d
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc e
e
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc f
f
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc g
g
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc h
h
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc i
i
      ]
  sqlSelectColCount :: Proxy (a, b, c, d, e, f, g, h, i) -> Int
sqlSelectColCount   = forall a r. SqlSelect a r => Proxy a -> Int
sqlSelectColCount forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a b c d e f g h i.
Proxy (a, b, c, d, e, f, g, h, i)
-> Proxy ((a, b), (c, d), (e, f), (g, h), i)
from9P
  sqlSelectProcessRow :: [PersistValue] -> Either Text (ra, rb, rc, rd, re, rf, rg, rh, ri)
sqlSelectProcessRow = forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap forall a b c d e f g h i.
((a, b), (c, d), (e, f), (g, h), i) -> (a, b, c, d, e, f, g, h, i)
to9 forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a r. SqlSelect a r => [PersistValue] -> Either Text r
sqlSelectProcessRow

from9P :: Proxy (a,b,c,d,e,f,g,h,i) -> Proxy ((a,b),(c,d),(e,f),(g,h),i)
from9P :: forall a b c d e f g h i.
Proxy (a, b, c, d, e, f, g, h, i)
-> Proxy ((a, b), (c, d), (e, f), (g, h), i)
from9P = forall a b. a -> b -> a
const forall {k} (t :: k). Proxy t
Proxy

from9 :: (a,b,c,d,e,f,g,h,i) -> ((a,b),(c,d),(e,f),(g,h),i)
from9 :: forall a b c d e f g h i.
(a, b, c, d, e, f, g, h, i) -> ((a, b), (c, d), (e, f), (g, h), i)
from9 (a
a,b
b,c
c,d
d,e
e,f
f,g
g,h
h,i
i) = ((a
a,b
b),(c
c,d
d),(e
e,f
f),(g
g,h
h),i
i)

to9 :: ((a,b),(c,d),(e,f),(g,h),i) -> (a,b,c,d,e,f,g,h,i)
to9 :: forall a b c d e f g h i.
((a, b), (c, d), (e, f), (g, h), i) -> (a, b, c, d, e, f, g, h, i)
to9 ((a
a,b
b),(c
c,d
d),(e
e,f
f),(g
g,h
h),i
i) = (a
a,b
b,c
c,d
d,e
e,f
f,g
g,h
h,i
i)

instance ( SqlSelect a ra
         , SqlSelect b rb
         , SqlSelect c rc
         , SqlSelect d rd
         , SqlSelect e re
         , SqlSelect f rf
         , SqlSelect g rg
         , SqlSelect h rh
         , SqlSelect i ri
         , SqlSelect j rj
         ) => SqlSelect (a, b, c, d, e, f, g, h, i, j) (ra, rb, rc, rd, re, rf, rg, rh, ri, rj) where
  sqlSelectCols :: IdentInfo
-> (a, b, c, d, e, f, g, h, i, j) -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc (a
a, b
b, c
c, d
d, e
e, f
f, g
g, h
h, i
i, j
j) =
    forall a. Monoid a => [(Builder, a)] -> (Builder, a)
uncommas'
      [ forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc a
a
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc b
b
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc c
c
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc d
d
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc e
e
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc f
f
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc g
g
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc h
h
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc i
i
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc j
j
      ]
  sqlSelectColCount :: Proxy (a, b, c, d, e, f, g, h, i, j) -> Int
sqlSelectColCount   = forall a r. SqlSelect a r => Proxy a -> Int
sqlSelectColCount forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a b c d e f g h i j.
Proxy (a, b, c, d, e, f, g, h, i, j)
-> Proxy ((a, b), (c, d), (e, f), (g, h), (i, j))
from10P
  sqlSelectProcessRow :: [PersistValue]
-> Either Text (ra, rb, rc, rd, re, rf, rg, rh, ri, rj)
sqlSelectProcessRow = forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap forall a b c d e f g h i j.
((a, b), (c, d), (e, f), (g, h), (i, j))
-> (a, b, c, d, e, f, g, h, i, j)
to10 forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a r. SqlSelect a r => [PersistValue] -> Either Text r
sqlSelectProcessRow

from10P :: Proxy (a,b,c,d,e,f,g,h,i,j) -> Proxy ((a,b),(c,d),(e,f),(g,h),(i,j))
from10P :: forall a b c d e f g h i j.
Proxy (a, b, c, d, e, f, g, h, i, j)
-> Proxy ((a, b), (c, d), (e, f), (g, h), (i, j))
from10P = forall a b. a -> b -> a
const forall {k} (t :: k). Proxy t
Proxy

from10 :: (a,b,c,d,e,f,g,h,i,j) -> ((a,b),(c,d),(e,f),(g,h),(i,j))
from10 :: forall a b c d e f g h i j.
(a, b, c, d, e, f, g, h, i, j)
-> ((a, b), (c, d), (e, f), (g, h), (i, j))
from10 (a
a,b
b,c
c,d
d,e
e,f
f,g
g,h
h,i
i,j
j) = ((a
a,b
b),(c
c,d
d),(e
e,f
f),(g
g,h
h),(i
i,j
j))

to10 :: ((a,b),(c,d),(e,f),(g,h),(i,j)) -> (a,b,c,d,e,f,g,h,i,j)
to10 :: forall a b c d e f g h i j.
((a, b), (c, d), (e, f), (g, h), (i, j))
-> (a, b, c, d, e, f, g, h, i, j)
to10 ((a
a,b
b),(c
c,d
d),(e
e,f
f),(g
g,h
h),(i
i,j
j)) = (a
a,b
b,c
c,d
d,e
e,f
f,g
g,h
h,i
i,j
j)

instance ( SqlSelect a ra
         , SqlSelect b rb
         , SqlSelect c rc
         , SqlSelect d rd
         , SqlSelect e re
         , SqlSelect f rf
         , SqlSelect g rg
         , SqlSelect h rh
         , SqlSelect i ri
         , SqlSelect j rj
         , SqlSelect k rk
         ) => SqlSelect (a, b, c, d, e, f, g, h, i, j, k) (ra, rb, rc, rd, re, rf, rg, rh, ri, rj, rk) where
  sqlSelectCols :: IdentInfo
-> (a, b, c, d, e, f, g, h, i, j, k) -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc (a
a, b
b, c
c, d
d, e
e, f
f, g
g, h
h, i
i, j
j, k
k) =
    forall a. Monoid a => [(Builder, a)] -> (Builder, a)
uncommas'
      [ forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc a
a
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc b
b
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc c
c
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc d
d
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc e
e
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc f
f
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc g
g
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc h
h
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc i
i
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc j
j
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc k
k
      ]
  sqlSelectColCount :: Proxy (a, b, c, d, e, f, g, h, i, j, k) -> Int
sqlSelectColCount   = forall a r. SqlSelect a r => Proxy a -> Int
sqlSelectColCount forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a b c d e f g h i j k.
Proxy (a, b, c, d, e, f, g, h, i, j, k)
-> Proxy ((a, b), (c, d), (e, f), (g, h), (i, j), k)
from11P
  sqlSelectProcessRow :: [PersistValue]
-> Either Text (ra, rb, rc, rd, re, rf, rg, rh, ri, rj, rk)
sqlSelectProcessRow = forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap forall a b c d e f g h i j k.
((a, b), (c, d), (e, f), (g, h), (i, j), k)
-> (a, b, c, d, e, f, g, h, i, j, k)
to11 forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a r. SqlSelect a r => [PersistValue] -> Either Text r
sqlSelectProcessRow

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)
from11P :: forall a b c d e f g h i j k.
Proxy (a, b, c, d, e, f, g, h, i, j, k)
-> Proxy ((a, b), (c, d), (e, f), (g, h), (i, j), k)
from11P = forall a b. a -> b -> a
const forall {k} (t :: k). Proxy t
Proxy

from11 :: (a,b,c,d,e,f,g,h,i,j,k) -> ((a,b),(c,d),(e,f),(g,h),(i,j),k)
from11 :: forall a b c d e f g h i j k.
(a, b, c, d, e, f, g, h, i, j, k)
-> ((a, b), (c, d), (e, f), (g, h), (i, j), k)
from11 (a
a,b
b,c
c,d
d,e
e,f
f,g
g,h
h,i
i,j
j,k
k) = ((a
a,b
b),(c
c,d
d),(e
e,f
f),(g
g,h
h),(i
i,j
j),k
k)

to11 :: ((a,b),(c,d),(e,f),(g,h),(i,j),k) -> (a,b,c,d,e,f,g,h,i,j,k)
to11 :: forall a b c d e f g h i j k.
((a, b), (c, d), (e, f), (g, h), (i, j), k)
-> (a, b, c, d, e, f, g, h, i, j, k)
to11 ((a
a,b
b),(c
c,d
d),(e
e,f
f),(g
g,h
h),(i
i,j
j),k
k) = (a
a,b
b,c
c,d
d,e
e,f
f,g
g,h
h,i
i,j
j,k
k)

instance ( SqlSelect a ra
         , SqlSelect b rb
         , SqlSelect c rc
         , SqlSelect d rd
         , SqlSelect e re
         , SqlSelect f rf
         , SqlSelect g rg
         , SqlSelect h rh
         , SqlSelect i ri
         , SqlSelect j rj
         , SqlSelect k rk
         , SqlSelect l rl
         ) => 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) where
  sqlSelectCols :: IdentInfo
-> (a, b, c, d, e, f, g, h, i, j, k, l)
-> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc (a
a, b
b, c
c, d
d, e
e, f
f, g
g, h
h, i
i, j
j, k
k, l
l) =
    forall a. Monoid a => [(Builder, a)] -> (Builder, a)
uncommas'
      [ forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc a
a
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc b
b
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc c
c
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc d
d
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc e
e
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc f
f
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc g
g
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc h
h
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc i
i
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc j
j
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc k
k
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc l
l
      ]
  sqlSelectColCount :: Proxy (a, b, c, d, e, f, g, h, i, j, k, l) -> Int
sqlSelectColCount   = forall a r. SqlSelect a r => Proxy a -> Int
sqlSelectColCount forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall 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)
-> Proxy ((a, b), (c, d), (e, f), (g, h), (i, j), (k, l))
from12P
  sqlSelectProcessRow :: [PersistValue]
-> Either Text (ra, rb, rc, rd, re, rf, rg, rh, ri, rj, rk, rl)
sqlSelectProcessRow = forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap forall a b c d e f g h i j k l.
((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 forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a r. SqlSelect a r => [PersistValue] -> Either Text r
sqlSelectProcessRow

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))
from12P :: forall 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)
-> Proxy ((a, b), (c, d), (e, f), (g, h), (i, j), (k, l))
from12P = forall a b. a -> b -> a
const forall {k} (t :: k). Proxy t
Proxy

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))
from12 :: forall a b c d e f g h i j k l.
(a, b, c, d, e, f, g, h, i, j, k, l)
-> ((a, b), (c, d), (e, f), (g, h), (i, j), (k, l))
from12 (a
a,b
b,c
c,d
d,e
e,f
f,g
g,h
h,i
i,j
j,k
k,l
l) = ((a
a,b
b),(c
c,d
d),(e
e,f
f),(g
g,h
h),(i
i,j
j),(k
k,l
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)
to12 :: forall a b c d e f g h i j k l.
((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
a,b
b),(c
c,d
d),(e
e,f
f),(g
g,h
h),(i
i,j
j),(k
k,l
l)) = (a
a,b
b,c
c,d
d,e
e,f
f,g
g,h
h,i
i,j
j,k
k,l
l)

instance ( SqlSelect a ra
         , SqlSelect b rb
         , SqlSelect c rc
         , SqlSelect d rd
         , SqlSelect e re
         , SqlSelect f rf
         , SqlSelect g rg
         , SqlSelect h rh
         , SqlSelect i ri
         , SqlSelect j rj
         , SqlSelect k rk
         , SqlSelect l rl
         , SqlSelect m rm
         ) => 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) where
  sqlSelectCols :: IdentInfo
-> (a, b, c, d, e, f, g, h, i, j, k, l, m)
-> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc (a
a, b
b, c
c, d
d, e
e, f
f, g
g, h
h, i
i, j
j, k
k, l
l, m
m) =
    forall a. Monoid a => [(Builder, a)] -> (Builder, a)
uncommas'
      [ forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc a
a
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc b
b
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc c
c
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc d
d
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc e
e
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc f
f
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc g
g
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc h
h
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc i
i
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc j
j
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc k
k
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc l
l
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc m
m
      ]
  sqlSelectColCount :: Proxy (a, b, c, d, e, f, g, h, i, j, k, l, m) -> Int
sqlSelectColCount   = forall a r. SqlSelect a r => Proxy a -> Int
sqlSelectColCount forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall 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)
-> Proxy ((a, b), (c, d), (e, f), (g, h), (i, j), (k, l), m)
from13P
  sqlSelectProcessRow :: [PersistValue]
-> Either Text (ra, rb, rc, rd, re, rf, rg, rh, ri, rj, rk, rl, rm)
sqlSelectProcessRow = forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap forall 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)
-> (a, b, c, d, e, f, g, h, i, j, k, l, m)
to13 forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a r. SqlSelect a r => [PersistValue] -> Either Text r
sqlSelectProcessRow

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)
from13P :: forall 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)
-> Proxy ((a, b), (c, d), (e, f), (g, h), (i, j), (k, l), m)
from13P = forall a b. a -> b -> a
const forall {k} (t :: k). Proxy t
Proxy

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)
from13 :: forall 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)
-> ((a, b), (c, d), (e, f), (g, h), (i, j), (k, l), m)
from13 (a
a,b
b,c
c,d
d,e
e,f
f,g
g,h
h,i
i,j
j,k
k,l
l,m
m) = ((a
a,b
b),(c
c,d
d),(e
e,f
f),(g
g,h
h),(i
i,j
j),(k
k,l
l),m
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)
to13 :: forall 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)
-> (a, b, c, d, e, f, g, h, i, j, k, l, m)
to13 ((a
a,b
b),(c
c,d
d),(e
e,f
f),(g
g,h
h),(i
i,j
j),(k
k,l
l),m
m) = (a
a,b
b,c
c,d
d,e
e,f
f,g
g,h
h,i
i,j
j,k
k,l
l,m
m)

instance ( SqlSelect a ra
         , SqlSelect b rb
         , SqlSelect c rc
         , SqlSelect d rd
         , SqlSelect e re
         , SqlSelect f rf
         , SqlSelect g rg
         , SqlSelect h rh
         , SqlSelect i ri
         , SqlSelect j rj
         , SqlSelect k rk
         , SqlSelect l rl
         , SqlSelect m rm
         , SqlSelect n rn
         ) => 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) where
  sqlSelectCols :: IdentInfo
-> (a, b, c, d, e, f, g, h, i, j, k, l, m, n)
-> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc (a
a, b
b, c
c, d
d, e
e, f
f, g
g, h
h, i
i, j
j, k
k, l
l, m
m, n
n) =
    forall a. Monoid a => [(Builder, a)] -> (Builder, a)
uncommas'
      [ forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc a
a
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc b
b
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc c
c
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc d
d
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc e
e
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc f
f
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc g
g
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc h
h
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc i
i
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc j
j
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc k
k
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc l
l
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc m
m
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc n
n
      ]
  sqlSelectColCount :: Proxy (a, b, c, d, e, f, g, h, i, j, k, l, m, n) -> Int
sqlSelectColCount   = forall a r. SqlSelect a r => Proxy a -> Int
sqlSelectColCount forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall 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)
-> Proxy ((a, b), (c, d), (e, f), (g, h), (i, j), (k, l), (m, n))
from14P
  sqlSelectProcessRow :: [PersistValue]
-> Either
     Text (ra, rb, rc, rd, re, rf, rg, rh, ri, rj, rk, rl, rm, rn)
sqlSelectProcessRow = forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap forall 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))
-> (a, b, c, d, e, f, g, h, i, j, k, l, m, n)
to14 forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a r. SqlSelect a r => [PersistValue] -> Either Text r
sqlSelectProcessRow

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))
from14P :: forall 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)
-> Proxy ((a, b), (c, d), (e, f), (g, h), (i, j), (k, l), (m, n))
from14P = forall a b. a -> b -> a
const forall {k} (t :: k). Proxy t
Proxy

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))
from14 :: forall 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)
-> ((a, b), (c, d), (e, f), (g, h), (i, j), (k, l), (m, n))
from14 (a
a,b
b,c
c,d
d,e
e,f
f,g
g,h
h,i
i,j
j,k
k,l
l,m
m,n
n) = ((a
a,b
b),(c
c,d
d),(e
e,f
f),(g
g,h
h),(i
i,j
j),(k
k,l
l),(m
m,n
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)
to14 :: forall 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))
-> (a, b, c, d, e, f, g, h, i, j, k, l, m, n)
to14 ((a
a,b
b),(c
c,d
d),(e
e,f
f),(g
g,h
h),(i
i,j
j),(k
k,l
l),(m
m,n
n)) = (a
a,b
b,c
c,d
d,e
e,f
f,g
g,h
h,i
i,j
j,k
k,l
l,m
m,n
n)

instance ( SqlSelect a ra
         , SqlSelect b rb
         , SqlSelect c rc
         , SqlSelect d rd
         , SqlSelect e re
         , SqlSelect f rf
         , SqlSelect g rg
         , SqlSelect h rh
         , SqlSelect i ri
         , SqlSelect j rj
         , SqlSelect k rk
         , SqlSelect l rl
         , SqlSelect m rm
         , SqlSelect n rn
         , SqlSelect o ro
         ) => 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) where
  sqlSelectCols :: IdentInfo
-> (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o)
-> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc (a
a, b
b, c
c, d
d, e
e, f
f, g
g, h
h, i
i, j
j, k
k, l
l, m
m, n
n, o
o) =
    forall a. Monoid a => [(Builder, a)] -> (Builder, a)
uncommas'
      [ forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc a
a
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc b
b
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc c
c
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc d
d
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc e
e
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc f
f
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc g
g
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc h
h
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc i
i
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc j
j
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc k
k
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc l
l
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc m
m
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc n
n
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc o
o
      ]
  sqlSelectColCount :: Proxy (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) -> Int
sqlSelectColCount   = forall a r. SqlSelect a r => Proxy a -> Int
sqlSelectColCount forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall 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)
-> Proxy
     ((a, b), (c, d), (e, f), (g, h), (i, j), (k, l), (m, n), o)
from15P
  sqlSelectProcessRow :: [PersistValue]
-> Either
     Text (ra, rb, rc, rd, re, rf, rg, rh, ri, rj, rk, rl, rm, rn, ro)
sqlSelectProcessRow = forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap forall 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)
-> (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o)
to15 forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a r. SqlSelect a r => [PersistValue] -> Either Text r
sqlSelectProcessRow

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)
from15P :: forall 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)
-> Proxy
     ((a, b), (c, d), (e, f), (g, h), (i, j), (k, l), (m, n), o)
from15P = forall a b. a -> b -> a
const forall {k} (t :: k). Proxy t
Proxy

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)
from15 :: forall 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)
-> ((a, b), (c, d), (e, f), (g, h), (i, j), (k, l), (m, n), o)
from15 (a
a,b
b,c
c,d
d,e
e,f
f,g
g,h
h,i
i,j
j,k
k,l
l,m
m,n
n,o
o) = ((a
a,b
b),(c
c,d
d),(e
e,f
f),(g
g,h
h),(i
i,j
j),(k
k,l
l),(m
m,n
n),o
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)
to15 :: forall 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)
-> (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o)
to15 ((a
a,b
b),(c
c,d
d),(e
e,f
f),(g
g,h
h),(i
i,j
j),(k
k,l
l),(m
m,n
n),o
o) = (a
a,b
b,c
c,d
d,e
e,f
f,g
g,h
h,i
i,j
j,k
k,l
l,m
m,n
n,o
o)

instance ( SqlSelect a ra
         , SqlSelect b rb
         , SqlSelect c rc
         , SqlSelect d rd
         , SqlSelect e re
         , SqlSelect f rf
         , SqlSelect g rg
         , SqlSelect h rh
         , SqlSelect i ri
         , SqlSelect j rj
         , SqlSelect k rk
         , SqlSelect l rl
         , SqlSelect m rm
         , SqlSelect n rn
         , SqlSelect o ro
         , SqlSelect p rp
         ) => 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) where
  sqlSelectCols :: IdentInfo
-> (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p)
-> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc (a
a, b
b, c
c, d
d, e
e, f
f, g
g, h
h, i
i, j
j, k
k, l
l, m
m, n
n, o
o, p
p) =
    forall a. Monoid a => [(Builder, a)] -> (Builder, a)
uncommas'
      [ forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc a
a
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc b
b
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc c
c
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc d
d
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc e
e
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc f
f
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc g
g
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc h
h
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc i
i
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc j
j
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc k
k
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc l
l
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc m
m
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc n
n
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc o
o
      , forall a r.
SqlSelect a r =>
IdentInfo -> a -> (Builder, [PersistValue])
sqlSelectCols IdentInfo
esc p
p
      ]
  sqlSelectColCount :: Proxy (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) -> Int
sqlSelectColCount   = forall a r. SqlSelect a r => Proxy a -> Int
sqlSelectColCount forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall 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)
-> Proxy
     ((a, b), (c, d), (e, f), (g, h), (i, j), (k, l), (m, n), (o, p))
from16P
  sqlSelectProcessRow :: [PersistValue]
-> Either
     Text
     (ra, rb, rc, rd, re, rf, rg, rh, ri, rj, rk, rl, rm, rn, ro, rp)
sqlSelectProcessRow = forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap forall 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))
-> (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p)
to16 forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a r. SqlSelect a r => [PersistValue] -> Either Text r
sqlSelectProcessRow

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))
from16P :: forall 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)
-> Proxy
     ((a, b), (c, d), (e, f), (g, h), (i, j), (k, l), (m, n), (o, p))
from16P = forall a b. a -> b -> a
const forall {k} (t :: k). Proxy t
Proxy

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))
from16 :: forall 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)
-> ((a, b), (c, d), (e, f), (g, h), (i, j), (k, l), (m, n), (o, p))
from16 (a
a,b
b,c
c,d
d,e
e,f
f,g
g,h
h,i
i,j
j,k
k,l
l,m
m,n
n,o
o,p
p) = ((a
a,b
b),(c
c,d
d),(e
e,f
f),(g
g,h
h),(i
i,j
j),(k
k,l
l),(m
m,n
n),(o
o,p
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)
to16 :: forall 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))
-> (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p)
to16 ((a
a,b
b),(c
c,d
d),(e
e,f
f),(g
g,h
h),(i
i,j
j),(k
k,l
l),(m
m,n
n),(o
o,p
p)) = (a
a,b
b,c
c,d
d,e
e,f
f,g
g,h
h,i
i,j
j,k
k,l
l,m
m,n
n,o
o,p
p)

-- | Insert a 'PersistField' for every selected value.
--
-- @since 2.4.2
insertSelect
    :: (MonadIO m, PersistEntity a, SqlBackendCanWrite backend)
    => SqlQuery (SqlExpr (Insertion a))
    -> R.ReaderT backend m ()
insertSelect :: forall (m :: * -> *) a backend.
(MonadIO m, PersistEntity a, SqlBackendCanWrite backend) =>
SqlQuery (SqlExpr (Insertion a)) -> ReaderT backend m ()
insertSelect SqlQuery (SqlExpr (Insertion a))
a = forall (f :: * -> *) a. Functor f => f a -> f ()
void forall a b. (a -> b) -> a -> b
$ forall (m :: * -> *) a backend.
(MonadIO m, PersistEntity a, SqlBackendCanWrite backend) =>
SqlQuery (SqlExpr (Insertion a)) -> ReaderT backend m Int64
insertSelectCount SqlQuery (SqlExpr (Insertion a))
a

-- | Insert a 'PersistField' for every selected value, return the count afterward
insertSelectCount
    :: (MonadIO m, PersistEntity a, SqlBackendCanWrite backend)
    => SqlQuery (SqlExpr (Insertion a))
    -> R.ReaderT backend m Int64
insertSelectCount :: forall (m :: * -> *) a backend.
(MonadIO m, PersistEntity a, SqlBackendCanWrite backend) =>
SqlQuery (SqlExpr (Insertion a)) -> ReaderT backend m Int64
insertSelectCount SqlQuery (SqlExpr (Insertion a))
a = forall (m :: * -> *) a r backend.
(MonadIO m, SqlSelect a r, BackendCompatible SqlBackend backend) =>
Mode -> SqlQuery a -> ReaderT backend m Int64
rawEsqueleto Mode
INSERT_INTO SqlQuery (SqlExpr (Insertion a))
a

-- | Renders an expression into 'Text'. Only useful for creating a textual
-- representation of the clauses passed to an "On" clause.
--
-- @since 3.2.0
renderExpr :: SqlBackend -> SqlExpr (Value Bool) -> T.Text
renderExpr :: SqlBackend -> SqlExpr (Value Bool) -> Text
renderExpr SqlBackend
sqlBackend SqlExpr (Value Bool)
e = case SqlExpr (Value Bool)
e of
    ERaw SqlExprMeta
_ NeedParens -> IdentInfo -> (Builder, [PersistValue])
mkBuilderValues ->
         let (Builder
builder, [PersistValue]
_) = NeedParens -> IdentInfo -> (Builder, [PersistValue])
mkBuilderValues NeedParens
Never (SqlBackend
sqlBackend, IdentState
initialIdentState)
         in (Builder -> Text
builderToText Builder
builder)

-- | An exception thrown by 'RenderExpr' - it's not designed to handle composite
-- keys, and will blow up if you give it one.
--
-- @since 3.2.0
data RenderExprException = RenderExprUnexpectedECompositeKey T.Text
    deriving Int -> RenderExprException -> ShowS
[RenderExprException] -> ShowS
RenderExprException -> String
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [RenderExprException] -> ShowS
$cshowList :: [RenderExprException] -> ShowS
show :: RenderExprException -> String
$cshow :: RenderExprException -> String
showsPrec :: Int -> RenderExprException -> ShowS
$cshowsPrec :: Int -> RenderExprException -> ShowS
Show

-- |
--
-- @since 3.2.0
instance Exception RenderExprException

-- | @valkey i = 'val' . 'toSqlKey'@
-- (<https://github.com/prowdsponsor/esqueleto/issues/9>).
valkey
    :: (ToBackendKey SqlBackend entity, PersistField (Key entity))
    => Int64 -> SqlExpr (Value (Key entity))
valkey :: forall entity.
(ToBackendKey SqlBackend entity, PersistField (Key entity)) =>
Int64 -> SqlExpr (Value (Key entity))
valkey = forall typ. PersistField typ => typ -> SqlExpr (Value typ)
val forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall record.
ToBackendKey SqlBackend record =>
Int64 -> Key record
toSqlKey

-- | @valJ@ is like @val@ but for something that is already a @Value@. The use
-- case it was written for was, given a @Value@ lift the @Key@ for that @Value@
-- into the query expression in a type safe way. However, the implementation is
-- more generic than that so we call it @valJ@.
--
-- 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
-- (<https://github.com/prowdsponsor/esqueleto/pull/69>).
--
-- @since 1.4.2
valJ
    :: (PersistField (Key entity))
    => Value (Key entity)
    -> SqlExpr (Value (Key entity))
valJ :: forall entity.
PersistField (Key entity) =>
Value (Key entity) -> SqlExpr (Value (Key entity))
valJ = forall typ. PersistField typ => typ -> SqlExpr (Value typ)
val forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a. Value a -> a
unValue


-- | Synonym for 'Database.Persist.Store.delete' that does not
-- clash with @esqueleto@'s 'delete'.
deleteKey
    ::
    ( PersistStore backend
    , BaseBackend backend ~ PersistEntityBackend val
    , MonadIO m
    , PersistEntity val
    )
    => Key val
    -> R.ReaderT backend m ()
deleteKey :: forall backend val (m :: * -> *).
(PersistStore backend,
 BaseBackend backend ~ PersistEntityBackend val, MonadIO m,
 PersistEntity val) =>
Key val -> ReaderT backend m ()
deleteKey = forall backend record (m :: * -> *).
(PersistStoreWrite backend, MonadIO m,
 PersistRecordBackend record backend) =>
Key record -> ReaderT backend m ()
Database.Persist.delete

-- | Avoid N+1 queries and join entities into a map structure.
--
-- This function is useful to call on the result of a single @JOIN@. For
-- example, suppose you have this query:
--
-- @
-- getFoosAndNestedBarsFromParent
--     :: ParentId
--     -> SqlPersistT IO [(Entity Foo, Maybe (Entity Bar))]
-- getFoosAndNestedBarsFromParent parentId =
--     'select' $ do
--         (foo :& bar) <- from $
--             table @Foo
--             ``LeftOuterJoin``
--             table @Bar
--                 ``on`` do
--                     \\(foo :& bar) ->
--                         foo ^. FooId ==. bar ?. BarFooId
--         where_ $
--             foo ^. FooParentId ==. val parentId
--         pure (foo, bar)
-- @
--
-- This is a natural result type for SQL - a list of tuples. However, it's not
-- what we usually want in Haskell - each @Foo@ in the list will be represented
-- multiple times, once for each @Bar@.
--
-- We can write @'fmap' 'associateJoin'@ and it will translate it into a 'Map'
-- that is keyed on the 'Key' of the left 'Entity', and the value is a tuple of
-- the entity's value as well as the list of each coresponding entity.
--
-- @
-- getFoosAndNestedBarsFromParentHaskellese
--     :: ParentId
--     -> SqlPersistT (Map (Key Foo) (Foo, [Maybe (Entity Bar)]))
-- getFoosAndNestedBarsFromParentHaskellese parentId =
--     'fmap' 'associateJoin' $ getFoosdAndNestedBarsFromParent parentId
-- @
--
-- What if you have multiple joins?
--
-- Let's use 'associateJoin' with a *two* join query.
--
-- @
-- userPostComments
--     :: SqlQuery (SqlExpr (Entity User, Entity Post, Entity Comment))
-- userPostsComment = do
--     (u :& p :& c) <- from $
--         table @User
--         ``InnerJoin``
--         table @Post
--             `on` do
--                 \\(u :& p) ->
--                     u ^. UserId ==. p ^. PostUserId
--         ``InnerJoin``
--         table @Comment
--             ``on`` do
--                 \\(_ :& p :& c) ->
--                     p ^. PostId ==. c ^. CommentPostId
--     pure (u, p, c)
-- @
--
-- 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.
--
-- @
-- nest :: (a, b, c) -> (a, (b, c))
-- nest (a, b, c) = (a, (b, c))
-- @
--
-- This makes the return of the query conform to the input expected from
-- 'associateJoin'.
--
-- @
-- nestedUserPostComments
--     :: SqlPersistT IO [(Entity User, (Entity Post, Entity Comment))]
-- nestedUserPostComments =
--     fmap nest $ select userPostsComments
-- @
--
-- Now, we can call 'associateJoin' on it.
--
-- @
-- associateUsers
--     :: [(Entity User, (Entity Post, Entity Comment))]
--     -> Map UserId (User, [(Entity Post, Entity Comment)])
-- associateUsers =
--     associateJoin
-- @
--
-- Next, we'll use the 'Functor' instances for 'Map' and tuple to call
-- 'associateJoin' on the @[(Entity Post, Entity Comment)]@.
--
-- @
-- associatePostsAndComments
--     :: Map UserId (User, [(Entity Post, Entity Comment)])
--     -> Map UserId (User, Map PostId (Post, [Entity Comment]))
-- associatePostsAndComments =
--     fmap (fmap associateJoin)
-- @
--
-- For more reading on this topic, see
-- <https://www.foxhound.systems/blog/grouping-query-results-haskell/ this Foxhound Systems blog post>.
--
-- @since 3.1.2
associateJoin
    :: forall e1 e0.  Ord (Key e0)
    => [(Entity e0, e1)]
    -> Map.Map (Key e0) (e0, [e1])
associateJoin :: forall e1 e0.
Ord (Key e0) =>
[(Entity e0, e1)] -> Map (Key e0) (e0, [e1])
associateJoin = forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr forall {a} {a}.
Ord (Key a) =>
(Entity a, a) -> Map (Key a) (a, [a]) -> Map (Key a) (a, [a])
f forall {k} {a}. Map k a
start
  where
    start :: Map k a
start = forall {k} {a}. Map k a
Map.empty
    f :: (Entity a, a) -> Map (Key a) (a, [a]) -> Map (Key a) (a, [a])
f (Entity a
one, a
many) =
        forall k a. Ord k => (a -> a -> a) -> k -> a -> Map k a -> Map k a
Map.insertWith
            (\(a
oneOld, [a]
manyOld) (a
_, [a]
manyNew) -> (a
oneOld, [a]
manyNew forall a. [a] -> [a] -> [a]
++ [a]
manyOld ))
            (forall record. Entity record -> Key record
entityKey Entity a
one)
            (forall record. Entity record -> record
entityVal Entity a
one, [a
many])