sam-w
sam-w

Reputation: 7687

Where can I define methods to be called on Tables?

(I'm a complete beginner with Scala and Slick, so code review of any kind is appreciated)

I have the following class and Slick Table defined:

case class Foo(title: String, description: String, id: Int = 0)

class FooTable(tag: Tag) extends Table[Foo](tag, "FOO") {

  def id = column[Int]("ID", O.PrimaryKey, O.AutoInc)
  def title = column[String]("TITLE", O.NotNull)
  def description = column[String]("DESCRIPTION")

  def * = (title, description, id) <> (Foo.tupled, Foo.unapply)
}

I want to add a method which will return a List of Foos which match a specified title. Something like this:

def findByTitle(title: String) = DB.withSession { implicit s: Session =>
  <FooTable TableQuery>.filter(_.title === title)
}

I'd then be able to use the method like this:

val foos = TableQuery[FooTable]
DB.withSession { implicit s: Session =>
  val anId = foos.findByTitle("bar")
}

How/where can I add a method which can act on a TableQuery for a particular Table? Is this even the correct way to be arranging my application?

Upvotes: 1

Views: 101

Answers (2)

cvogt
cvogt

Reputation: 11270

implicit class FooTableExtensions(q: Query[FooTable,Foo]){
  def findByTitle(t: String) = q.filter(_.title === t)
}

foos.findByTitle("Bar")

See Scala eXchange 2013 talk our website.

For pre-compiled queries it may be useful to have a DAO though, where you can cache the pre-compiled query. See Scala Days 2013 talk. Syntax changed since then though. Check the manual for Compiled.

Upvotes: 2

johanandren
johanandren

Reputation: 11479

I think what you want is to introduce a DAO (data access object), depending on your needs you could let the companion object of the FooTable class be the DAO which would let you call FooTable.findByTitle() from the rest of your codebase.

Upvotes: 1

Related Questions