-3

Can someone tell me what the best practice is for inserting records with slick 3.x?

I want a simple pattern of insert a record, and the response should be the model with the updating primary key value.

case class User(int: Int, name: String, email: String)

I want to do the following:

  1. Insert a new record
  2. Return the model (User) with the updating PK value for the id property
  3. Throw an exception if the insert failed, which I believe is when the insert returns less than 0 right?

I am using postgresql if that matters.

The docs have this:

val userWithId =
  (users returning users.map(_.id)
         into ((user,id) => user.copy(id=Some(id)))
  ) += User(None, "Stefan", "Zeiger")

Is there a helper function that I could use in my entire DB layer that will also return an exception if the insert failed? i.e. if it is successful, return the user with Id otherwise throw an exception.

cool breeze
  • 4,461
  • 5
  • 38
  • 67
  • 4
    Have you tried reading the [documentation](http://slick.typesafe.com/doc/3.1.1/queries.html#inserting) already? – hasumedic Feb 22 '16 at 16:22
  • Yes, but they don't have a concrete example of an insert, with updating the database, and throwing an exception. There should be a best-practise for this instead of everyone writing their own. – cool breeze Feb 22 '16 at 17:52
  • This has already been answered in the following question: http://stackoverflow.com/questions/27080868/how-to-catch-slick-postgres-exceptions-for-duplicate-key-value-violations – Laurence Bird Feb 24 '16 at 20:17
  • @LaurenceBird no that is not slick 3.x – cool breeze Feb 24 '16 at 21:13

1 Answers1

2

As @Laurece Bird mentioned, there's an answer already. Despite the fact that is aimed to slick 2.x, it should work on slick 3.x

Have you tried? Are you having any error?

Still, the logic it's the same, try returning something, and embrace the method on a java try/catch or in a scala Try

Community
  • 1
  • 1
pedrorijo91
  • 7,635
  • 9
  • 44
  • 82
  • i'm looking for a generic solution I could use everywhere, like a helper method that will do this. – cool breeze Feb 29 '16 at 15:54
  • I don't think it exists. You can raise an issue on the [github repo](https://github.com/slick/slick) so they may consider it in future releases. Else, just if you create... – pedrorijo91 Feb 29 '16 at 16:02