Easiest Way To Insert Scala Collection into PostgreSQL using Slick

Knoldus Inc.
Knoldus - Technical Insights
2 min readFeb 5, 2015

Few days ago, I had a scenario, in which I had to insert scala collection into postgreSQL using Slick. My postgreSQL table has some columns with data types such as Arrays, hstore etc..
I tried to do this using slick, but didn’t get success. After beating my head whole day, I found a solution.
I found a slick extension slick-pg, which supports following postgreSQL types:-

  • ARRAY
  • Date/Time
  • Enum
  • Range
  • Hstore
  • LTree
  • JSON
  • Inet/MacAddr
  • text Search
  • postgis Geometry

In this blog, I have explained how to insert Scala collection into PostgreSQL using Slick through an example. In this example, there is a student table, which has 4 columns

[code language=”sql”]CREATE EXTENSION hstore;

CREATE TABLE student (
id int,
name varchar(254) NOT NULL,
hobbies text[],
marks hstore
);
[/code]

Here hobbies is Array of String and marks is hstore(Set of key-value pair).

As suggested here https://github.com/tminglei/slick-pg , I created a trait MyPostgresDriver and integrated with PostgresDriver like this:-

[code language=”java”]

trait MyPostgresDriver extends PostgresDriver
with PgArraySupport
with PgHStoreSupport {

override lazy val Implicit = new ImplicitsPlus {}
override val simple = new SimpleQLPlus {}

trait ImplicitsPlus extends Implicits
with ArrayImplicits
with HStoreImplicits

trait SimpleQLPlus extends SimpleQL
with ImplicitsPlus
}

[/code]

Then I mapped my table like this:-

[code language=”java”]
class StudentTable(tag: Tag) extends Table[Student](tag, "student") {
def id = column[Int]("id", O.PrimaryKey)
def name = column[String]("name")
def hobbies = column[List[String]]("hobbies", O.Default(Nil))
def marks = column[Map[String, String]]("marks")

def * = (id, name, hobbies, marks) <> (Student.tupled, Student.unapply)
}

[/code]

After running command sbt run, I was able to store data in postgres.

Selection_039

For complete example, please go here https://gist.github.com/ayushmishra2005/d382801e0cb2d0df9e7c

--

--

Knoldus Inc.
Knoldus - Technical Insights

Group of smart Engineers with a Product mindset who partner with your business to drive competitive advantage | www.knoldus.com