How to use SQL "LIKE" operator in SLICK
13,496
Solution 1
Exactly as you normally would!
val query = for {
coffee <- Coffees if coffee.name like "%expresso%"
} yield (coffee.name, coffee.price)
Will generate SQL like
SELECT name, price FROM coffees WHERE NAME like '%expresso%';
Solution 2
This is how I got it to work:
// argMap is map of type [Str, Str]
val query = for {
coffee <- coffees if (
argMap.map{ case (k,v) =>
metric.column[String](k) like s"%${v}%"
}.reduce(_ && _)
)
} yield(coffee.name)
And then you can run this using your db:
val res = db.run(query.result)
Of course res
is a future here that you need to use await to get the actual result.
Author by
wassertim
I'm a software developer and a musician. I'm interested in web and flamenco :-)
Updated on June 05, 2022Comments
-
wassertim almost 2 years
Maybe a silly question. But I have not found an answer so far. So how do you represent the SQL's "LIKE" operator in SLICK?
-
wassertim about 11 yearsThanks. Is it scala query or slick? For me in slick it only works with coffe.name.like("%expresso%") (with dot separator).
-
kiritsuku about 11 years@Tim: Your syntax is equivalent to the one Faiz presented (note the dot between
coffee
andname
). -
wassertim about 11 yearsNo it does not sschaef. Faiz's answer has no dot between name and like - so I get a compiler error. If I separate name and like with dot - no error. Why's that? Am I supposed to import some namespace?
-
Faiz about 11 yearsWell if you're using say, mysql,
import scala.slick.driver.MySQLDriver.simple._
will help. replaceMySQLDriver
with the driver of your choice. -
wassertim about 11 yearsDoes make sense. import slick.driver.ExtendedProfile works fine
-
Travis Stevens almost 11 yearsDoes anyone know if like does sanitation on the string?
-
Dileep almost 9 yearsJust to be aware : this solution allows sql injection!
-
Tim Gautier almost 9 yearsif coffee.name like "%${queryStringFromUser}%" <-- This seems to sanitize the string. If it contains \ or ' it will be escaped.