scala - Slick Plain SQL Query with Dynamic Conditions -
i'm struggling on appending additional conditions query. in simplest form, need below:
def findpeople(name: string, maybesurname: option[string]) = { val sql1 = sql"select * my_table name = $name" val sql2 = maybesurname.map( surname => sql"and col2 = $surname" ).getorelse(sql"") val finalsql = sql1 + sql2 // need kind of feature ... ... }
using #$ option, surname wouldn't bind variable, big issue.
here sample test on slick 3.1.x
import slick.jdbc.{sqlactionbuilder, setparameter, positionedparameters} object slickkit { implicit class sqlactionbuilderconcat (a: sqlactionbuilder) { def concat (b: sqlactionbuilder): sqlactionbuilder = { sqlactionbuilder(a.queryparts ++ b.queryparts, new setparameter[unit] { def apply(p: unit, pp: positionedparameters): unit = { a.unitpconv.apply(p, pp) b.unitpconv.apply(p, pp) } }) } } }
and then
import slickkit._ val sql1 = sql""" select count(*) idinfo_#$i """ val sql2 = sql""" source=$source """ val sql = sql1 concat sql2 sql.as[int].head
Comments
Post a Comment