emg184
emg184

Reputation: 1010

How to Dynamically assemble SQL queries with haskell based on route parameters

I've got a scotty web app that I am trying to implement a dynamic search interface over and keep hitting a wall on how I should implement it. The Basic premise is the following:

Given a list of URL parameters: let params = [Param]

where param: type Param = (Text, Text)

I would like to be able to

Lets say I have a table in my database where:

Users
| user_id | username | email | first_name | last_name | created_at |
|---------|----------|-------|------------|-----------|------------|
|   Int   |  Text    | Text  |  Text      | Text      | timestamp  |

My base SQL query might look like this:

baseQuery :: Query
baseQuery :: [sql| SELECT user_id, username, email, first_name, last_name, created_at FROM users |]

In the case of receiving url parameters I would want to be able to apply them to the WHERE clause, ORDER BY clause, etc.

What would be the best strategy to transform the following url:

arbitraryhost:/users?order_by_max=user_id&first_name=emg184&last_name=stackoverflow&limit=20

which would result in the following parameters list:

let params = [("order_by_max","user_id"), ("first_name","emg184"), ("last_name","stackoverflow"), ("limit", "20")]

How would i generate the follwing query:

"SELECT user_id, username, email, first_name, last_name, created_at 
FROM users
WHERE first_name = ? AND last_name = ?
ORDER BY user_id
LIMIT ?"

("emg184", "stackoverflow", 20)

(I really like the way that the query builder knexjs works which allows for ad hoc fragments of queries to be generated and applied as a higher order function to some base query http://knexjs.org/)

Im wondering what a strategy or implementation of this might be as I have not been successful in building anything that I find to be very fitting for this.

Upvotes: 1

Views: 195

Answers (0)

Related Questions