Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

sub_select produces invalid SQL sometimes #126

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ stack.yaml.lock
.cabal-sandbox/
cabal.sandbox.config
.hspec-failures
stack.yaml.lock
12 changes: 10 additions & 2 deletions src/Database/Esqueleto/Internal/Internal.hs
Original file line number Diff line number Diff line change
Expand Up @@ -634,11 +634,11 @@ v `notIn` e = ifNotEmptyList e True $ unsafeSqlBinOp " NOT IN " v (veryUnsafeCo
-- return person
-- @
exists :: SqlQuery () -> SqlExpr (Value Bool)
exists = unsafeSqlFunction "EXISTS " . existsHelper
exists = unsafeSqlFunctionNoParens "EXISTS " . existsHelper

-- | @NOT EXISTS@ operator.
notExists :: SqlQuery () -> SqlExpr (Value Bool)
notExists = unsafeSqlFunction "NOT EXISTS " . existsHelper
notExists = unsafeSqlFunctionNoParens "NOT EXISTS " . existsHelper

-- | @SET@ clause used on @UPDATE@s. Note that while it's not
-- a type error to use this function on a @SELECT@, it will
Expand Down Expand Up @@ -1717,6 +1717,14 @@ unsafeSqlValue v = ERaw Never $ const (v, mempty)
unsafeSqlFunction :: UnsafeSqlFunctionArgument a =>
TLB.Builder -> a -> SqlExpr (Value b)
unsafeSqlFunction name arg =
ERaw Never $ \info ->
let (argsTLB, argsVals) =
uncommas' $ map (\(ERaw _ f) -> f info) $ toArgList arg
in (name <> parens (parens argsTLB), argsVals)

unsafeSqlFunctionNoParens :: UnsafeSqlFunctionArgument a =>
TLB.Builder -> a -> SqlExpr (Value b)
unsafeSqlFunctionNoParens name arg =
ERaw Never $ \info ->
let (argsTLB, argsVals) =
uncommas' $ map (\(ERaw _ f) -> f info) $ toArgList arg
Expand Down
16 changes: 16 additions & 0 deletions test/Common/Test.hs
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,22 @@ testSelect run = do
ret <- select $ return nothing
liftIO $ ret `shouldBe` [ Value (Nothing :: Maybe Int) ]

describe "sub_select" $ do
it "works inside of sum" $ do
run $ do
ret <-
select $
pure $
sum_ $
sub_select $
from $ \foo -> do
pure (foo ^. FooName)
nonSub <-
select $
from $ \foo -> do
pure (sum_ (foo ^. FooName))

liftIO $ ret `shouldBe` (nonSub :: [Value (Maybe Int)])

testSelectSource :: Run -> Spec
testSelectSource run = do
Expand Down