Common CRUD Operations Using Slick 2.0

I am trying to write a generic CRUD tag for Slick 2.0. This feature should a) provide general methods for reading / updating / deleting objects, and b) abstract data from the database. Follow this anti-aliasing example (database abstraction) and in this article (CRUD) I came up with the following (shortened) code snippet:

trait Profile { val profile: JdbcProfile } trait Crud[T <: AbstractTable[A], A] { this: Profile => import profile.simple._ val qry: TableQuery[T] def countAll()(implicit session: Session): Int = { qry.length.run } def getAll()(implicit session: Session): List[A] = { qry.list // <-- type mismatch; found: List[T#TableElementType] required: List[A] } } 

The code is invalid due to type mismatch. The return type of the 2nd function is apparently of type List[T#TableElementType] , but should be List [A]. Any ideas on how to solve the problem. Further links to further readings on common Slick 2.0 operations are also welcome.

+4
source share
1 answer

type TableElementType is abstract inside the class AbstractTable[A] . Scala is unaware of any relationship between A and TableElementType . class Table , on the other hand, defines the final type TableElementType = A , which tells Scala about this relation (and, apparently, Scala is smart enough to use the final annotation to know that the relation is even executed for the T <: Table[A] eventhough Table[A] not a co-option in A ).

Therefore, you need to use T <: Table[A] instead of T <: AbstractTable[A] . And because Table is inside the cake with the Slick box (as in the cake template), you also need to move Crud into your cake. Cakes are viral.

 trait Profile { val profile: JdbcProfile } trait CrudComponent{ this: Profile => import profile.simple._ trait Crud[T <: Table[A], A] { val qry: TableQuery[T] def countAll()(implicit session: Session): Int = { qry.length.run } def getAll()(implicit session: Session): List[A] = { qry.list // <-- works as intended } } } 
+2
source

All Articles