prowdsponsor / esqueleto

Bare bones, type-safe EDSL for SQL queries on persistent backends.
http://hackage.haskell.org/package/esqueleto
BSD 3-Clause "New" or "Revised" License
178 stars 51 forks source link

naming columns? #44

Closed mwotton closed 10 years ago

mwotton commented 10 years ago

I might be doing this incorrectly, but I was wondering if there was a way to rename columns in Esqueleto so you can select from them twice in a single query.

As an example, I have some code that selects the two-component phrase ["foo", "bar"] from my db:

 select c1.id,c2.id
 from component as c1, component as c2, word_component as w1,   
 word_component as w2
 where c1.text='foo' 
   and c2.text='bar'
   and w1.component_id=c1.id 
   and w2.component_id=c2.id 
   and w1.word_id=w2.word_id 
   and w1.index=1 and w2.index=2;

Have I missed something, or is this just missing functionality?

erikd commented 10 years ago

Untested, but it should look something like this (basically just a direct translation from what you had to esqueleto):

rows <- select . from $ \(c1, c2, w1, w2) -> do
            where_ (c1 ^. ComponentText ==. val "foo"
                 &&. c2 ^. ComponentText ==. val "bar"
                 &&. w1 ^. WordComponentComponentId ==. c1 ^. ComponentId
                 &&. w2 ^. WordComponentComponentId ==. c2 ^. ComponentId
                 &&. w1 ^. WordComponentWordId ==. w2 ^. WordComponentWordId
                 &&. w1 ^. WordComponentIndex ==. val 1
                 &&. w2 ^. WordComponentIndex ==. val 2
                 )
           return (c1 ^. ComponentId, c2 ^. ComponentId)
mwotton commented 10 years ago

c2 ^. ComponentId rather than c2 ^ ComponentId, but otherwise perfect. Cheers Erik :)