Skip to content

Instantly share code, notes, and snippets.

@nraychaudhuri
Created July 18, 2013 04:31
Show Gist options
  • Save nraychaudhuri/6026730 to your computer and use it in GitHub Desktop.
Save nraychaudhuri/6026730 to your computer and use it in GitHub Desktop.
drive agnostic slick crud example
import scala.slick.lifted.MappedTypeMapper
import scala.slick.lifted.ColumnBase
import scala.slick.session.Session
import models._
import alltables._
//so that we dont depend on specific driver
import scala.slick.driver.BasicDriver.simple._
import scala.slick.lifted.Projection
//generic CRUD that can operate on any table with id column
class CRUD[M <: Model, T[M] <: BaseTable[M]](t: T[M]) {
def insert(entity: M)(implicit session: Session): Long = {
t.forInsert.insert(entity)
}
def insertAll1[M1 <: M](entities: M1*)(implicit session: Session): Seq[Long] = {
insertAll(entities)(session)
}
def insertAll[M1 <: M](entities: Seq[M1])(implicit session: Session): Seq[Long] = {
t.forInsert.insertAll(entities: _*)
}
def findAll(implicit session: Session): Seq[M] = q.list()
def findById(id: Long)(implicit session: Session): Option[M] = q.where(_.id === id).firstOption
def q = Query(t)
def update(id: Long, entity: M)(implicit session: Session) {
q.where(_.id === id).update(entity)
}
def delete(id: Long)(implicit session: Session): Int = {
q.where(_.id === id).delete
}
def count(implicit session: Session): Int = Query(q.length).first
}
//example tables
object alltables {
import models._
import SessionTypes._
val talks = new Talks
val speakers = new Speakers
abstract class BaseTable[T](name: String) extends Table[T](name) {
def id: Column[Long]
def forInsert = * returning id
}
class Speakers extends BaseTable[Speaker]("SPEAKERS") {
def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
def name = column[String]("name", O.NotNull)
def bio = column[String]("bio", O.NotNull)
def twitterId = column[String]("twitterId", O.NotNull)
def * = name ~ bio ~ twitterId ~ id.? <> (Speaker.apply _, Speaker.unapply _)
}
class Talks extends BaseTable[Talk]("TALKS") {
def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
def description = column[String]("description", O.NotNull)
def sessionType = column[SessionType]("sessionType", O.NotNull)
def tags = column[String]("tags", O.NotNull)
def speakerId = column[Long]("speakerId")
def speaker = foreignKey("SUP_FK", speakerId, speakers)(_.id)
def * = description ~ sessionType ~ tags ~ speakerId ~ id.? <> (Talk.apply _, Talk.unapply _)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment