case class filter criteria in Slick 3.0.3 - scala

I have a Model, corresponding Table and a Repository. In my repository, using TableQuery I want to find a model object based on some criteria (a function from model to boolean), which the repository have no control, it is injected as a parameter. E.g.
case class JournalEntryModel(id: Option[Long] = None, isDebit: Boolean, principal: Double)
class JournalEntryTable(tag: Tag) extends Table[JournalEntryModel](tag, "journal_entries") {
def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
def isDebit = column[Boolean]("is_debit")
def principal = column[Double]("principal")
def * = (id.?, isDebit, principal) <>
(JournalEntryModel.tupled, JournalEntryModel.unapply)
}
object journalEntries extends TableQuery(new JournalEntryTable(_))
object Repository {
def find(criteria: JournalEntryModel => Boolean): List[JournalEntryModel] = db.run {
journalEntries.filter(je => criteria(je)).result
} toList
}
val credits = Repository.find(!_.isDebit && _.principal > 500.0)
How do I write a such a filter function ?

I think your question is "How do I write a function literal for JournalEntryModel => Boolean"?
If you want to do it with a literal like you have, you need to define your parameters:
// Parameter list ("model" here) is required. You also need the argument type(s).
// Here, they're inferred from the argument to "find".
val credits = Repository.find(model => !model.isDebit && model.principal > 500.0)

Related

Generic update with mapping in Slick

I'm writing a CRUD app using Slick, and I want my update queries to only update a specific set of columns and I use .map().update() for that.
I have a function that returns a tuple of fields that can be updated in my table definition (def writableFields). And I have a funciton that returns a tuple of values to write there extracted from a case class.
It works fine, but it's annoying to create a repo and write the whole update function for every table. I want to create a generic form of this function, and make my table and it's companion object to extend some trait. But I cannot come up with correct type definitions.
Slick expects output of map() to be somehow compatible with the output of update. And I don't know how to make a generic type for tuples.
Is it even possible to accomplish? Or is there an alternative way to limit code duplication? Ideally I want to avoid writing Repos at all and just either instantiate a generic class or call a generic method.
object ProjectsRepo extends BaseRepository[Projects, Project] {
protected val query = lifted.TableQuery[Projects]
def update(id: Long, c: Project): Future[Option[Project]] = {
val q = filterByIdQuery(id).map(_.writableFields)
.update(Projects.mapFormToTable(c))
(db run q).flatMap(
affected =>
if (affected > 0) {
findOneById(id)
} else {
Future(None)
}
)
}
}
class Projects(tag: Tag) extends Table[Project](tag, "projects") with IdentifiableTable[Long] {
val id = column[Long]("id", O.PrimaryKey, O.AutoInc)
val title = column[String]("title")
val slug = column[String]("slug")
val created_at = column[Timestamp]("created_at")
val updated_at = column[Timestamp]("updated_at")
def writableFields =
(
title,
slug
)
def readableFields =
(
id,
created_at,
updated_at
)
def allFields = writableFields ++ readableFields // shapeless
def * = allFields <> (Projects.mapFromTable, (_: Project) => None)
}
object Projects {
def mapFormToTable(c: Project): FormFields =
(
c.title,
c.slug
)
}

In Slick, how to filter based on a custom column properties?

I have a custom column in my Slick as follow:
class PgACL(tag: Tag) extends Table[ACL](tag, Some(schemaName), "ACL") {
def id = column[UUID]("ID", O.PrimaryKey)
def resourceSpec = column[ResourceSpec]("RESOURCE_SPEC")
def * = (id, resourceSpec) <>(ACL.tupled, ACL.unapply)
}
and the custom class:
case class ResourceSpec (val resourceType: String, val resourceId: String)
And I map them like this:
implicit val ResourceSpecMapper = MappedColumnType.base[ResourceSpec, String](
resourceSpec => resourceSpec.resourceSpecStr,
str => ResourceSpec.fromString(str)
)
I am trying to have a query which filter based on a property of the custom column, but I don't know how I can access to it. For example I want to have:
TableQuery[PgACL].filter(x => x.resourceSpec.resourceType === "XYZ")
But x.resourceSpec returns Rep[ResourceSpec] and I don't know how to get its "resourceType" property.
Any help?

Scala slick query comparison of a custom user type (enumeration) gives error

I'm trying to use Slick with a column that has a user defined type (an enumeration). All is working until I try to write a query that uses the column.
When compiling I get an error on the following method:
def findCredentials(credentialType:CredentialType)(implicit session: Session): List[Credential] = {
val query = for {
c <- credentials if c.credentialType === credentialType
} yield c
query.list
}
Here is the error:
[error] ... value === is not a member of
scala.slick.lifted.Column[models.domain.enumeration.CredentialType.CredentialType]
[error] c <- credentials if c.credentialType === credentialType
The enumeration code is here:
object CredentialType extends Enumeration {
type CredentialType = Value
val Password, Token = Value
}
The table definition is here:
case class Credential(id: Long, userId: Long, credentialType: CredentialType)
class Credentials(tag: Tag) extends Table[Credential](tag, "credential") {
implicit val credentialTypeColumnType = MappedColumnType.base[CredentialType, String](
{ c => c.toString },
{ s => CredentialType.withName(s)}
)
def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
def userId = column[Long]("user_id")
def credentialType = column[CredentialType]("type")
def * = (id, userId, credentialType) <> (Credential.tupled, Credential.unapply)
}
I've googled a number of other questions but they're either not for slick 2.x.x or do not involve Enumeration types.
My question is, do I need to define the === operator somewhere for enumeration types, or is there a simpler way using current slick 2.0.0 functionality that I'm missing?
Thanks
I think you need the implicit type mapper in scope when using the === operator. You should put the
implicit val credentialTypeColumnType = MappedColumnType.base[CredentialType, String](
{ c => c.toString },
{ s => CredentialType.withName(s)}
)
somewhere where it is visible when you are creating the query.

Scala Reflection to update a case class val

I'm using scala and slick here, and I have a baserepository which is responsible for doing the basic crud of my classes.
For a design decision, we do have updatedTime and createdTime columns all handled by the application, and not by triggers in database. Both of this fields are joda DataTime instances.
Those fields are defined in two traits called HasUpdatedAt, and HasCreatedAt, for the tables
trait HasCreatedAt {
val createdAt: Option[DateTime]
}
case class User(name:String,createdAt:Option[DateTime] = None) extends HasCreatedAt
I would like to know how can I use reflection to call the user copy method, to update the createdAt value during the database insertion method.
Edit after #vptron and #kevin-wright comments
I have a repo like this
trait BaseRepo[ID, R] {
def insert(r: R)(implicit session: Session): ID
}
I want to implement the insert just once, and there I want to createdAt to be updated, that's why I'm not using the copy method, otherwise I need to implement it everywhere I use the createdAt column.
This question was answered here to help other with this kind of problem.
I end up using this code to execute the copy method of my case classes using scala reflection.
import reflect._
import scala.reflect.runtime.universe._
import scala.reflect.runtime._
class Empty
val mirror = universe.runtimeMirror(getClass.getClassLoader)
// paramName is the parameter that I want to replacte the value
// paramValue is the new parameter value
def updateParam[R : ClassTag](r: R, paramName: String, paramValue: Any): R = {
val instanceMirror = mirror.reflect(r)
val decl = instanceMirror.symbol.asType.toType
val members = decl.members.map(method => transformMethod(method, paramName, paramValue, instanceMirror)).filter {
case _: Empty => false
case _ => true
}.toArray.reverse
val copyMethod = decl.declaration(newTermName("copy")).asMethod
val copyMethodInstance = instanceMirror.reflectMethod(copyMethod)
copyMethodInstance(members: _*).asInstanceOf[R]
}
def transformMethod(method: Symbol, paramName: String, paramValue: Any, instanceMirror: InstanceMirror) = {
val term = method.asTerm
if (term.isAccessor) {
if (term.name.toString == paramName) {
paramValue
} else instanceMirror.reflectField(term).get
} else new Empty
}
With this I can execute the copy method of my case classes, replacing a determined field value.
As comments have said, don't change a val using reflection. Would you that with a java final variable? It makes your code do really unexpected things. If you need to change the value of a val, don't use a val, use a var.
trait HasCreatedAt {
var createdAt: Option[DateTime] = None
}
case class User(name:String) extends HasCreatedAt
Although having a var in a case class may bring some unexpected behavior e.g. copy would not work as expected. This may lead to preferring not using a case class for this.
Another approach would be to make the insert method return an updated copy of the case class, e.g.:
trait HasCreatedAt {
val createdAt: Option[DateTime]
def withCreatedAt(dt:DateTime):this.type
}
case class User(name:String,createdAt:Option[DateTime] = None) extends HasCreatedAt {
def withCreatedAt(dt:DateTime) = this.copy(createdAt = Some(dt))
}
trait BaseRepo[ID, R <: HasCreatedAt] {
def insert(r: R)(implicit session: Session): (ID, R) = {
val id = ???//insert into db
(id, r.withCreatedAt(??? /*now*/))
}
}
EDIT:
Since I didn't answer your original question and you may know what you are doing I am adding a way to do this.
import scala.reflect.runtime.universe._
val user = User("aaa", None)
val m = runtimeMirror(getClass.getClassLoader)
val im = m.reflect(user)
val decl = im.symbol.asType.toType.declaration("createdAt":TermName).asTerm
val fm = im.reflectField(decl)
fm.set(??? /*now*/)
But again, please don't do this. Read this stackoveflow answer to get some insight into what it can cause (vals map to final fields).

Slick 2.0: How to convert lifted query results to a case class?

in order to implement a ReSTfull APIs stack, I need to convert data extracted from a DB to JSON format. I think that the best way is to extract data from the DB and then convert the row set to JSON using Json.toJson() passing as argument a case class after having defined a implicit serializer (writes).
Here's my case class and companion object:
package deals.db.interf.slick2
import scala.slick.driver.MySQLDriver.simple._
import play.api.libs.json.Json
case class PartnerInfo(
id: Int,
name: String,
site: String,
largeLogo: String,
smallLogo: String,
publicationSite: String
)
object PartnerInfo {
def toCaseClass( ?? ) = { // what type are the arguments to be passed?
PartnerInfo( fx(??) ) // how to transform the input types (slick) to Scala types?
}
// Notice I'm using slick 2.0.0 RC1
class PartnerInfoTable(tag: Tag) extends Table[(Int, String, String, String, String, String)](tag, "PARTNER"){
def id = column[Int]("id")
def name = column[String]("name")
def site = column[String]("site")
def largeLogo = column[String]("large_logo")
def smallLogo = column[String]("small_logo")
def publicationSite = column[String]("publication_site")
def * = (id, name, site, largeLogo, smallLogo, publicationSite)
}
val partnerInfos = TableQuery[PartnerInfoTable]
def qPartnerInfosForPuglisher(publicationSite: String) = {
for (
pi <- partnerInfos if ( pi.publicationSite == publicationSite )
) yield toCaseClass( _ ) // Pass all the table columns to toCaseClass()
}
implicit val partnerInfoWrites = Json.writes[PartnerInfo]
}
What I cannot get is how to implement the toCaseClass() method in order to transform the column types from Slick 2 to Scala types - notice the function fx() in the body of toCaseClass() is only meant to give emphasis to that.
I'm wondering if is it possible to get the Scala type from Slick column type because it is clearly passed in the table definition, but I cannot find how to get it.
Any idea?
I believe the simplest method here would be to map PartnerInfo in the table schema:
class PartnerInfoTable(tag: Tag) extends Table[PartnerInfo](tag, "PARTNER"){
def id = column[Int]("id")
def name = column[String]("name")
def site = column[String]("site")
def largeLogo = column[String]("large_logo")
def smallLogo = column[String]("small_logo")
def publicationSite = column[String]("publication_site")
def * = (id, name, site, largeLogo, smallLogo, publicationSite) <> (PartnerInfo.tupled, PartnerInfo.unapply)
}
val partnerInfos = TableQuery[PartnerInfoTable]
def qPartnerInfosForPuglisher(publicationSite: String) = {
for (
pi <- partnerInfos if ( pi.publicationSite == publicationSite )
) yield pi
}
Otherwise PartnerInfo.tupled should do the trick:
def toCaseClass(pi:(Int, String, String, String, String, String)) = PartnerInfo.tupled(pi)