How to return object with scala slick after insert - scala

I'm trying to use generic insert function that would return object when inserting data using Slick.
I've tried with following code
// This works without any issues but limited to specific entity and table
def insertEmployee(employee: Employee): IO[Employee] = DB.run(db, {
def returnObj = (EmployeeTable.instance returning EmployeeTable.instance.map(_.id)).into((obj, id) => obj.copy(id = id))
returnObj += employee
})
// This doesn't work and returns error on "copy". Error: Cannot resolve symbol copy
def withReturningObj[E <: BaseEntity, T <: BaseTable[E]](query: TableQuery[T]) =
(query returning query.map(_.id)).into((obj, id) => obj.copy(id = id))
Anyone who could suggest a possible solution?

I'm guessing you haven't defined your own copy method and are trying to use the one synthesized for case classes. The problem here is that obj isn't known to be of a type that has a copy method, just that it is a BaseEntity. I've had this same issue though, as unfortunately there isn't actually a way to constrain a type parameter to be a case class (that I know of, I would LOVE to be wrong about this though). I ended up doing something equivalent to defining a withId() method in your BaseEntity for specifically this purpose.
trait BaseEntity {
val id: IdType
def withId(id: IdType): BaseEntity
}
// ...
def withReturningObj[E <: BaseEntity, T <: BaseTable[E]](query: TableQuery[T]) =
(query returning query.map(_.id)).into((obj, id) => obj.withId(id) // <-- use withId here instead of copy

Related

Scala how to pass in child class and then return the same child class type while getting it generic?

I have a method definitions like so
def batchCacheable[T: ClassTag](cacheKeys: Seq[CacheKey])(callServiceToFetchValues: Seq[CacheKey] => Try[Map[CacheKey, T]]): Try[Map[CacheKey, T]]
Where CacheKey is a trait defined as having a single method called buildCacheKey, and I have a case class that extends that trait and has a id in it as well.
trait CacheKey {
def buildCacheKey: String
}
case class IDCacheKey(id: String) extends CacheKey {
override def buildCacheKey: String = {
s"CacheKey:$stringId"
}
}
And the function that I want to use for callServiceToFetchValues needs IDCacheKey to get the Id, it looks like this.
private def getStringsFromLMS(cacheKeys: Seq[CacheKey]): Try[Map[CacheKey, String]] = {
cacheKeys.map(_ -> _.Id)
}
So that it returns a map of Keys -> Ids. The problem is that batchCacheable can only pass into it a Seq of CacheKey, but I need it to be a Seq of IDCacheKey for the Id. How can I do this?
A straightforward solution would be to do something like this:
def getStringsFromLMS(cacheKeys: Seq[CacheKey]): Try[Map[CacheKey, String]] = {
cacheKeys.collect { case k: IDCacheKey => k.id }
}
This will silently ignore everything that's not IDCacheKey. If you'd rather throw an error in case there are keys of wrong type in the input, just replace .collect with .map.
Either way, this is not the right solution. The function declared to expect CacheKey should be able to handle any instance of CacheKey, no matter what type.
At a more general level, a CacheKey that doesn't provide enough identity information to fetch the value is not very useful.
Long story short, it looks like your CacheKey trait needs an abstract id method. That would solve your problem in a natural (and "correct") way.
Alternatively, you could further parameterize batchCacheable:
def batchCacheable[T, K <: CacheKey](cacheKeys: Seq[K])(
callServiceToFetchValues: Seq[K] => Try[Map[K, T]]
): Try[Map[K, T]]
This lets you declare getStringsFromLMS to accept IDCacheKey, and still be usable with batchCacheable

Scala annotation macro only works with pre-defined classes

Note: There's an EDIT below!
Note: There's another EDIT below!
I have written a Scala annotation macro that is being passed a class and creates (or rather populates) a case object. The name of the case object is the same as the name of the passed class. More importantly, for every field of the passed class, there will be a field in the case object of the same name. The fields of the case object, however, are all of type String, and their value is the name of the type of the respective field in the passed class. Example:
// Using the annotation macro to populate a case object called `String`
#RegisterClass(classOf[String]) case object String
// The class `String` defines a field called `value` of type `char[]`.
// The case object also has a field `value`, containing `"char[]"`.
println(String.value) // Prints `"char[]"` to the console
This, however, seems to only work with pre-defined classes such as String. If I define a case class A(...) and try to do #RegisterClass(classOf[A]) case object A, I get the following error:
[info] scala.tools.reflect.ToolBoxError: reflective compilation has failed:
[info]
[info] not found: type A
What have I done wrong? The code of my macro can be found below. Also, if someone notices un-idiomatic Scala or bad practices in general, I wouldn't mind a hint. Thank you very much in advance!
class RegisterClass[T](clazz: Class[T]) extends StaticAnnotation {
def macroTransform(annottees: Any*) =
macro RegisterClass.expandImpl[T]
}
object RegisterClass {
def expandImpl[T](c: blackbox.Context)(annottees: c.Expr[Any]*) = {
import c.universe._
val clazz: Class[T] = c.prefix.tree match {
case q"new RegisterClass($clazz)" => c.eval[Class[T]](c.Expr(clazz))
case _ => c.abort(c.enclosingPosition, "RegisterClass: Annotation expects a Class[T] instance as argument.")
}
annottees.map(_.tree) match {
case List(q"case object $caseObjectName") =>
if (caseObjectName.toString != clazz.getSimpleName)
c.abort(c.enclosingPosition, "RegisterClass: Annotated case object and class T of passed Class[T] instance" +
"must have the same name.")
val clazzFields = clazz.getDeclaredFields.map(field => field.getName -> field.getType.getSimpleName).toList
val caseObjectFields = clazzFields.map(field => {
val fieldName: TermName = field._1
val fieldType: String = field._2
q"val $fieldName = $fieldType"
})
c.Expr[Any](q"case object $caseObjectName { ..$caseObjectFields }")
case _ => c.abort(c.enclosingPosition, "RegisterClass: Annotation must be applied to a case object definition.")
}
}
}
EDIT: As Eugene Burmako pointed out, the error happens because class A hasn't been compiled yet, so a java.lang.Class for it doesn't exist. I have now started a bounty of 100 StackOverflow points for everyone who as an idea how one could get this to work!
EDIT 2: Some background on the use case: As part of my bachelor thesis I am working on a Scala DSL for expressing queries for event processing systems. Those queries are traditionally expressed as strings, which induces a lot of problems. A typical query would look like that: "select A.id, B.timestamp from pattern[A -> B]". Meaning: If an event of type A occurs and after that an event of type B occurs, too, give me the id of the A event and the timestamp of the B event. The types A and B usually are simple Java classes over which I have no control. id and timestamp are fields of those classes. I would like queries of my DSL to look like that: select (A.id, B.timestamp) { /* ... * / }. This means that for every class representing an event type, e.g., A, I need a companion object -- ideally of the same name. This companion object should have the same fields as the respective class, so that I can pass its fields to the select function, like so: select (A.id, B.timestamp) { /* ... * / }. This way, if I tried to pass A.idd to the select function, it would fail at compile-time if there was no such field in the original class -- because then there would not be one in the companion object either.
This isn't an answer to your macro problem, but it could be a solution to your general problem.
If you can allow a minor change to the syntax of your DSL this might be possible without using macro's (depending on other requirements not mentioned in this question).
scala> class Select[A,B]{
| def apply[R,S](fa: A => R, fb: B => S)(body: => Unit) = ???
| }
defined class Select
scala> def select[A,B] = new Select[A,B]
select: [A, B]=> Select[A,B]
scala> class MyA { def id = 42L }
defined class MyA
scala> class MyB { def timestamp = "foo" }
defined class MyB
scala> select[A,B](_.id, _.timestamp){ /* ... */ }
scala.NotImplementedError: an implementation is missing
I use the class Select here as a means to be able to specify the types of your event classes while letting the compiler infer the result types of the functions fa and fb. If your don't need those result types you could just write it as def select[A,B](fa: A => Any, fb: B => Any)(body: => Unit) = ???.
If necessary you can still implement the select or apply method as a macro. But using this syntax, you will no longer need to generate objects with macro annotations.

Find the outer class when provided an instance of the inner class

Is there a way to get the parent class from an instance of an inner class using macros rather than run-time reflection?
I have a set of classes like this:
trait IdProvider {
type IdObject = Id.type
case class Id(underlying: Int)
}
case class SomeEntity(id: SomeEntity.Id)
object SomeEntity extends IdProvider
And some code that works with arbitrary IdProvider#Ids:
val lookup = Map[IdProvider#IdObject, Set[Operation]]
def can(operation: Operation, id: IdProvider#Id): Boolean = {
val idObject = findIdTypeFromInstance(id) // This is what I don't have
lookup.get(idObject).exists(s => s(operation))
}
Taking a leaf out of this gist by Paul P. I now have this macro:
def findIdTypeFromInstance[T <: AnyRef : c.WeakTypeTag](
c: blackbox.Context)(thing: c.Expr[T]): c.Expr[T] = {
import c.universe._
val companion = thing.actualType.typeSymbol.companion match {
case NoSymbol =>
c.abort(c.enclosingPosition, s"Instance of ${thing.actualType} has no companion object")
case sym => sym
}
def make[U: c.WeakTypeTag] = c.Expr[U](internal.gen.mkAttributedRef(companion))
make(c.WeakTypeTag(companion.typeSignature))
}
This works for simpler cases (top level case classes, classes and objects, and even nested case classes). However, when dealing with the IdProvider setup above the macro tries to generate this tree:
Select(This(TypeName("IdProvider")), TermName("Id"))
This results in an extremely long stack trace in my test, which starts with:
scala.reflect.internal.Types$TypeError: value is not a member of my.spec.MacroSpec
I have not been able to find a path from the instance or the companion (IdProvider#Id) to the parent class (in this case SomeEntity). Is there a way to get to SomeEntity or do I have to use run-time reflection?
The Id companion is basically a lazy val. You need the enclosing instance to retrieve its value because it's not a statically defined stable path.
With -Yshow-syms you can see it get added in mixin phase:
object SomeEntity
constructor SomeEntity
* method Id$lzycompute (private)
method apply (case <synthetic>)
value id
method readResolve (private <synthetic>)
method unapply (case <synthetic>)
value x$0 (<synthetic>)
* object Id (<synthetic> <stable>)
value <local SomeEntity>
* variable Id$module (private <local> <synthetic>)
The $outer field of an Id is added in explicitouter.
Is it easier just to expose the companion reference explicitly?
case class Id(underlying: Int) {
def c = Id
}
This is just a quick look; maybe there's a clever way to do it.

How to write class and tableclass mapping for slick2 instead of using case class?

I use case class to transform the class object to data for slick2 before, but current I use another play plugin, the plugin object use the case class, my class is inherent from this case class. So, I can not use case class as the scala language forbidden use case class to case class inherent.
before:
case class User()
class UserTable(tag: Tag) extends Table[User](tag, "User") {
...
def * = (...)<>(User.tupled,User.unapply)
}
it works.
But now I need to change above to below:
case class BasicProfile()
class User(...) extends BasicProfile(...){
...
def unapply(i:User):Tuple12[...]= Tuple12(...)
}
class UserTable(tag: Tag) extends Table[User](tag, "User") {
...
def * = (...)<>(User.tupled,User.unapply)
}
I do not know how to write the tupled and unapply(I am not my writing is correct or not) method like the case class template auto generated. Or you can should me other way to mapping the class to talbe by slick2.
Any one can give me an example of it?
First of all, this case class is a bad idea:
case class BasicProfile()
Case classes compare by their member values, this one doesn't have any. Also the name is not great, because we have the same name in Slick. May cause confusion.
Regarding your class
class User(...) extends BasicProfile(...){
...
def unapply(i:User):Tuple12[...]= Tuple12(...)
}
It is possible to emulate case classes yourself. Are you doing that because of the 22 field limit? FYI: Scala 2.11 supports larger case classes. We are doing what you are trying at Sport195, but there are several aspects to take care of.
apply and unapply need to be members of object User (the companion object of class User). .tupled is not a real method, but generated automatically by the Scala compiler. it turns a method like .apply that takes a list of arguments into a function that takes a single tuple of those arguments. As tuples are limited to 22 columns, so is .tupled. But you could of course auto-generated one yourself, may have to give it another name.
We are using the Slick code generator in combination with twirl template engine (uses # to insert expressions. The $ are inserted as if into the generated Scala code and evaluated, when the generated code is compiled/run.). Here are a few snippets that may help you:
Generate apply method
/** Factory for #{name} objects
#{indentN(2,entityColumns.map(c => "* #param "+c.name+" "+c.doc).mkString("\n"))}
*/
final def apply(
#{indentN(2,
entityColumns.map(c =>
colWithTypeAndDefault(c)
).mkString(",\n")
)}
) = new #{name}(#{columnsCSV})
Generate unapply method:
#{if(entityColumns.size <= 22)
s"""
/** Extractor for ${name} objects */
final def unapply(o: ${name}) = Some((${entityColumns.map(c => "o."+c.name).mkString(", ")}))
""".trim
else
""}
Trait that can be mixed into User to make it a Scala Product:
trait UserBase with Product{
// Product interface
def canEqual(that: Any): Boolean = that.isInstanceOf[#name]
def productArity: Int = #{entityColumns.size}
def productElement(n: Int): Any = Seq(#{columnsCSV})(n)
override def toString = #{name}+s"(${productIterator.toSeq.mkString(",")})"
...
case-class like .copy method
final def copy(
#{indentN(2,columnsCopy)}
): #{name} = #{name}(#{columnsCSV})
To use those classes with Slick you have several options. All are somewhat newer and not documented (well). The normal <> operator Slick goes via tuples, but that's not an option for > 22 columns. One option are the new fastpath converters. Another option is mapping via a Slick HList. No examples exist for either. Another option is going via a custom Shape, which is what we do. This will require you to define a custom shape for your User class and another class defined using Column types to mirror user within queries. Like this: http://slick.typesafe.com/doc/2.1.0/api/#scala.slick.lifted.ProductClassShape Too verbose to write by hand. We use the following template code for this:
/** class for holding the columns corresponding to #{name}
* used to identify this entity in a Slick query and map
*/
class #{name}Columns(
#{indent(
entityColumns
.map(c => s"val ${c.name}: Column[${c.exposedType}]")
.mkString(", ")
)}
) extends Product{
def canEqual(that: Any): Boolean = that.isInstanceOf[#name]
def productArity: Int = #{entityColumns.size}
def productElement(n: Int): Any = Seq(#{columnsCSV})(n)
}
/** shape for mapping #{name}Columns to #{name} */
object #{name}Implicits{
implicit object #{name}Shape extends ClassShape(
Seq(#{
entityColumns
.map(_.exposedType)
.map(t => s"implicitly[Shape[ShapeLevel.Flat, Column[$t], $t, Column[$t]]]")
.mkString(", ")
}),
vs => #{name}(#{
entityColumns
.map(_.exposedType)
.zipWithIndex
.map{ case (t,i) => s"vs($i).asInstanceOf[$t]" }
.mkString(", ")
}),
vs => new #{name}Columns(#{
entityColumns
.map(_.exposedType)
.zipWithIndex
.map{ case (t,i) => s"vs($i).asInstanceOf[Column[$t]]" }
.mkString(", ")
})
)
}
import #{name}Implicits.#{name}Shape
A few helpers we put into the Slick code generator:
val columnsCSV = entityColumns.map(_.name).mkString(", ")
val columnsCopy = entityColumns.map(c => colWithType(c)+" = "+c.name).mkString(", ")
val columnNames = entityColumns.map(_.name.toString)
def colWithType(c: Column) = s"${c.name}: ${c.exposedType}"
def colWithTypeAndDefault(c: Column) =
colWithType(c) + colDefault(c).map(" = "+_).getOrElse("")
def indentN(n:Int,code: String): String = code.split("\n").mkString("\n"+List.fill(n)(" ").mkString(""))
I know this may a bit troublesome to replicate, especially if you are new to Scala. I hope to to find the time get it into the official Slick code generator at some point.

Dependent method types and type-classes

I've got a bunch of data store type-classes that look all the same.
trait FooStore[C] {
def create(f: FooId => Foo)(c: C): Foo
// update and find methods
}
I'd like to simplify things and was hoping to use dependent method types to get something closer to
sealed trait AR {
type Id
type Type
}
sealed trait FooAR extends AR {
type Id = FooId
type Type = Foo
}
trait DataStore[C] {
def create(ar: AR)(f: ar.Id => ar.Type)(c: C): ar.Type
}
but when I try and create an instance of that as follows
case class InMemory(foos: List[Foo])
object InMemory {
lazy val InMemoryDataStore: DataStore[InMemory] = new DataStore[InMemory] {
def create(ar: AR)(f: ar.Id => ar.Type)(c: InMemory): ar.Type = sys.error("not implemented")
}
}
I get the following compile error
object creation impossible, since method create in trait DataStore of type (ar: AR)(f: ar.Id => ar.Type)(c: InMemory)ar.Type is not defined
lazy val InMemoryDataStore: DataStore[InMemory] = new DataStore[InMemory] {
^
one error found
I don't understand since that method is pretty clearly defined on the DataStore instance. What does the error mean and is this possible? If not, is there a different way to accomplish the same thing?
It compiles using the Scala-2.10-M2 milestone, some dependent method type bugs have been fixed since the 2.9 release. I'm not completely sure, but perhaps this one might have made it work.