Skip to content

Instantly share code, notes, and snippets.

@d6y
Created August 14, 2014 07:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save d6y/a625e98dc9c2124d4231 to your computer and use it in GitHub Desktop.
Save d6y/a625e98dc9c2124d4231 to your computer and use it in GitHub Desktop.
Slick with Reader
import scalaz._
import Scalaz._
trait Tables {
val profile: scala.slick.driver.JdbcProfile
import profile.simple._
case class Planet(name: String, id: Long=0L)
class PlanetTable(tag: Tag) extends Table[Planet](tag, "planet") {
def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
def name = column[String]("name")
def * = (name, id) <> (Planet.tupled, Planet.unapply)
}
lazy val planets = TableQuery[PlanetTable]
}
import scala.slick.driver.PostgresDriver.simple._
object Tables extends {
val profile = scala.slick.driver.PostgresDriver
} with Tables {
val db = Database.forURL("jdbc:postgresql:some-db", user="some-user", password="trustno1", driver = "org.postgresql.Driver")
}
object Main extends App {
import Tables._
// Create tables:
// db.withSession { implicit s =>
// (planets.ddl).create
// planets += Planet("Earth")
// planets += Planet("Mars")
// }
type Work[A] = Reader[Session, A]
def run[T](work: Work[T]): T =
db.withSession { work.run }
def findAll: Work[Seq[Planet]] = Reader(planets.list(_))
val result = run(findAll)
println(result)
// - vs -
def findAllRegular(implicit session: Session): Seq[Planet] =
planets.list
db.withSession { implicit session =>
val result = findAllRegular
println(result)
}
// Both produce:
// List(Planet(Earth,1), Planet(Mars,2))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment