Different API to combine JOINs (and queries in general)
Nobody has claimed this yet.
Assessment
- Difficulty
- 5/5
- Estimated time
- Over a week
- Newbie friendliness
- 8/100
Research direction
This is a design proposal, not a scoped task: it asks for criticism of a FromQuery wrapper around SqlQuery that defers the FROM and WHERE clauses. The proposed code uses from, innerJoin, leftJoin, where_ and runFromQuery from Database.Esqueleto.Experimental, so start by reading how SqlQuery's SideData is built there. Done would mean a maintainer-agreed API direction, which the thread has not yet reached.
Written by the indexing model from the issue text.
Description
Next to #440 , I also was fed up with how large queries with 5+ JOINs start to become super cumbersome with all the positional :& arguments and the lack of modularity. So I made something to alleviate this issue.
And just like in #440, I'm looking for either:
- criticism to improve the implementation; and/or,
- maybe give some ideas for
esqueletoto improve.
I wanted to define a query like:
SELECT * FROM user WHERE user.id = $1
and be able to compose it with moren later on, like adding on user_item and all items of the last month:
INNER JOIN user_item ON user_item.user = user.id
INNER JOIN item ON user_item.item = item.id
but when using esqueleto I can't do the following
fromUser :: Email -> SqlQuery (SqlExpr (Entity User))
fromUser email = do
user <- from $ table @User
where_ $ user.email ==. val email
pure user
fetchItemsFromUser :: Email -> SqlQuery (SqlExpr (Entity User), SqlExpr (Entity Item))
fetchItemsFromUser email = do
(user :& userItem :& item) <- from $
-- doesn't work, because it needs to be a `From`, but then it also doesn't
-- automatically include the `WHERE` clause.
fromUser email
`innerJoin` table @UserItem
`on` (\(user :& userItem) -> user.id ==. userItem.user
`innerJoin` table @Item
`on` (\(_ :& userItem :& item) -> userItem.item ==. item.id
restOfQueryThatLimitsItems item -- for example
pure (user, item)
So I made a small wrapper around SqlQuery called FromQuery (working title) to suspend the creation of the sdFromClause and the sdWhereClause in the SideData of SqlQuery. And the result can be seen at the bottom of this text, but the idea is that with that API, you can now do the following:
fromUser :: Email -> FromQuery (SqlExpr (Entity User))
fromUser email = do
user <- from $ table @User
where_ $ user.email ==. email
pure user
fromItemViaUser :: FromQuery (SqlExpr (Entity UserItem), SqlExpr (Entity Item))
fromItemViaUser user = do
userItem <- from $ table @UserItem
item <- innerJoin $ table @Item `on` \item -> userItem.item ==. item.id
pure (userItem, item)
fetchItemsFromUser :: MonadIO m => Email -> SqlPersistT m [Entity Item]
fetchItemsFromUser email = select $ do
user <- fromUser email
(userItem, item) <-
innerJoinFrom $
fromItemViaUser `on` \(userItem, _) -> userItem.user ==. user.id
pure item
-- This all instead of what it would be using the traditional 'Esqueleto' API:
--
-- And while this doesn't look too bad, imagine having a query with
-- 6-10 tables being joined and half of what you see of the query is
--
-- @(user :& _ :& _ :& _ :& product :& _ :& _ :& _ :& someOuterJoinResult)@
--
fetchItemsFromUser :: MonadIO m => Email -> SqlPersistT m [Entity Item]
fetchItemsFromUser email = select $ do
(user :& _ :& item) <- from $ table @User
`innerJoin` table @UserItem
`on` (\user :& userItem) -> user.id ==. userItem.user
`innerJoin` table @Item
`on` (\(_ :& userItem :& item) -> userItem.item ==. item.id
where_ $ user.email ==. val email
pure item
The resulting query is:
SELECT item.*
FROM user
INNER JOIN (user_item INNER JOIN item ON user_item.item = item.id)
ON user_item.user = user.id
WHERE user.email = {email}
SOME DRAWBACKS
Since everything is brought into scope immediately, whether something is NULLABLE or not can't be changed after the fact. This means that implementing a RIGHT OUTER JOIN is impossible (or at least very annoying and/or doesn't result in a nice API)
And while this makes things very modular, it might also inadvertently create less performant queries, since it's easier to accidentally create JOINs that have the parentheses in a less optimal position. (Mostly an issue with LEFT OUTER JOINs, since an all-INNER JOIN query is at least associative and maybe even commutative)
THE ACTUAL IMPLEMENTATION
{- |
Monad wrapper around 'SqlQuery' which allows for more succinct and modular
@FROM@ definitions.
These 'FromQuery's can also have accompanying @WHERE@
clauses so that specific pre-made @JOIN@s can be sure certain filters are
present when using pre-made 'FromQuery' definitions.
@
fromBookingsWithEvents ::
FromQuery (SqlExpr (Entity Booking) :& SqlExpr (Entity Event))
fromBookingsWithEvents = do
event <- from $ table \@Event
eventBooking <- innerJoin $
table \@EventBooking `on` \\eventBookings -> event.id ==. eventBooking.event
booking <- innerJoin $
table \@Booking `on` \\booking -> booking.id ==. eventBooking.booking
pure (event :& booking)
@
-}
newtype FromQuery a = FromQuery (StateT FromData SqlQuery a)
deriving newtype (Functor, Applicative, Monad)
instance ValidOnClause (FromQuery a)
-- | Run a @SELECT@ SQL query
select :: (MonadIO m, SqlSelectUnpack a r b) => FromQuery a -> SqlPersistT m [b]
select = E.select . runFromQuery
-- | Run a @SELECT@ SQL query that includes a @LIMIT 1@
selectOne :: (MonadIO m, SqlSelectUnpack a r b) => FromQuery a -> SqlPersistT m (Maybe b)
selectOne = E.selectOne . runFromQuery
{- |
Running a 'FromQuery' to create a 'SqlQuery'
This is not to be used in regular usage, the 'select' and 'selectOne' definitions
use it internally so that when trying to use this new method, there's no way
to accidentally add a 'SqlQuery' into the 'FromQuery' mix.
-}
runFromQuery :: FromQuery a -> SqlQuery a
runFromQuery (FromQuery query) = do
(a, fromData) <- query `S.runStateT` emptyFromData
let sideData =
mempty
{ sdFromClause = [FromRaw fromData.fromClause]
, sdWhereClause = fromData.whereClause
}
Q $ tell sideData
pure a
-- | Start with a table (or a join of tables) to add to the SQL query
from :: ToFrom a b => a -> FromQuery b
from f = do
(ret, fromClause) <- peekFrom f
-- Should be the first one, and used only once, so overwriting here is fine.
modify $ \fd -> fd{fromClause}
pure ret
{- |
Adds the 'a' to the current @FROM@ clause as an @INNER JOIN@
Can be used with the commonly used 'Database.Esqueleto.Experimental.on'
in the following way:
@
query = do
event <- from $ table @Event
user <- innerJoin $ table @User `on` \\user -> event.createdBy ==. user.id
@
-}
innerJoin :: ToFrom a b => (a, b -> SqlExpr (Value Bool)) -> FromQuery b
innerJoin (rhs, onClause) = do
(ret, fromClauseFn) <- peekFrom rhs
addToExistingFrom " INNER JOIN " fromClauseFn $ onClause ret
pure ret
-- | Same as 'innerJoin', but as a @LEFT OUTER JOIN@
leftJoin :: (ToFrom a b, ToMaybe b) => (a, ToMaybeT b -> SqlExpr (Value Bool)) -> FromQuery (ToMaybeT b)
leftJoin (rhs, onClause) = do
(ret, fromClauseFn) <- peekFrom rhs
let mRet = toMaybe ret
addToExistingFrom " LEFT OUTER JOIN " fromClauseFn $ onClause mRet
pure mRet
addToExistingFrom :: String -> RawFn -> SqlExpr (Value Bool) -> FromQuery ()
addToExistingFrom joinWord fromClauseFn onClause = do
currentFromClause <- FromQuery $ S.gets fromClause
-- If this can fail, we want it to fail ASAP, hence the strictness annotation
let !newFromClause =
case (currentFromClause, fromClauseFn) of
(currentFrom, newFrom) ->
fromJoin (fromString joinWord) currentFrom newFrom (Just onClause)
modify $ \fd -> fd{fromClause = newFromClause}
-- | Same as 'innerJoin', but for a pre-made 'FromQuery'
innerJoinFrom :: (FromQuery a, a -> SqlExpr (Value Bool)) -> FromQuery a
innerJoinFrom = joinFromHelper id " INNER JOIN "
-- | Same as 'innerJoinFrom' but as a @LEFT OUTER JOIN@
leftJoinFrom ::
ToMaybe a => (FromQuery a, ToMaybeT a -> SqlExpr (Value Bool)) -> FromQuery (ToMaybeT a)
leftJoinFrom = joinFromHelper toMaybe " LEFT OUTER JOIN "
joinFromHelper :: (a -> b) -> String -> (FromQuery a, b -> SqlExpr (Value Bool)) -> FromQuery b
joinFromHelper toB joinWord (fromQuery, onClause) = do
-- Save 'From/Where' up to now
beforeState <- popState
-- Process prepped query
a <- fromQuery
let b = toB a
-- Combine previous and new 'From/Where'
modify $ combineFromData (innerHelper b) beforeState
-- Provide result of prepped query for further usage
pure b
where
innerHelper a lhs rhs =
fromJoin (fromString joinWord) lhs rhs (Just $ onClause a)
----------
-- SQL FUNCTIONS
----------
-- | Add a statement to the global @WHERE@ clause
where_ :: SqlExpr (Value Bool) -> FromQuery ()
where_ stmt = do
((), sideData) <- peek $ E.where_ stmt
modify $ \fd ->
fd{whereClause = fd.whereClause <> sideData.sdWhereClause}
pure ()
{-
Most other functions for regular `SqlQuery` can be defined the following way:
{function} = liftQ . Database.Esqueleto.Experimental.{function}
Where {function} can be things like `orderBy`, `groupBy`, etc. which will just change the `SideData` immediately.
-}
------------
-- State of 'FromQuery'
------------
data FromData = FromData
{ fromClause :: RawFn
, whereClause :: WhereClause
}
combineFromData ::
(RawFn -> RawFn -> RawFn) ->
(FromData -> FromData -> FromData)
combineFromData combineFromClauses fd1 fd2 =
FromData
{ fromClause = fd1.fromClause `combineFromClauses` fd2.fromClause
, whereClause = fd1.whereClause <> fd2.whereClause
}
emptyFromData :: FromData
emptyFromData =
FromData
{ fromClause = \_ _ -> ("", [])
, whereClause = NoWhere
}
----------
-- HELPER FUNCTIONS
----------
liftQ :: SqlQuery a -> FromQuery a
liftQ = FromQuery . lift
popState :: FromQuery FromData
popState = FromQuery $ S.state (,emptyFromData)
-- "run" a query without adding it to the context
peek :: SqlQuery a -> FromQuery (a, SideData)
peek =
liftQ . Q . censor (const mempty) . listen . unQ
modify :: (FromData -> FromData) -> FromQuery ()
modify f = FromQuery $ S.modify' f
peekFrom :: ToFrom a b => a -> FromQuery (b, RawFn)
peekFrom q = do
(ret, sideData) <- peek $ E.from q
-- The 'E.from' will always set one 'FromRaw :: FromClause'
let !fromClauseFn =
case lastMay $ sdFromClause sideData of
Just (FromRaw rawFn) -> rawFn
_ -> impossible
pure (ret, fromClauseFn)
where
impossible =
error "Import.Esqueleto.Experimental: peekFrom: impossible empty 'from'"
- Dominant language
- Haskell
- Stars
- 401
- Forks
- 108
- PR merge metrics
- No merged PRs in 30d
Getting set up
- No Dockerfile or Docker Compose file
- Has a pull request template
- No contributing guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
More from bitemyapp/esqueleto
-
Difficulty 5/5 Over a week Newbie friendliness 15/100
-
Difficulty 4/5 3-5 days Newbie friendliness 64/100
-
Difficulty 4/5 3-5 days Newbie friendliness 45/100
-
Difficulty 5/5 Over a week Newbie friendliness 25/100
-
Difficulty 2/5 1-3 hours Newbie friendliness 45/100
All issues in bitemyapp/esqueleto
Similar issues
-
Difficulty 2/5 1-3 hours Newbie friendliness 72/100
haskell/bytestring#730 · 1 comment ·
-
Difficulty 2/5 1-3 hours Newbie friendliness 84/100
seal-harness/seal-harness#399 ·
Maintainers usually reply within 1 day
-
bug
Difficulty 2/5 1-3 hours Newbie friendliness 65/100
fmidue/codeworld-tasks#124 ·
-
Difficulty 2/5 1-3 hours Newbie friendliness 62/100
reflex-frp/reflex#563 ·
-
The codecov job never gets a runner on macos-26 and is cancelledPossibly taken @yegor256 claimed this 1 day ago. Openbug
Difficulty 1/5 1-3 hours Newbie friendliness 88/100
objectionary/phino#2524 · 1 comment ·
Maintainers usually reply within 1 day