4

I'm using slick to access database. I want to query like this:

case class Coupon(couponId: Long, shopId: String)

class Coupons(tag: Tag) extends Table[Coupon](tag, "coupons"){

  def couponId = column[Long]("coupon_id")

  def shopId = column[String]("shop_id")

  override def * = (couponId, shopId) <> (Coupon.tupled, Coupon.unapply)
}

object Coupons extends TableQuery(new Coupons(_)){

  def findCouponBy(couponId: Long, shopId: Option[String]) = {

    val s = DB.createSession()
    try {
       val q = for {
           coupon <- this.filter(c => c.couponId === couponId && 
                shopId.map(s => c.shopId === s).getOrElse(true)
        } yield coupon
      s.database.run(q.result)
    } finally s.close
  }
}

I thought this might work. However, the compiler tells me that Error:(126, -1) Play 2 Compiler: type mismatch; found : Any required: slick.lifted.Rep[?]

Problem lies on here: shopId.map(s => c.shopId === s).getOrElse(true)

I'm wondering how I can make this work.

I'm using slick 3.0.0-RC

Andrii Abramov
  • 10,019
  • 9
  • 74
  • 96
Wayne Wang
  • 163
  • 9

2 Answers2

2

Use slick.lifted.LiteralColumn(true)

Scala's type infer limitation

Andrii Abramov
  • 10,019
  • 9
  • 74
  • 96
cvogt
  • 11,260
  • 30
  • 46
  • And I was wondering that, I want to take this out as a method: `shopId.map(s => c.shopId === s).getOrElse(true)` as `def checkCondition[T](column: Rep[T], parameter:T) = { column === parameter }` Is there a way to make it through? – Wayne Wang May 07 '15 at 05:26
  • parameter: Rep[T] or maybe checkCondition[T:TypedType] or checkcondition[T:BaseTypedType] – cvogt May 07 '15 at 05:52
  • there's a little hook on the left of the answer – cvogt May 08 '15 at 15:51
1

As it is mentioned in this answer, you can use the following API since Slick 3.3.0:

def findCouponBy(couponId: Long, shopId: Option[String]) = {
  val query = 
    this
      .filter(_.couponId === couponId)
      .filterOpt(shopId){ case (table, sid) =>
        table.filter(_.shopId === sid)
      }

  db run query.result
}
Andrii Abramov
  • 10,019
  • 9
  • 74
  • 96