Passing scala slick table in the akka actor message

851 views Asked by At

I want to send slick table as part of the akka actor message . So that the remote actor at the other end can connect to the database and can do CRUD operations on the mysql database. Am unable to get my head over the slick types and i find compiler/eclipse complaining. How can i get this done. Is it a good idea to pass slick queries as part of actor messages.

object RemoteActorMessages {
  case class Create(table: Table[A])
  case class RunQuery(query: Query[_, _, _])
  case Result(code: Int, message: String)
}

class DBActor extends Actor {
  def recieve = {
    case Create(table) => createTable(table)
    case RunQuery(query) => runQuery(query)
   case ... //so on
  }
}

def createTable(table: Table[M]): Future[A]  = Future {
   db.withSession(implicit session => tableQuery[table].ddl.create)
}

def runQuery(query: Query[_, _, _]): Future[A] = Future {
   db.withSession { implicit session => {
                                       query.run
                                     }
                                   }
}

warning: code might have some type errors.Discretion is appreciated from the viewers

I am confused about how to send results back to the sender of the messages. for example: query.list.run gives back list of model objects. So, how should i frame by Result message

1

There are 1 answers

1
Pere Villega On

I think this is a case of 'when you have a hammer everything becomes nails'. I believe this is not the right use case for the actors. A reason (not the only one) would be that DB operations are 'slow' and they would block the actor threads for a long time.

Arguably you want a service that manages the table operations, using Futures and a custom Execution Context to isolate the impact (for example, in Play is done like this). Something like:

object DBService {
   def createTable() : Future[Boolean] = ???
   ...
}

Actors should only receive commands like CreateTable that then call the corresponding method in the service.

Incidentally, this would simplify your use case as the service could know more about the table and other Slick specifics, whilst the actor would be oblivious to them.

Not the only way, but arguably simpler.