ps0604 ps0604 - 3 years ago 189
Scala Question

Assign dynamically injected database name in Play Slick

I have the following Play Slick DAO class. Note that the database configuration is a constant

. The DAO has a function
that reads a user based on its user id:

class UsersDAO @Inject()(@NamedDatabase("control0001")
protected val dbConfigProvider: DatabaseConfigProvider)
extends HasDatabaseConfigProvider[JdbcProfile] {

import driver.api._

def readUser (userid: String) = {
val users = TableQuery[UserDB]
val action = users.filter(_.userid === userid).result
val future ={
case Success(s) =>
if (s.length>0)
case Failure(e) => throw new Exception ("Failure in readUser: " + e.getMessage)

Instead of having a constant in
, I need the database to be variable. In the application, I have multiple databases (
and so on) configured in
. Depending on a variable value, I need to determine the database to be used in the DAO. All the databases are similar and have the same tables (the data in each database differs).

The following Play class calls the DAO function, but first it needs to determine the database name to be injected:

class TestSlick @Inject()(dao: UsersDAO) extends Controller {

def test(someCode: Int, userId: String) = Action { request =>

val databaseName = if (someCode == 1) "control0001" else "control0002"

// Run the method in UsersDAO accessing the database set by databaseName

val future = dao.readUser(userId) { result =>
result match {
case Some(user) => Ok(user.firstName)
case _ => Ok("user not found")

How can this be achieved in Play Slick?

Answer Source

You can try to initialize slick db object overriding default config:

val db = Database.forURL("jdbc:mysql://localhost/" + databaseName, driver="org.h2.Driver")

more information in slick docs

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download