vendredi 9 octobre 2015

case class filter criteria in Slick 3.0.3

I have a Model, corresponding Table and a Repository. In my repository, using TableQuery I want to find a model object based on some criteria (a function from model to boolean), which the repository have no control, it is injected as a parameter. E.g.

case class JournalEntryModel(id: Option[Long] = None, isDebit: Boolean, principal: Double)

class JournalEntryTable(tag: Tag) extends Table[JournalEntryModel](tag, "journal_entries") {

   def id = column[Long]("id", O.PrimaryKey, O.AutoInc)

   def isDebit = column[Boolean]("is_debit")  

   def principal = column[Double]("principal")

   def * = (id.?, isDebit, principal) <>
      (JournalEntryModel.tupled, JournalEntryModel.unapply)
}

object journalEntries extends TableQuery(new JournalEntryTable(_))

object Repository {

    def find(criteria: JournalEntryModel => Boolean): List[JournalEntryModel] = db.run {
         journalEntries.filter(je => criteria(je)).result            
    } toList
}

val credits = Repository.find(!_.isDebit && _.principal > 500.0)

How do I write a such a filter function ?

Aucun commentaire:

Enregistrer un commentaire