如何正确比较Slick中的选项成员?

时间:2014-06-24 15:39:33

标签: scala database-design database-schema optional slick-2.0

我正在处理地址,成员 subpremise (公寓/公寓#)导致检索错过。我也担心subpremise是我唯一索引约束的一部分,因为它可以为null。

故障过滤器:

tableQuery.filter(c=> (c.longitude === r.longitude && c.latitude === r.latitude) ||
        (c.streetNumber === r.streetNumber && c.route === r.route && c.subpremise === r.subpremise && c.neighborhoodId === r.neighborhoodId))

成功过滤:(通过removung subpremise)

tableQuery.filter(c=> (c.longitude === r.longitude && c.latitude === r.latitude) ||
            (c.streetNumber === r.streetNumber && c.route === r.route && c.neighborhoodId === r.neighborhoodId)) 

我已经在下面列出了以下定义。如果还有其他因素我错过了,希望会被注意到。

case class Address(id:Option[Long],streetNumber:Short,route:String,subpremise:Option[String],neighborhoodId:Fk,latitude:Option[Double],longitude:Option[Double])

class Addresses(tag: Tag) extends Table[Address](tag, "addresses") with Logging {
  def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
  def streetNumber = column[Short]("street_number")
  def route = column[String]("route",O.NotNull)
  def subpremise = column[Option[String]]("subpremise")
  def neighborhoodId = column[Long]("neighborhood",O.NotNull)
  def latitude = column[Option[Double]]("latitude")
  def longitude = column[Option[Double]]("longitude")

  //Constraints
  def idx = index("idx_streetnum_route_subpremise_neighborhood", (streetNumber,route,subpremise,neighborhoodId), unique = true)
  def gps = index("gps", (latitude,longitude), unique = true)

  //Foreign Key
  def neighborhood = foreignKey("NEIGHBORHOOD_FK", neighborhoodId, Neighborhoods.tableQuery)(_.id)

  def * = (id.?,streetNumber,route,subpremise,neighborhoodId,latitude,longitude) <> (Address.tupled,Address.unapply)
}

2 个答案:

答案 0 :(得分:3)

答案是使用以下检查。

( //Option Scenario both are defined
  (c.subpremise.isDefined && r.subpremise.isDefined && c.subpremise === r.subpremise) ||
  //Option Scenario both are empty
  (c.subpremise.isEmpty && r.subpremise.isEmpty)
)

答案 1 :(得分:0)

我的与Slick 3.3.x兼容的解决方案

tableQuery
  .filterIf(r.subpremise.isEmpty)(_.subpremise.isEmpty) // 1. both are empty
  .filterOpt(r.subpremise)(_.subpremise === _) // 2. both are defined and equal

情况1(r.subpremise为空)对应以下SQL:

select * from addresses where subpremise is null

案例2(r.subpremise不为空):

select * from addresses where subpremise = ?