Search code examples
scalaakkaslickalpakka

How to insert case objects to mysql with alpakka slick connector


I'm writing some code to insert data into MySQL. I've decided to use Alpakka Slick Connector. Using that example: https://developer.lightbend.com/docs/alpakka/latest/slick.html#using-a-slick-flow-or-sink I've successfully added data to DB, but it requires me to pass strings with SQL commands to Sink. Since I have collection of case objects I need to build commands from that objects. I can add methods to generate INSERT, UPDATE and DELETE commands to case classes but maybe there is some better way to add whole collection of objects without wrapping data with SQL.


Solution

  • The alternative to using "plain SQL" is to use a "typed" insert. Here is an example using Slick.sink that is adapted from SlickSpec:

    case class User(id: Int, name: String)
    class Users(tag: Tag) extends Table[(Int, String)](tag, "USERS") {
      def id = column[Int]("ID")
      def name = column[String]("NAME")
      def * = (id, name)
    }
    
    val typedUsers = TableQuery[Users]
    
    def insertUser(user: User): DBIO[Int] = typedUsers += user
    
    val users = (1 to 40).map(i => User(i, s"Name$i")).toSet
    
    Source(users)
      .runWith(Slick.sink(parallelism = 4, insertUser))
    

    The above code inserts 40 users (using a collection of User case class instances) with a parallelism setting of four.