Last active
December 23, 2015 15:29
-
-
Save milieu/6656192 to your computer and use it in GitHub Desktop.
A modified version of [this DRY Slick trait](http://logician.eu/2013/07/08/crud-trait-for-slick-models-in-the-play-framework/) that incorporates autoincrementing ids and Guice injection for abstracting out database drivers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package models | |
//import scala.slick.driver.PostgresDriver.simple._ | |
import com.google.inject.Inject | |
import controllers.DatabaseComponent | |
import play.api.Play.current | |
import play.api.db.DB | |
class Wrapper @Inject() (dc: DatabaseComponent) { | |
val database = dc | |
/** | |
* All Slick tables that implement CUD and have an auto-incrementing id need to implement this trait. | |
*/ | |
trait auto[T] { | |
def forInsert: database.Driver.KeysInsertInvoker[T, Int] | |
} | |
/** | |
* Create, update, and delete abstractions for auto-incrementing Slick tables. | |
*/ | |
trait CUD[I <: AnyRef] { self: database.Driver.simple.Table[I] with auto[I] => | |
import database.Driver.simple._ | |
def id: Column[Int] | |
def * : scala.slick.lifted.ColumnBase[I] | |
def db = database.Driver.simple.Database.forDataSource(DB.getDataSource()) | |
def insert(entity: I) = { | |
db withSession { implicit session: Session => | |
self.forInsert insert (entity) | |
} | |
} | |
def insertAll(entities: Seq[I]) { | |
db withSession { implicit session: Session => // the lack of implicit session here doesn't bug out Eclipse: why? | |
self.insertAll(entities) | |
} | |
} | |
def update(id: Int, entity: I) { | |
db withSession { implicit session: Session => | |
tableQueryToUpdateInvoker( | |
tableToQuery(this).where(_.id === id)).update(entity) | |
} | |
} | |
def delete(id: Int) { | |
db withSession { implicit session: Session => | |
queryToDeleteInvoker( | |
tableToQuery(this).where(_.id === id)).delete | |
} | |
} | |
def count = db withSession { implicit session: Session => | |
Query(tableToQuery(this).length).first | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment