How to filter using inSetBind for multiple columns in Slick?

I have the following table definition (simplified):

class Houses(tag: Tag) extends Table[HouseRow](tag, "HOUSE") {
  def houseId = column[Long]("HOUSE_ID", O.NotNull, O.PrimaryKey, O.AutoInc)
  def houseName = column[String]("HOUSE_NAME", O.NotNull)
  def houseType = column[String]("HOUSE_TYPE", O.NotNull)

  def uniqueHouseName = index("UQ_HOUSE_NAME_HOUSE_TYPE", (houseName, houseType), true)

  def * = (houseId, houseName, houseType) <> (HouseRow.tupled, HouseRow.unapply)
}

val houses = TableQuery[Houses]

      

I would like to select houses that match the uniqueHouseName index set as follows.

case class HouseKey(houseName: String, houseType: String)
val houseKeys: Seq(HouseKey("name1", "type1"), HouseKey("name2", "type2"))

      

A naive inSetBind

filter would match eg. HouseRow(ID, "name1", "type2")

which is wrong. In MySql, I would do something like:

SELECT * FROM HOUSE h
WHERE(h.HOUSE_TYPE, d.HOUSE_NAME) IN
(
  SELECT 'type1' as HOUSE_TYPE, 'name1' as HOUSE_NAME
  UNION
  SELECT 'type2', 'name2'
);

      

+3


source to share


3 answers


Adapting tuxdna's answer to allow arbitrary seqs. However, this query cannot be precompiled to SQL at this time and has runtime overhead.



val filteredHouses =  
  houses.filter(h =>
    houseKeys.map(hk => h.houseName === hk.houseName && h.houseType === hk.houseType)
              .reduce(_ || _)
  )

      

+1


source


Like @cvogt's version, but not empty on empty list:

val filteredHouses = 
  houses.filter(h =>
    houseKeys.map(hk => h.houseName === hk.houseName &&
        h.houseType === hk.houseType)
      .reduceOption(_ || _).getOrElse(false: Rep[Boolean])
)

      



Tested in slick 3.1.0

+2


source


This is not a complete answer, but for only two pairs of values, you can do this:

   val filteredHouses =  for {
      h <- houses
      if (h.houseName === "name1" && h.houseType === "type1") || (
        h.houseName === "name2" && h.houseType === "type2")
    } yield h

      

0


source







All Articles