Search code examples
scalapostgisslick

Get Nearest Point with slick


I have the following case class:

case class Block(
                         
id: Option[Int] = None,
                         
blockId: Int,
                         
name: String,
                         
location: Option[Point] = None,
                         
geometry: Option[Geometry] = None,
                                           
)

In postgres i have a table SubBlock contient id : int, block_id: Int, name: String, geom_location: geography, sub_block_geom: geography

And I define a function to return a subBlock nearest of a specified point

override def getNearestSubBlock(point: Point): Future[SubBlock] = {
      
val query = sql"""SELECT sub_block_id,block_id,name,ST_AsText(geom_location),sub_block_geom from now.sub_block order by ST_Distance(geom_location, ST_MakePoint(${point.getX()}, ${point.getY()})::geography) limit 1""".as[SubBlock].head
      
db.run(query)
    
}

implicit val getSubBlock = GetResult(r => SubBlock(r.nextIntOption(), r.nextInt(), r.nextString(), Option(Location.location2Point(Location.fromWKT(r.nextString()))), Option(new WKTReader().read(r.nextString())))

And my request return the right result, but after I got « Exception in thread "main" java.lang.NullPointerException « because the sub_block_geom is null in my database, so I think that the solution is to change implicit val getSubBlock or to write query with filter, sortedBy , … and I don’t know how to do that


Solution

  • Well... I am not too sure about your problem, as a lot of required details are missing. But from what I can see, you just need to properly handle possibility of null in your getSubBlock.

    implicit val getSubBlock = GetResult(r => {
      val id = r.nextIntOption()
      val blockId = r.nextInt()
      val location: Option[Point] = r.nextStringOption().map(s => Location.location2Point(Location.fromWKT(s)))
      val geometry: Option[Geometry] = r.nextStringOption().map(s => new WKTReader().read(s)))
    
      SubBlock(id, blockId, location, geometry)
    }