How can I correctly compare Options elements in Slick?

I am doing something with the Addresses, and the subpremise member (apartment / condo #) is trying to skip. I am also worried that the sub-premium is part of my unique index constraint, as it may be zero.

Failure Filter:

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))

Successful filter: (by removing the submode)

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

I have included the definitions below st if there is another factor that I missed, I hope it will be noticed.

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)
}
+6
source share
2 answers

The answer was to use the following check.

( //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)
)
+3
source

My solution that works with 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 = ?
0

Source: https://habr.com/ru/post/1545866/


All Articles