Slick: Codegen Foreign Key Links

I am using slick 2.x codegen to generate Scala models from a database schema. However, is it possible to overcome the limitations of a foreign key to create related models, for example. if i have this circuit

CREATE TABLE people(id INT PRIMARY KEY AUTO INCREMENT, name VARCHAR(31));
CREATE TABLE dogs(name VARCHAR(31), ownerId INT FOREIGN KEY people(id));

I get the following models from slick:

case class PeopleRow(id: Int, name: String)
case class DogsRow(name: String, ownerId: Int)

But I really want:

case class PeopleRow(id: Int, name: String)
case class DogsRow(name: String, owner: PeopleRow)

or even better:

case class PeopleRow(id: Int, name: String) {
  def dogs: List[DogsRow]   // return items from dogs table that has this.id as ownerId
}

case class DogsRow(name: String, ownerId: People) {
  lazy val owner: People  // lazy on-demand or, can be a def too
}

Do I need to override slick codegen for this?

+4
source share
1 answer

Do not do it like this. One of the power of Slick Core is query writing. Although what you intend, you may be violating this power. Write inquiries instead!

implicit class PersonExtension(q: Query[Person,PersonRow]){
  def dogs = q.join(Dog).on(_.id === _.ownerId).map(_._2)
}
implicit class DogExtension(q: Query[Person,PersonRow]){
  def owner = q.join(Person).on(_.ownerId === _.id).map(_._2)
}

val personQuery = Person.filter(_.id === someId)
val person = personQuery.first
val dogsQuery = personQuery.dogs
val dogs = dogsQuery.run
val ownerQuery = dogsQuery.owner
val owner = ownerQuery.first

, , . , , . ? :

val brownDogsQuery = personQuery.dogs.filter(_.color === "brown")

, , .

:

  • Scala eXchange 2013
  • Scala User Group Berlin talk Dec, 2013
  • Scala 2014

http://slick.typesafe.com/docs/

+5

Source: https://habr.com/ru/post/1546514/


All Articles