Search code examples
postgresqlscalaslick

Optimize database actions Slick 3


I have created a database with Slick. And I am trying to create schemas of tables, select some information and so on. Here is my code for schemas creation:

val createUserTable = UserTable.table.schema.create
val createTaskTable = TaskTable.table.schema.create
Await.result(db.run(DBIO.seq(Queries.createUserTable, Queries.createTaskTable)), 2 seconds)

This code works just fine but I do not want to use Await.result with every query. What I am looking for is executing them in batch at least by purpose (creation, selection and so on). I could I have created this method to pass different actions:

def executeAction[T](action: DBIO[T]) =
    Await.result(db.run(action), 2 seconds)

So I am curious how can I change it to pass some data structure which holds a sequence of queries? For example, List(createUserTable, createTaskTable)

Your help is appreciated!


Solution

  • Two ways to avoid Await for every DBIO action

    1. Create list of DBIO actions and gather them using DBIO.seq and execute.

    2. Use for-comprehension to compose all DBIO actions into one DBIO action.

    This will help you some using await again and again to wait for the result of your intermediate DBIO actions.

    In both cases, you have to wait for results in main thread (i.e stop the main thread from exiting) using Await.result at least once.