I am writing some database query helper methods for my classes in Scala.
This select
method is intended to pluck certain columns from the Product table, specified as a comma-seperated list (String) of the desired columns.
I want to be able to call it like this: Product.select("id, title")
The following code does not work:
def select(columns: String) = { DB.readOnly{ implicit session =>
sql"select ${columns} from $sqlTable limit 1000".map(row => Product(row)).list.apply()
}}
But this code (for illustration purposes only) does
def select(columns: String) = { DB.readOnly{ implicit session =>
var x = sqls"id, title, description, available_online"
sql"select ${x} from $sqlTable limit 1000".map(row => Product(row)).list.apply()
}}
Now, obviously I don't want to hard code columns into the method, but i want to do this with the columns
parameter string (I hope you catch my drift). How can I apply the sqls
interpolator on the columns string?
It would be something like var x = sqls(columns)
Here you can find more info on the sqls
and sql
interpolators
Please comment if you require more information and I'd appreciate your feedback.