PostgreSQL
 sql >> Base de Dados >  >> RDS >> PostgreSQL

Operações CRUD Genéricas Slick 2.0


Consegui fazer funcionar, este é o meu traço genérico:
import scala.slick.driver.PostgresDriver
import scala.slick.driver.PostgresDriver.simple._
import path.to.RichTable

trait PostgresGeneric[T <: RichTable[A], A] {

  val tableReference: TableQuery[T]

  def insert(row: T#TableElementType)(implicit s: Session) = 
    tableReference.insert(row)

  def insertAndGetId(row: T#TableElementType)(implicit s: Session) = 
    (tableReference returning tableReference.map(_.id)) += row

  def deleteById(id: Long)(implicit s: Session): Boolean = 
    tableReference.filter(_.id === id).delete == 1

  def updateById(id: Long, row: T#TableElementType)(implicit s: Session): Boolean = 
    tableReference.filter(_.id === id).update(row) == 1

  def selectById(id: Long)(implicit s: Session): Option[T#TableElementType] = 
    tableReference.filter(_.id === id).firstOption

  def existsById(id: Long)(implicit s: Session): Boolean = {
    (for {
      row <- tableReference
      if row.id === id
    } yield row).firstOption.isDefined
  }
}

Onde RichTable é uma classe abstrata com um campo id, isso, com a restrição de limite superior, é útil para obter o campo id de T#TableElementType (veja isto para mais informações):
import scala.slick.driver.PostgresDriver.simple._
import scala.slick.jdbc.{GetResult => GR}

abstract class RichTable[T](tag: Tag, name: String) extends Table[T](tag, name) {
  val id: Column[Long] = column[Long]("id", O.PrimaryKey, O.AutoInc)
}

E minha tabela de campanha agora está assim:
import scala.slick.driver.PostgresDriver.simple._
import scala.slick.jdbc.{GetResult => GR}
import scala.slick.lifted.TableQuery

case class CampaignRow(id: Long, name: Option[String])

class Campaign(tag: Tag) extends RichTable[CampaignRow](tag, "campaign") {
  def * = (id, name) <>(CampaignRow.tupled, CampaignRow.unapply)

  def ? = (id.?, name).shaped.<>({
    r => import r._; _1.map(_ => CampaignRow.tupled((_1.get, _2)))
  }, (_: Any) => throw new Exception("Inserting into ? projection not supported."))

  override val id: Column[Long] = column[Long]("id", O.AutoInc, O.PrimaryKey)
  val name: Column[Option[String]] = column[Option[String]]("name")
}

O modelo que implementa a característica genérica é assim:
 object CampaignModel extends PostgresGeneric[Campaign, CampaignRow] {

   override val tableReference: PostgresDriver.simple.TableQuery[Tables.Campaign] = 
     TableQuery[Campaign]

   def insertCampaign(row: CampaignRow) = {
     insert(CampaignRow(0, "test"))
   }
 }