Search code examples
scalaslickliquibase

Connecting to multiple db in scala


I'm working on a project were I'm using Hikari, Liquibase, Slick for db related purposes.

Now I would like to separate the tables into multiple dbs. How exactly do I do that, such as if I want to query something, to know exactly which db should I query and of course to be able to connect to those dbs


Solution

  • It's simple if you use play-slick ... in the examples it explains how to: https://github.com/playframework/play-slick/tree/master/samples/basic

    First you must declare the multiple configurations: https://github.com/playframework/play-slick/blob/master/samples/basic/conf/application.conf

    # Database configuration
    # ~~~~~ 
    # You can declare as many datasources as you want.
    # By convention, the default datasource is named `default`
    #
    slick.dbs.default.profile="slick.jdbc.H2Profile$"
    slick.dbs.default.db.driver="org.h2.Driver"
    slick.dbs.default.db.url="jdbc:h2:mem:play"
    slick.dbs.default.db.user=sa
    slick.dbs.default.db.password=""
    
    slick.dbs.mydb.profile="slick.jdbc.H2Profile$"
    slick.dbs.mydb.db.driver="org.h2.Driver"
    slick.dbs.mydb.db.url="jdbc:h2:mem:play"
    slick.dbs.mydb.db.user=sa
    slick.dbs.mydb.db.password=""
    

    Then use it when you inject it into your DAO (s):

    default -> https://github.com/playframework/play-slick/blob/master/samples/basic/app/dao/CatDAO.scala

    class CatDAO @Inject() (protected val dbConfigProvider: DatabaseConfigProvider)(implicit executionContext: ExecutionContext) extends HasDatabaseConfigProvider[JdbcProfile] {
      import profile.api._
    
      //...
    }
    

    mydb -> https://github.com/playframework/play-slick/blob/master/samples/basic/app/dao/DogDAO.scala

    class DogDAO @Inject() (@NamedDatabase("mydb") protected val dbConfigProvider: DatabaseConfigProvider)(implicit executionContext: ExecutionContext) extends HasDatabaseConfigProvider[JdbcProfile] {
                  import profile.api._
    
                  //...
     }
    

    If you do not use play-slick, you can look in the official documentation ... here is an example of how to declare it in the MYSCHEMA table: http://slick.lightbend.com/doc/3.3.1/schemas.html

    class Coffees(tag: Tag)
      extends Table[(String, Int, Double, Int, Int)](tag, Some("MYSCHEMA"), "COFFEES") {
      //...
    }
    

    In our case we do not have an example that we connect to multiple databases with the same model ... for that we inject it in the initialize at the beginning and inject it on demand by the selected APIKEY

    Something else that could help you:

    Assign dynamically injected database name in Play Slick

    http://gbmetzner.github.io/Multiple-DB/