module Conduit.DB.Utils where

import Data.Time (UTCTime(..), fromGregorian, secondsToDiffTime)
import Database.Esqueleto.Experimental (SqlExpr, SqlQuery, Value, where_)

-- | Temporarily sets the time to some irrelevant number for typing reasons.
--   Used for rows where the DB sets the timestamp using some trigger.
dbTimeNow :: UTCTime
dbTimeNow :: UTCTime
dbTimeNow = Day -> DiffTime -> UTCTime
UTCTime (Year -> MonthOfYear -> MonthOfYear -> Day
fromGregorian Year
1 MonthOfYear
0 MonthOfYear
0) (Year -> DiffTime
secondsToDiffTime Year
0)

-- | Shorthand for DB queries that select from a table just applying some filter
--
-- > select $ do 
-- >   e <- from table `suchThat` \e -> e.id ==. ???
-- >   ...
infixl 5 `suchThat`
suchThat :: SqlQuery a -> (a -> SqlExpr (Value Bool)) -> SqlQuery a
suchThat :: forall a. SqlQuery a -> (a -> SqlExpr (Value Bool)) -> SqlQuery a
suchThat SqlQuery a
entity a -> SqlExpr (Value Bool)
predicate = do
  a
e <- SqlQuery a
entity
  SqlExpr (Value Bool) -> SqlQuery ()
where_ (a -> SqlExpr (Value Bool)
predicate a
e)
  a -> SqlQuery a
forall a. a -> SqlQuery a
forall (f :: * -> *) a. Applicative f => a -> f a
pure a
e