haskellari / postgresql-simple

Mid-level client library for accessing PostgreSQL from Haskell
Other
85 stars 43 forks source link

Antiquotations in sql quasiquoter #68

Open akrmn opened 3 years ago

akrmn commented 3 years ago

One of the more frequent pain points I've experienced when working with postgresql-simple has been matching a Haskell n-tuple to n question marks in a [sql| ... |] quasiquotation, especially as requirements change and fields get added/removed. This would also improve readability, since one wouldn't need to constantly jump from the query to the arguments while reading through it.

With antiquotations, we'd be able to move from

foosBeforeBar :: Connection -> Foo -> Bar -> IO [(Foo, Bar)]
foosBeforeBar conn foo maxBar = 
  query conn
    [sql|
      SELECT 
        foo,
        bar
      FROM qux
      WHERE foo = ?
      AND bar < ?
    |] (foo, maxBar)

to

foosBeforeBar :: Connection -> Foo -> Bar -> IO [(Foo, Bar)]
foosBeforeBar conn foo maxBar = 
  query_ conn
    [sql_with_antiquotes|
      SELECT 
        foo,
        bar
      FROM qux
      WHERE foo = $foo
      AND bar < $maxBar
    |]

(of course, the quasiquoter could have a better name, and antiquotation need not be done with dollar signs).

I was wondering if there's an interest in adding such a feature, or if this has been tried before and there's a good reason it's a bad idea. I'd be willing to bring in the effort if there's indeed interest for it.

StefanFehrenbach commented 3 years ago

Have a look at sqlExp in https://hackage.haskell.org/package/postgresql-query-3.7.0

jmoore34 commented 2 months ago

postgresql-simple-interpolate