Skip to content

Instantly share code, notes, and snippets.

@cvogt
Last active July 1, 2016 12:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cvogt/6953558 to your computer and use it in GitHub Desktop.
Save cvogt/6953558 to your computer and use it in GitHub Desktop.
import scala.slick.driver.JdbcProfile
import scala.slick.ast.BaseTypedType
trait Profile {
val profile: JdbcProfile
}
trait TableComponent extends Profile {
import profile.simple._
trait TypedId{ def id:Long }
trait Entity[ID]{
def id : Option[ID]
}
case class AccountId( id:Long ) extends TypedId
case class Account( emal:String, id:Option[AccountId] ) extends Entity[AccountId]
abstract class PowerTable[ID <: TypedId, E <: Entity[ID]](tag:Tag, tableName: String)
extends Table[E](tag, tableName) with HasId[ID] {
}
trait HasId[ID <: TypedId] {
self: Table[_] =>
protected val idColumnName = "id"
implicit val idMapper: BaseTypedType[ID] // changed the type here
def id = column[ID](idColumnName, O.AutoInc, O.NotNull)
}
}
trait AccountTable {
self: TableComponent =>
import profile.simple._
val accountQuery = TableQuery[Accounts]
class Accounts(tag:Tag) extends PowerTable[AccountId, Account](tag, "accounts")
with HasId[AccountId] {
implicit lazy val idMapper : BaseTypedType[AccountId] = MappedColumnType.base[AccountId, Long](
i => i.id,
l => AccountId(l)
)
def create = Account.apply _
def extrator = Account.unapply _
def email = column[String]("email", O.NotNull)
def * = (email, id.?) <> ( create.tupled, extrator)
}
}
@Leammas
Copy link

Leammas commented Jul 1, 2016

In slick 3.x (dunno about 2.x) it's possible to make AccountId successor of MappedTo

 import slick.lifted.MappedTo
 case class AccountId( value:Long ) extends MappedTo[Long]

and in AccountTable write

def baseTypedType: BaseTypedType[AccountId] = implicitly[BaseTypedType[Id]]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment