Hassan Syed
Hassan Syed

Reputation: 20485

slick mapping an array of records for postgres

Could someone help me out by showing me how to map these two types :

case class forumQuote(
            index:          Int,
            startOffset:    Int,
            endOffset:      Int,
            isDirect:       Boolean,
            quotedId:       Int)
case class forumQuotes(quotes: List[forumQuote])

represented in postgres As :

CREATE TYPE forum_quote AS
(
    index           INTEGER,
    q_start_offset  INTEGER,
    q_end_offset    INTEGER,
    is_direct       BOOLEAN,
    quoted_id       INTEGER
);

Used as a array field in

CREATE TABLE forum_posts
(
...
quotes      forum_quote [],
...
)

Used in my own lifted table as :

object ForumPosts extends Table[...] {
...
def quotes = Column[forumQuotes]("forum_quotes")
...
}

Note: I prefer not see any use of JDBC arrays since I need to do some funky stuff with hstore later on (Key[String] => Value[Array[T]]) where T is a postgresql record.

Upvotes: 1

Views: 1463

Answers (1)

Hassan Syed
Hassan Syed

Reputation: 20485

FYI slick-pg will have full support for records and arrays soon.


I adapted the code from postgres extension plugin from the slick dudes. The following shows how you would go about getting type mapper for records, and arrays of records.

  object ForumQuoteMapper extends RecordMapper[ForumQuote] {
    val name = "forum_quote"
    val extractorRegex = "\\((\\d+),(\\d+),(\\d+),([t|f]),(\\d+)\\)".r
    def fnFromString = (lit: String) =>  {
      def toBool(str: String) = { str match { case "t" => true; case "f" => false}}

      lit match {
        case extractorRegex(index,startOffset,endOffset,bol,quotedId) =>
          ForumQuote(index.toInt,startOffset.toInt,endOffset.toInt,toBool(bol),quotedId.toInt)
      }}
    def fnToString = (v: ForumQuote)=>s"(${v.index}, ${v.startOffset}, ${v.endOffset}, ${v.isDirect},${v.quotedId})"
  }
  implicit val forumQuoteRecordMapper = ForumQuoteMapper.getRecordMapper
  implicit val forumQuoteArrayMapper = ForumQuoteMapper.getRecordArrayMapper

The adapted code can be found here. I'll probably find and fix tons of bugs once I start integrating it into my code :D but it passes the basic test cases as is.

Upvotes: 2

Related Questions