nosatik
nosatik

Reputation: 53

Slick insert from select

I use scala 2.11 and slick 2.1.0 and have a compiled code:

   trait TSegmentClient { this: Profile =>

        import profile.simple._

        class SegmentClients(tag: Tag) extends Table[(Int, Long)](tag, "seg") {

            def segmentId = column[Int]("segment_id")
            def clientId = column[Long]("client_id")

            def * = (segmentId, clientId)
        }
    }

    segmentClients.insert(clientBehaviors.map(c => (1, c.clientId)))

it works.

But i need a case class like this:

case class SegmentClient(segmentId: Int, clientId: Long)

trait TSegmentClient { this: Profile =>

    import profile.simple._

    class SegmentClients(tag: Tag) extends Table[SegmentClient](tag, "seg") {

        def segmentId = column[Int]("segment_id")
        def clientId = column[Long]("client_id")

        def * = (segmentId, clientId) <> (SegmentClient.tupled, SegmentClient.unapply)
    }
}

segmentClients.insert(clientBehaviors.map(c => (1, c.clientId)))

But it doesn't compile.

(value: models.coper.datamining.SegmentClient)(implicit session: scala.slick.jdbc.JdbcBackend#SessionDef)Int cannot be applied to (scala.slick.lifted.Query[(scala.slick.lifted.Column[Int], scala.slick.lifted.Column[Long]),(Int, Long),Seq]) segmentClients.insert(clientBehaviors.map(c => (segmentId, c.clientId)))

What is wrong with my code?

Upvotes: 5

Views: 2002

Answers (2)

cvogt
cvogt

Reputation: 11270

You can do this using another projection to a tuple that is not mapped to a case class.

case class SegmentClient(segmentId: Int, clientId: Long)

trait TSegmentClient { this: Profile =>

    import profile.simple._

    class SegmentClients(tag: Tag) extends Table[SegmentClient](tag, "seg") {

        def segmentId = column[Int]("segment_id")
        def clientId = column[Long]("client_id")
        def tuple = (segmentId, clientId) 
        def * = tuple <> (SegmentClient.tupled, SegmentClient.unapply)
    }
}

segmentClients.map(_.tuple).insert(clientBehaviors.map(c => (1, c.clientId)))

Upvotes: 3

edi
edi

Reputation: 3122

The insert method on segmentClients in your second example expects a SegmentClient instance since SegmentClients is a mapped table. That's what the compiler error message is basically saying. I don't know whether there's a more idiomatic approach, since I don't know Slick too well, but as a workaround you could also use:

val behaviours = clientBehaviours.list.map(c => SegmentClient(1, c.clientId))
segmentClients.insertAll(behaviours)

Upvotes: 0

Related Questions