You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

69 lines
1.9 KiB

package com.example.Car.slick
import javax.inject.{Inject, Singleton}
// import org.joda.time.DateTime
import slick.jdbc.JdbcProfile
import slick.jdbc.JdbcBackend.Database
import com.example.user._
import java.time.Instant
import scala.concurrent.{ExecutionContext, Future}
import com.example.user.slick.Tables
/**
* A Car DAO implemented with Slick, leveraging Slick code gen.
*
* Note that you must run "flyway/flywayMigrate" before "compile" here.
*
* @param db the slick database that this Car DAO is using internally, bound through Module.
* @param ec a CPU bound execution context. Slick manages blocking JDBC calls with its
* own internal thread pool, so Play's default execution context is fine here.
*/
@Singleton
class SlickCarDAO @Inject()(db: Database)(implicit ec: ExecutionContext) extends CarDAO with Tables {
override val profile: JdbcProfile = _root_.slick.jdbc.H2Profile
import profile.api._
private val queryById = Compiled(
(id: Rep[String]) => Cars.filter(_.id === id))
def lookup(id: String): Future[Option[Car]] = {
val f: Future[Option[CarsRow]] = db.run(queryById(id).result.headOption)
f.map(maybeRow => maybeRow.map(carsRowToCar))
}
def all: Future[Seq[Car]] = {
val f = db.run(Cars.result)
f.map(seq => seq.map(carsRowToCar))
}
def update(car: Car): Future[Int] = {
db.run(queryById(car.id).update(carToCarsRow(car)))
}
def delete(id: String): Future[Int] = {
db.run(queryById(id).delete)
}
def create(car: Car): Future[Int] = {
db.run(
Cars += carToCarsRow(car.copy(createdAt = Instant.now()))
)
}
def close(): Future[Unit] = {
Future.successful(db.close())
}
private def carToCarsRow(car: Car): CarsRow = {
CarsRow(car.id, car.model, car.createdAt, car.updatedAt)
}
private def carsRowToCar(carsRow: CarsRow): Car = {
Car(carsRow.id, carsRow.model, carsRow.createdAt, carsRow.updatedAt)
}
}