Search code examples
postgresqlscalaslick

Scala Slick inserting multiple random rows into PostgreSql database


I need to insert multiple rows (about 1 mill.) with random numbers into a PostgreSQL table. This code inserts random numbers into one column. How could i make it to insert random data to all the columns at the same time?

import slick.driver.PostgresDriver.simple._

object Main {

  class Users(tag: Tag) extends Table[(Int, String, String)](tag, "users") {
    def id = column[Int]("id")

    def username = column[String]("username")

    def miestas = column[String]("miestas")

    def * = (id, username, miestas)
  }

  def main(args: Array[String]): Unit = {

    val connectionUrl = "jdbc:postgresql://localhost/test?user=postgres&password=kurmis"

    Database.forURL(connectionUrl, driver = "org.postgresql.Driver") withSession {
      implicit session =>
        val users = TableQuery[Users]

        for (a <- 1 to 10) {
          val r = scala.util.Random
          users.map(_.username) += r.nextInt.toString

        }

        //Insert
        val r = scala.util.Random
        users.map(_.username) += r.nextInt.toString
        println("pabandom")

        }
    }
  }

Solution

  • The documentation has this example:

    people.map(p => (p.name, p.age, p.addressId)) += ("M Odersky",12345,1)
    

    And the equivalent SQL:

    insert into PERSON (NAME, AGE, ADDRESS_ID) values ('M Odersky', 12345, 1)
    

    So in your case you might write something like this:

    users.map(u => (u.username, u.miestas)) += (r.nextInt.toString, r.nextInt.toString)