Skip to content

Starting with Slick – Part 1

December 6, 2012

I have chosen slick to query a PostgreSql database for a scala + play 2 project I’m working on. Also, because I needed something stable I’ve chosen lifted embedding api because it’s stable (direct embedding is still in experimental state).

In order to help others (documentation has some limitations) I will post here some code I’ve written.

To map a specific table which looks like:

CREATE TABLE geo_location
(
 latitude double precision,
 longitude double precision NOT NULL,
 altitude double precision NOT NULL,
 id serial NOT NULL,
 CONSTRAINT geo_location_pkey PRIMARY KEY (id)
)

we have to write a mapper class:

import scala.slick.driver.PostgresDriver.simple._

case class GeoLocation(id: Option[Int], latitude: Option[Double], longitude: Double, altitude: Double)

/**
 * Define table "geo_location".
 */
object GeoLocations extends RichTable[GeoLocation]("geo_location") {
  def latitude = column[Double]("latitude")
  def longitude = column[Double]("longitude")
  def altitude = column[Double]("altitude")

   def * = id.? ~ latitude.? ~ longitude ~ altitude <> (GeoLocation, GeoLocation.unapply _)
  def forInsert = latitude.? ~ longitude ~ altitude <> ({ (lat, long, alt) => GeoLocation(None, lat, long, alt) },
    { g: GeoLocation => Some((g.latitude, g.longitude, g.altitude)) })

}

As you see, I had to declare id as Optional and also a project named forInsert (consider it a hack in order to force PostgreSql driver to auto-inc our id for the follwing case, an INSERT statement):

GeoLocations.forInsert.insert(GeoLocation(None, 22.23, 25.36, 22.22))

Also, RichTable is an abstract class in order to not declare ids for each Table I have but just extend this::

abstract class RichTable[T](name: String) extends Table[T](name) {
  def id = column[Int]("id", O.PrimaryKey, O.AutoInc)

  val byId = createFinderBy(_.id)
}
Advertisements

From → Scala, Slick

One Comment
  1. Very nice post. It would be very nice to see other posts like this.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: